Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
de0cf7dd77 |
No files matched your search
@@ -1,70 +1,42 @@
|
||||
# Define directories
|
||||
SRC_DIR := source
|
||||
OBJ_DIR := obj
|
||||
FMT_DIR := external/fmt
|
||||
|
||||
CXX := clang++
|
||||
EXE ?= Eleanor
|
||||
EVALFILE := ./nnue.bin
|
||||
|
||||
ifeq ($(OS),Windows_NT)
|
||||
UNAME_S := Windows
|
||||
EXE_EXT := .exe
|
||||
MKDIR := mkdir
|
||||
RM := rmdir /s /q
|
||||
DEL := del /q
|
||||
PLATFORM := windows
|
||||
else
|
||||
UNAME_S := $(shell uname -s)
|
||||
ARCH := $(shell uname -m)
|
||||
EXE_EXT :=
|
||||
MKDIR := mkdir -p
|
||||
RM := rm -rf
|
||||
DEL := rm -f
|
||||
ifeq ($(UNAME_S),Darwin)
|
||||
PLATFORM := mac
|
||||
else
|
||||
PLATFORM := unix
|
||||
endif
|
||||
endif
|
||||
|
||||
CXXFLAGS := -std=c++20 -O3 -flto -Wall
|
||||
LDFLAGS := -O3 -flto
|
||||
|
||||
ifeq ($(PLATFORM),mac)
|
||||
ifeq ($(ARCH),arm64)
|
||||
ARCH_FLAGS :=
|
||||
else
|
||||
ARCH_FLAGS := -march=native
|
||||
endif
|
||||
else
|
||||
ARCH_FLAGS := -march=native
|
||||
LDFLAGS += -fuse-ld=lld -static
|
||||
endif
|
||||
|
||||
CXXFLAGS += $(ARCH_FLAGS)
|
||||
LDFLAGS += $(ARCH_FLAGS)
|
||||
|
||||
MAKEFLAGS += -j
|
||||
|
||||
# Source and object files
|
||||
SRCS := $(wildcard $(SRC_DIR)/*.cpp)
|
||||
OBJS := $(patsubst $(SRC_DIR)/%.cpp, $(OBJ_DIR)/%.o, $(SRCS))
|
||||
|
||||
FMT_SRC := $(FMT_DIR)/format.cc
|
||||
FMT_OBJ := $(OBJ_DIR)/format.o
|
||||
|
||||
$(EXE)$(EXE_EXT): $(OBJS) $(FMT_OBJ)
|
||||
$(CXX) $(CXXFLAGS) -DEVALFILE=\"$(EVALFILE)\" $^ -o $@ $(LDFLAGS)
|
||||
# Final binary
|
||||
$(EXE)$(EXE_EXT): $(OBJS)
|
||||
$(CXX) -DEVALFILE=\"$(EVALFILE)\" $^ ./external/fmt/format.cc -o $@ -O3 -fuse-ld=lld -march=native -flto -static
|
||||
|
||||
# Compile .cpp -> .o
|
||||
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp | $(OBJ_DIR)
|
||||
$(CXX) $(CXXFLAGS) -c -o $@ $<
|
||||
|
||||
$(FMT_OBJ): $(FMT_SRC) | $(OBJ_DIR)
|
||||
$(CXX) $(CXXFLAGS) -c -o $@ $<
|
||||
$(CXX) -std=c++20 -c -o $@ $< -O3 -march=native -flto -static
|
||||
|
||||
# Create object directory
|
||||
$(OBJ_DIR):
|
||||
$(MKDIR) $(OBJ_DIR)
|
||||
|
||||
# Clean up and rebuild
|
||||
.PHONY: clean
|
||||
clean:
|
||||
ifeq ($(OS),Windows_NT)
|
||||
|
||||
Vendored
-23
@@ -1,23 +0,0 @@
|
||||
// Stolen from Ciekce - Stormphrax
|
||||
#pragma once
|
||||
|
||||
#include <array>
|
||||
#include <stdlib.h>
|
||||
|
||||
namespace internal
|
||||
{
|
||||
template <typename T, size_t N, size_t ... Ns>
|
||||
struct MultiArrayImpl
|
||||
{
|
||||
using Type = std::array<typename MultiArrayImpl<T, Ns...>::Type, N>;
|
||||
};
|
||||
|
||||
template <typename T, size_t N>
|
||||
struct MultiArrayImpl<T, N>
|
||||
{
|
||||
using Type = std::array<T, N>;
|
||||
};
|
||||
}
|
||||
|
||||
template <typename T, size_t ... Ns>
|
||||
using MultiArray = typename internal::MultiArrayImpl<T, Ns...>::Type;
|
||||
@@ -1,7 +1,6 @@
|
||||
#include <cstring>
|
||||
#include <string_view>
|
||||
#include <array>
|
||||
#include <memory>
|
||||
#include "benchmark.h"
|
||||
#include "search.h"
|
||||
#include "stopwatch.h"
|
||||
@@ -63,14 +62,15 @@ constexpr std::array<std::string_view, 50> fenPositions = {
|
||||
|
||||
void RunBenchmark() {
|
||||
Board board;
|
||||
int depth = BENCH_DEPTH;
|
||||
|
||||
auto ctx = std::make_unique<SearchContext>();
|
||||
SearchContext ctx;
|
||||
|
||||
Stopwatch sw;
|
||||
for (int i = 0; i < fenPositions.size(); i++) {
|
||||
board.SetByFen(fenPositions[i]);
|
||||
SearchPosition<bench>(board, SearchParams(), ctx.get());
|
||||
SearchPosition<bench>(board, SearchParams(), ctx);
|
||||
}
|
||||
|
||||
std::cout << ctx->nodes << " nodes " << int(ctx->nodes/sw.GetElapsedSec()) << " nps" << std::endl;
|
||||
std::cout << ctx.nodes << " nodes " << int(ctx.nodes/sw.GetElapsedSec()) << " nps" << std::endl;
|
||||
}
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
#pragma once
|
||||
#include <string>
|
||||
|
||||
constexpr int BENCH_DEPTH = 13;
|
||||
constexpr int BENCH_DEPTH = 11;
|
||||
|
||||
void RunBenchmark();
|
||||
+36
-125
@@ -2,7 +2,6 @@
|
||||
#include <fstream>
|
||||
#include <iomanip>
|
||||
#include <thread>
|
||||
#include <tuple>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
#include "datagen.h"
|
||||
@@ -11,11 +10,8 @@
|
||||
#include "movegen.h"
|
||||
#include "utils.h"
|
||||
|
||||
// OS-dependent threading includes
|
||||
#ifdef _WIN32
|
||||
#include <windows.h>
|
||||
#else
|
||||
#include <pthread.h>
|
||||
#include <windows.h>
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
@@ -34,21 +30,21 @@ static void ShowCursor() {
|
||||
cursorInfo.bVisible = TRUE;
|
||||
SetConsoleCursorInfo(hConsole, &cursorInfo);
|
||||
}
|
||||
#else
|
||||
static void HideCursor() {
|
||||
#endif
|
||||
|
||||
static void HideCursorLinux() {
|
||||
std::cout << "\033[?25l";
|
||||
}
|
||||
|
||||
static void ShowCursor() {
|
||||
static void ShowCursorLinux() {
|
||||
std::cout << "\033[?25h";
|
||||
}
|
||||
#endif
|
||||
|
||||
namespace DATAGEN {
|
||||
|
||||
static std::mutex fileOpenMutex;
|
||||
|
||||
static bool IsGameOver(Board &board, SEARCH::SearchContext* ctx) {
|
||||
static bool IsGameOver(Board &board, SEARCH::SearchContext& ctx) {
|
||||
if (SEARCH::IsDraw(board, ctx)) return true;
|
||||
|
||||
int moveSeen = 0;
|
||||
@@ -58,19 +54,19 @@ static bool IsGameOver(Board &board, SEARCH::SearchContext* ctx) {
|
||||
bool isLegal = copy.MakeMove(board.moveList[i]);
|
||||
|
||||
if (!isLegal) continue;
|
||||
moveSeen++;
|
||||
moveSeen++;
|
||||
}
|
||||
|
||||
return moveSeen == 0;
|
||||
}
|
||||
|
||||
static void PlayRandMoves(Board &board, SEARCH::SearchContext* ctx) {
|
||||
static void PlayRandMoves(Board &board, SEARCH::SearchContext& ctx) {
|
||||
std::random_device dev;
|
||||
std::mt19937_64 rng(dev());
|
||||
|
||||
std::uniform_int_distribution<int> moveDist(0, 1);
|
||||
bool plusOne = moveDist(rng);
|
||||
|
||||
|
||||
for (int count = 0; count < RAND_MOVES + plusOne; count++) {
|
||||
MOVEGEN::GenerateMoves<All>(board);
|
||||
|
||||
@@ -81,7 +77,7 @@ static void PlayRandMoves(Board &board, SEARCH::SearchContext* ctx) {
|
||||
count--;
|
||||
continue;
|
||||
}
|
||||
ctx->positionHistory[board.positionIndex] = board.hashKey;
|
||||
ctx.positionHistory[board.positionIndex] = board.hashKey;
|
||||
MOVEGEN::GenerateMoves<All>(board);
|
||||
if (IsGameOver(board, ctx)) break;
|
||||
}
|
||||
@@ -131,32 +127,13 @@ static void PlayGames(int id, std::atomic<int>& positions, std::atomic<bool>& st
|
||||
exit(-1);
|
||||
}
|
||||
|
||||
const int evenityMargin = 200;
|
||||
|
||||
/*
|
||||
const int winAdjMoveCount = 3;
|
||||
const int winAdjScore = 400;
|
||||
|
||||
const int drawAdjMoveNumber = 40;
|
||||
const int drawAdjMoveCount = 8;
|
||||
const int drawAdjScore = 10;
|
||||
*/
|
||||
|
||||
while (!stopFlag) {
|
||||
Board board;
|
||||
auto ctx = std::make_unique<SEARCH::SearchContext>();
|
||||
|
||||
PlayRandMoves(board, ctx.get());
|
||||
if (IsGameOver(board, ctx.get())) continue;
|
||||
|
||||
// Filter out games with a highly uneven starting position
|
||||
const int startingScore = SEARCH::SearchPosition<SEARCH::datagen>(board, SearchParams(), ctx.get()).score;
|
||||
|
||||
if (std::abs(startingScore) >= evenityMargin) continue;
|
||||
|
||||
ctx->nodes = 0;
|
||||
|
||||
Game game;
|
||||
Board board;
|
||||
SEARCH::SearchContext ctx;
|
||||
PlayRandMoves(board, ctx);
|
||||
if (IsGameOver(board, ctx)) continue;
|
||||
|
||||
Board startpos = board;
|
||||
|
||||
SearchResults safeResults;
|
||||
@@ -164,25 +141,24 @@ static void PlayGames(int id, std::atomic<int>& positions, std::atomic<bool>& st
|
||||
int staticEval = UTILS::ConvertToWhiteRelative(board, NNUE::net.Evaluate(board));
|
||||
int wdl = 1;
|
||||
|
||||
while (!IsGameOver(board, ctx.get())) {
|
||||
SearchResults results = SEARCH::SearchPosition<SEARCH::datagen>(board, SearchParams(), ctx.get());
|
||||
while (!IsGameOver(board, ctx)) {
|
||||
SearchResults results = SEARCH::SearchPosition<SEARCH::datagen>(board, SearchParams(), ctx);
|
||||
|
||||
if (!results.bestMove) break;
|
||||
safeResults = results;
|
||||
|
||||
|
||||
game.moves.emplace_back(ScoredMove(results.bestMove.ConvertToViriMoveFormat(),
|
||||
UTILS::ConvertToWhiteRelative(board, results.score)));
|
||||
|
||||
board.MakeMove(results.bestMove);
|
||||
ctx->positionHistory[board.positionIndex] = board.hashKey;
|
||||
ctx.positionHistory[board.positionIndex] = board.hashKey;
|
||||
|
||||
positions++;
|
||||
|
||||
|
||||
MOVEGEN::GenerateMoves<All>(board);
|
||||
}
|
||||
|
||||
if (!SEARCH::IsDraw(board, ctx.get())) {
|
||||
if (!SEARCH::IsDraw(board, ctx)) {
|
||||
wdl = board.sideToMove ? 2 : 0;
|
||||
}
|
||||
|
||||
@@ -202,62 +178,24 @@ static void PlayGames(int id, std::atomic<int>& positions, std::atomic<bool>& st
|
||||
}
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
// Windows implementation using std::thread
|
||||
static void CreateWorkerThread(int id, std::atomic<int>& positions, std::atomic<bool>& stopFlag, std::vector<std::thread>& threads) {
|
||||
threads.emplace_back(PlayGames, id, std::ref(positions), std::ref(stopFlag));
|
||||
}
|
||||
#else
|
||||
// Unix/Linux implementation using pthread
|
||||
static void* ThreadFunc(void* 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;
|
||||
}
|
||||
#endif
|
||||
|
||||
void Run(int targetPositions, int threads) {
|
||||
#ifdef _WIN32
|
||||
system("cls");
|
||||
HideCursor();
|
||||
#else
|
||||
std::cout << "\033[2J\033[H";
|
||||
HideCursor();
|
||||
HideCursorLinux();
|
||||
#endif
|
||||
|
||||
std::atomic<int> positions = 0;
|
||||
std::atomic<bool> stopFlag = false;
|
||||
|
||||
#ifdef _WIN32
|
||||
// Windows implementation using std::thread
|
||||
std::vector<std::thread> workerThreads;
|
||||
|
||||
for (int i = 0; i < threads - 1; ++i) {
|
||||
CreateWorkerThread(i, positions, stopFlag, workerThreads);
|
||||
|
||||
// Start N-1 threads
|
||||
for (int i = 0; i < threads-1; i++) {
|
||||
workerThreads.emplace_back(std::thread(PlayGames, i, std::ref(positions), std::ref(stopFlag)));
|
||||
}
|
||||
#else
|
||||
// Unix/Linux implementation using pthread
|
||||
std::vector<pthread_t> workerThreads;
|
||||
|
||||
for (int i = 0; i < threads - 1; ++i) {
|
||||
pthread_attr_t attr;
|
||||
pthread_attr_init(&attr);
|
||||
pthread_attr_setstacksize(&attr, 8 * 1024 * 1024); // 8 MB stack
|
||||
|
||||
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) {
|
||||
workerThreads.push_back(thread);
|
||||
} else {
|
||||
std::cerr << "Failed to create thread " << i << "\n";
|
||||
delete args;
|
||||
}
|
||||
|
||||
pthread_attr_destroy(&attr);
|
||||
}
|
||||
#endif
|
||||
|
||||
Stopwatch sw;
|
||||
while (positions < targetPositions) {
|
||||
@@ -265,28 +203,22 @@ void Run(int targetPositions, int threads) {
|
||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||
}
|
||||
|
||||
|
||||
PrintProgress(positions, targetPositions, sw, threads);
|
||||
|
||||
stopFlag = true;
|
||||
|
||||
#ifdef _WIN32
|
||||
// Join Windows threads
|
||||
for (std::thread& thread : workerThreads) {
|
||||
for (auto& thread : workerThreads) {
|
||||
if (thread.joinable()) {
|
||||
thread.join();
|
||||
}
|
||||
}
|
||||
#else
|
||||
// Join pthread threads
|
||||
for (pthread_t& thread : workerThreads) {
|
||||
pthread_join(thread, nullptr);
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
|
||||
#ifdef _WIN32
|
||||
ShowCursor();
|
||||
#else
|
||||
ShowCursor();
|
||||
ShowCursorLinux();
|
||||
#endif
|
||||
}
|
||||
|
||||
@@ -311,6 +243,9 @@ void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int
|
||||
lastElapsed = elapsed;
|
||||
}
|
||||
|
||||
int positionsInThousands = static_cast<int>(round(positions / 1000.0));
|
||||
int targetInThousands = static_cast<int>(round(targetPositions / 1000.0));
|
||||
|
||||
std::cout << "\033[H";
|
||||
|
||||
int width = 60;
|
||||
@@ -326,7 +261,7 @@ void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int
|
||||
std::cout << std::fixed << std::setprecision(0);
|
||||
|
||||
std::ostringstream datagenTextStream;
|
||||
datagenTextStream << std::fixed << std::setprecision(2)
|
||||
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 - datagenText.length()) / 2;
|
||||
@@ -350,31 +285,6 @@ void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int
|
||||
|
||||
std::cout << std::endl;
|
||||
|
||||
double remainingTime = 0.0;
|
||||
if (positions > 0 && elapsed > 0.0) {
|
||||
double positionsPerSec = positions / elapsed;
|
||||
remainingTime = (targetPositions - positions) / positionsPerSec;
|
||||
}
|
||||
|
||||
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 - remainingTimeText.length()) / 2;
|
||||
std::cout << COLOR_SECTION << std::setw(remainingPadding + remainingTimeText.length())
|
||||
<< remainingTimeText << COLOR_RESET << std::endl;
|
||||
|
||||
std::cout << std::endl;
|
||||
|
||||
int barWidth = 50;
|
||||
double progress = (double)positions / targetPositions;
|
||||
int pos = (int)(progress * barWidth);
|
||||
@@ -399,4 +309,5 @@ void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int
|
||||
std::cout << std::endl;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
@@ -299,6 +299,120 @@ Bitboard getPawnPushes(int square, bool color, Bitboard &occupancy) {
|
||||
return pushes;
|
||||
}
|
||||
|
||||
// Returns the direction to target from square
|
||||
static int GetDirection(int square, int target) {
|
||||
int rankDiff = (target / 8) - (square / 8);
|
||||
int fileDiff = (target % 8) - (square % 8);
|
||||
|
||||
// Main directions
|
||||
if (rankDiff == 0 && fileDiff < 0) {
|
||||
return west;
|
||||
} else if (rankDiff == 0 && fileDiff > 0) {
|
||||
return east;
|
||||
} else if (rankDiff < 0 && fileDiff == 0) {
|
||||
return south;
|
||||
} else if (rankDiff > 0 && fileDiff == 0) {
|
||||
return north;
|
||||
}
|
||||
|
||||
// Diagonals
|
||||
if (abs(rankDiff) == abs(fileDiff)) {
|
||||
if (rankDiff < 0 && fileDiff < 0) {
|
||||
return soWe;
|
||||
} else if (rankDiff < 0 && fileDiff > 0) {
|
||||
return soEa;
|
||||
} else if (rankDiff > 0 && fileDiff < 0) {
|
||||
return noWe;
|
||||
} else if (rankDiff > 0 && fileDiff > 0) {
|
||||
return noEa;
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Returns a bitboard of the squares from attacker to target
|
||||
static Bitboard SliderRayToSquare(int attacker, int target) {
|
||||
Bitboard ray;
|
||||
int direction = GetDirection(attacker, target);
|
||||
|
||||
if (direction) {
|
||||
while (attacker != target) {
|
||||
ray.SetBit(attacker);
|
||||
attacker += direction;
|
||||
}
|
||||
ray.SetBit(target);
|
||||
}
|
||||
|
||||
return ray;
|
||||
}
|
||||
|
||||
static Bitboard GetPinningRay(Board &board, int square, int direction) {
|
||||
Bitboard ray;
|
||||
int currentSquare = (board.pieces[King] & board.colors[board.sideToMove]).getLS1BIndex();
|
||||
int previousRank = currentSquare / 8;
|
||||
|
||||
currentSquare += direction;
|
||||
while (currentSquare < 64 && currentSquare >= 0) {
|
||||
int currentRank = currentSquare / 8;
|
||||
|
||||
int difference = abs(currentRank - previousRank);
|
||||
|
||||
if ((abs(direction) == 7 || abs(direction) == 9)
|
||||
&& difference != 1) {
|
||||
break;
|
||||
} else if (abs(direction) == 1 && difference) {
|
||||
break;
|
||||
}
|
||||
previousRank = currentRank;
|
||||
|
||||
ray.SetBit(currentSquare);
|
||||
if (board.occupied.IsSet(currentSquare)) {
|
||||
if (currentSquare == square) {
|
||||
currentSquare += direction;
|
||||
continue;
|
||||
}
|
||||
int attackerType = board.GetPieceType(currentSquare);
|
||||
int attackerColor = board.GetPieceColor(currentSquare);
|
||||
|
||||
if (attackerColor != board.sideToMove) {
|
||||
// Pinned by rook or queen
|
||||
if (abs(direction) == 1 || abs(direction) == 8) {
|
||||
if (attackerType == Rook || attackerType == Queen) {
|
||||
return ray;
|
||||
}
|
||||
// Pinned by bishop or queen
|
||||
} else if (direction % 2 != 0) {
|
||||
if (attackerType == Bishop || attackerType == Queen) {
|
||||
return ray;
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
currentSquare += direction;
|
||||
}
|
||||
|
||||
return 0ULL;
|
||||
}
|
||||
|
||||
static bool IsPinned(Board &board, int square) {
|
||||
int kingSquare = (board.colors[board.sideToMove] & board.pieces[King]).getLS1BIndex();
|
||||
int directionToKing = GetDirection(square, kingSquare);
|
||||
|
||||
if (directionToKing) {
|
||||
// Checking if there are any pieces between square and kingSquare
|
||||
if ((SliderRayToSquare(square, kingSquare)
|
||||
& board.occupied).PopCount() != 2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return GetPinningRay(board, square, -directionToKing).PopCount();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void GenThreatMaps(Board &board) {
|
||||
for (int color = White; color <= Black; color++) {
|
||||
board.colorThreats[color] = 0ULL;
|
||||
|
||||
+8
-43
@@ -35,7 +35,7 @@ void Network::Load(const std::string& path) {
|
||||
// Output biases
|
||||
for (size_t i = 0; i < output_bias.size(); i++) {
|
||||
file.read(reinterpret_cast<char*>(&output_bias[i]), sizeof(int16_t));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#if defined(__x86_64__) || defined(__amd64__) || (defined(_WIN64) && (defined(_M_X64) || defined(_M_AMD64)))
|
||||
@@ -74,6 +74,7 @@ using nativeVector = __m256i;
|
||||
}
|
||||
#else
|
||||
#pragma message("Using SSE NNUE inference")
|
||||
// Assumes SSE support here
|
||||
using nativeVector = __m128i;
|
||||
#define set1_epi16 _mm_set1_epi16
|
||||
#define load_epi16 _mm_load_si128
|
||||
@@ -92,47 +93,6 @@ using nativeVector = __m128i;
|
||||
}
|
||||
#endif
|
||||
|
||||
#elif defined(__aarch64__)
|
||||
#pragma message("Using ARM64 (NEON) NNUE inference")
|
||||
#include <arm_neon.h>
|
||||
using nativeVector = int16x8_t;
|
||||
static inline nativeVector set1_epi16(int16_t v) {
|
||||
return vdupq_n_s16(v);
|
||||
}
|
||||
static inline nativeVector load_epi16(const nativeVector* ptr) {
|
||||
return *ptr;
|
||||
}
|
||||
static inline nativeVector min_epi16(nativeVector a, nativeVector b) {
|
||||
return vminq_s16(a, b);
|
||||
}
|
||||
static inline nativeVector max_epi16(nativeVector a, nativeVector b) {
|
||||
return vmaxq_s16(a, b);
|
||||
}
|
||||
static inline int32x4_t madd_epi16(nativeVector a, nativeVector b) {
|
||||
int32x4_t lo = vmull_s16(vget_low_s16(a), vget_low_s16(b));
|
||||
int32x4_t hi = vmull_s16(vget_high_s16(a), vget_high_s16(b));
|
||||
int32x4_t sum_lo = vpaddq_s32(lo, lo);
|
||||
int32x4_t sum_hi = vpaddq_s32(hi, hi);
|
||||
return vcombine_s32(vget_low_s32(sum_lo), vget_low_s32(sum_hi));
|
||||
}
|
||||
static inline nativeVector mullo_epi16(nativeVector a, nativeVector b) {
|
||||
return vmulq_s16(a, b);
|
||||
}
|
||||
static inline int32x4_t add_epi32(int32x4_t a, int32x4_t b) {
|
||||
return vaddq_s32(a, b);
|
||||
}
|
||||
static inline int reduce_epi32(int32x4_t v) {
|
||||
int32x2_t pair = vadd_s32(vget_low_s32(v), vget_high_s32(v));
|
||||
int32x2_t total = vpadd_s32(pair, pair);
|
||||
return vget_lane_s32(total, 0);
|
||||
}
|
||||
|
||||
#else
|
||||
#pragma message("Using fallback scalar NNUE inference")
|
||||
using nativeVector = void*;
|
||||
#endif
|
||||
|
||||
|
||||
static int32_t VectorizedSCReLU(const Board& board, const Network& net, size_t outputBucket) {
|
||||
const size_t VECTOR_SIZE = sizeof(nativeVector) / sizeof(int16_t);
|
||||
static_assert(HL_SIZE % VECTOR_SIZE == 0, "HL size must be divisible by the native register size of your CPU for vectorization to work");
|
||||
@@ -168,11 +128,17 @@ static int32_t VectorizedSCReLU(const Board& board, const Network& net, size_t o
|
||||
|
||||
return reduce_epi32(accumulator);
|
||||
}
|
||||
#endif
|
||||
|
||||
int Forward(const Board& board, const Network& net) {
|
||||
bool stm = board.sideToMove;
|
||||
|
||||
const size_t divisor = 32 / OUTPUT_BUCKETS;
|
||||
const size_t outputBucket = (board.occupied.PopCount() - 2) / divisor;
|
||||
|
||||
const ACC::Accumulator& stmACC = stm ? board.accPair.white : board.accPair.black;
|
||||
const ACC::Accumulator& nstmACC = !stm ? board.accPair.white : board.accPair.black;
|
||||
|
||||
int64_t eval = 0;
|
||||
|
||||
eval = VectorizedSCReLU(board, net, outputBucket);
|
||||
@@ -181,7 +147,6 @@ int Forward(const Board& board, const Network& net) {
|
||||
|
||||
eval += net.output_bias[outputBucket];
|
||||
|
||||
|
||||
return (eval * SCALE) / (QA * QB);
|
||||
}
|
||||
|
||||
|
||||
+2
-2
@@ -8,7 +8,7 @@
|
||||
class Board;
|
||||
|
||||
#ifdef __AVX512F__
|
||||
constexpr size_t ALIGNMENT = 64;
|
||||
constexpr usize ALIGNMENT = 64;
|
||||
#else
|
||||
constexpr size_t ALIGNMENT = 32;
|
||||
#endif
|
||||
@@ -16,7 +16,7 @@ constexpr size_t ALIGNMENT = 32;
|
||||
namespace NNUE {
|
||||
|
||||
constexpr size_t INPUT_SIZE = 768;
|
||||
constexpr size_t HL_SIZE = 1024;
|
||||
constexpr size_t HL_SIZE = 256;
|
||||
constexpr size_t OUTPUT_BUCKETS = 8;
|
||||
|
||||
constexpr int16_t SCALE = 400;
|
||||
|
||||
+130
-252
@@ -22,30 +22,10 @@ void InitLMRTable() {
|
||||
}
|
||||
}
|
||||
|
||||
int16_t ContHistory::GetOnePly(Board& board, Move& move, SearchContext* ctx, int ply) {
|
||||
int prevType = ctx->ss[ply-1].pieceType;
|
||||
int prevTo = ctx->ss[ply-1].moveTo;
|
||||
int pieceType = board.GetPieceType(move.MoveFrom());
|
||||
int to = move.MoveTo();
|
||||
bool otherColor = ctx->ss[ply-1].side;
|
||||
|
||||
return ctx->conthist[otherColor][prevType][prevTo][board.sideToMove][pieceType][to];
|
||||
}
|
||||
|
||||
int16_t ContHistory::GetTwoPly(Board& board, Move& move, SearchContext* ctx, int ply) {
|
||||
int prevType = ctx->ss[ply-2].pieceType;
|
||||
int prevTo = ctx->ss[ply-2].moveTo;
|
||||
int pieceType = board.GetPieceType(move.MoveFrom());
|
||||
int to = move.MoveTo();
|
||||
bool otherColor = ctx->ss[ply-2].side;
|
||||
|
||||
return ctx->conthist[otherColor][prevType][prevTo][board.sideToMove][pieceType][to];
|
||||
}
|
||||
|
||||
static int ScoreMove(Board &board, Move &move, int ply, SearchContext* ctx) {
|
||||
TTEntry current = ctx->TT.GetRawEntry(board.hashKey);
|
||||
if (current.hashKey == board.hashKey && current.bestMove == move) {
|
||||
return 100000;
|
||||
static int ScoreMove(Board &board, Move &move, int ply, SearchContext& ctx) {
|
||||
TTEntry *current = ctx.TT.GetRawEntry(board.hashKey);
|
||||
if (current->hashKey == board.hashKey && current->bestMove == move) {
|
||||
return 50000;
|
||||
}
|
||||
|
||||
if (move.IsCapture()) {
|
||||
@@ -56,60 +36,49 @@ static int ScoreMove(Board &board, Move &move, int ply, SearchContext* ctx) {
|
||||
targetType = Pawn;
|
||||
}
|
||||
|
||||
return 50000 * ((SEE(board, move, -100))) + (100 * targetType - attackerType + 105);
|
||||
return 30000 * ((SEE(board, move, -100))) + moveScoreTable[attackerType][targetType];
|
||||
} else {
|
||||
if (ctx->killerMoves[0][ply] == move) {
|
||||
return 41000;
|
||||
} else if (ctx->killerMoves[1][ply] == move) {
|
||||
return 40000;
|
||||
if (ctx.killerMoves[0][ply] == move) {
|
||||
return 20000;
|
||||
} else if (ctx.killerMoves[1][ply] == move) {
|
||||
return 18000;
|
||||
} else {
|
||||
int historyScore = ctx->history[board.sideToMove][move.MoveFrom()][move.MoveTo()];
|
||||
int conthistScore = 0;
|
||||
|
||||
if (ply > 0) {
|
||||
conthistScore = ctx->conthist.GetOnePly(board, move, ctx, ply);
|
||||
/*
|
||||
if (ply > 1) {
|
||||
conthistScore += ctx->conthist.GetTwoPly(board, move, ctx, ply);
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
return 20000 + historyScore + conthistScore;
|
||||
// Max 16384
|
||||
return ctx.history[board.sideToMove][move.MoveFrom()][move.MoveTo()];
|
||||
}
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
static void SortMoves(Board &board, int ply, SearchContext* ctx) {
|
||||
static void SortMoves(Board &board, int ply, SearchContext& ctx) {
|
||||
if (board.currentMoveIndex <= 1) {
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
int scores[MAX_MOVES];
|
||||
|
||||
|
||||
for (int i = 0; i < board.currentMoveIndex; i++) {
|
||||
scores[i] = ScoreMove(board, board.moveList[i], ply, ctx);
|
||||
}
|
||||
|
||||
|
||||
for (int i = 1; i < board.currentMoveIndex; i++) {
|
||||
Move tempMove = board.moveList[i];
|
||||
int tempScore = scores[i];
|
||||
int j = i - 1;
|
||||
|
||||
|
||||
while (j >= 0 && scores[j] < tempScore) {
|
||||
board.moveList[j + 1] = board.moveList[j];
|
||||
scores[j + 1] = scores[j];
|
||||
j--;
|
||||
}
|
||||
|
||||
|
||||
board.moveList[j + 1] = tempMove;
|
||||
scores[j + 1] = tempScore;
|
||||
}
|
||||
}
|
||||
|
||||
void ListScores(Board &board, int ply, SearchContext* ctx) {
|
||||
void ListScores(Board &board, int ply, SearchContext& ctx) {
|
||||
SortMoves(board, ply, ctx);
|
||||
|
||||
for (int i = 0; i < board.currentMoveIndex; i++) {
|
||||
@@ -120,9 +89,9 @@ void ListScores(Board &board, int ply, SearchContext* ctx) {
|
||||
}
|
||||
}
|
||||
|
||||
static bool IsThreefold(Board &board, SearchContext* ctx) {
|
||||
static bool IsThreefold(Board &board, SearchContext& ctx) {
|
||||
for (int i = 0; i < board.positionIndex; i++) {
|
||||
if (ctx->positionHistory[i] == board.hashKey) {
|
||||
if (ctx.positionHistory[i] == board.hashKey) {
|
||||
// repetition found
|
||||
return true;
|
||||
}
|
||||
@@ -137,32 +106,26 @@ static bool IsFifty(Board &board) {
|
||||
}
|
||||
|
||||
static bool IsInsuffMat(Board &board) {
|
||||
return (board.occupied.PopCount() <= 3
|
||||
return (board.occupied.PopCount() <= 3
|
||||
&& !(board.pieces[Pawn] | board.pieces[Queen] | board.pieces[Rook]));
|
||||
}
|
||||
|
||||
bool IsDraw(Board &board, SearchContext* ctx) {
|
||||
bool IsDraw(Board &board, SearchContext& ctx) {
|
||||
return IsFifty(board) || IsInsuffMat(board) || IsThreefold(board, ctx);
|
||||
}
|
||||
|
||||
template <bool isPV>
|
||||
static int GetReductions(Board &board, Move &move, int depth, int moveSeen, int ply, bool cutnode, SearchContext* ctx) {
|
||||
static int GetReductions(Board &board, Move &move, int depth, int moveSeen, int ply, bool cutnode, SearchContext& ctx) {
|
||||
int reduction = 0;
|
||||
|
||||
|
||||
// Late Move Reduction
|
||||
if (depth >= 3 && moveSeen >= 2 + (2 * isPV) && !move.IsCapture()) {
|
||||
if (depth >= 3 && moveSeen >= 3 && !move.IsCapture()) {
|
||||
reduction = lmrTable[depth][moveSeen];
|
||||
|
||||
if (cutnode)
|
||||
reduction += 2;
|
||||
|
||||
// History LMR
|
||||
int historyReduction = ctx->history[board.sideToMove][move.MoveFrom()][move.MoveTo()];
|
||||
|
||||
if (ply > 0)
|
||||
historyReduction += ctx->conthist.GetOnePly(board, move, ctx, ply);
|
||||
|
||||
historyReduction /= 8192;
|
||||
int historyReduction = ctx.history[board.sideToMove][move.MoveFrom()][move.MoveTo()] / 8192;
|
||||
reduction -= historyReduction;
|
||||
}
|
||||
|
||||
@@ -202,7 +165,7 @@ bool SEE(Board& board, Move& move, int threshold) {
|
||||
|
||||
if (flags == epCapture)
|
||||
occupied.SetBit(board.enPassantTarget);
|
||||
|
||||
|
||||
Bitboard attackers = board.AttacksTo(to, occupied) & occupied;
|
||||
|
||||
bool color = !board.sideToMove;
|
||||
@@ -225,7 +188,7 @@ bool SEE(Board& board, Move& move, int threshold) {
|
||||
attackers |= MOVEGEN::getRookAttack(to, occupied) & rooks;
|
||||
|
||||
attackers &= occupied;
|
||||
|
||||
|
||||
color = !color;
|
||||
|
||||
balance = -balance - 1 - SEEPieceValues[nextVictim];
|
||||
@@ -242,39 +205,37 @@ bool SEE(Board& board, Move& move, int threshold) {
|
||||
}
|
||||
|
||||
template <searchMode mode>
|
||||
static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, SearchContext* ctx) {
|
||||
static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, SearchContext& ctx) {
|
||||
if constexpr (mode != nodesMode) {
|
||||
if constexpr (mode != bench) {
|
||||
if (ctx->nodes % 1024 == 0) {
|
||||
if (ctx->sw.GetElapsedMS() >= ctx->timeToSearch) {
|
||||
ctx->searchStopped = true;
|
||||
if (ctx.nodes % 1024 == 0) {
|
||||
if (ctx.sw.GetElapsedMS() >= ctx.timeToSearch) {
|
||||
ctx.searchStopped = true;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if constexpr (mode == nodesMode) {
|
||||
if (ctx->nodes > ctx->nodesToGo) {
|
||||
ctx->searchStopped = true;
|
||||
if (ctx.nodes > ctx.nodesToGo) {
|
||||
ctx.searchStopped = true;
|
||||
return 0;
|
||||
}
|
||||
} else if constexpr (mode == datagen) {
|
||||
if (ctx->nodes > DATAGEN::HARD_NODES) {
|
||||
ctx->searchStopped = true;
|
||||
if (ctx.nodes > DATAGEN::HARD_NODES) {
|
||||
ctx.searchStopped = true;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (ply > ctx->seldepth)
|
||||
ctx->seldepth = ply;
|
||||
|
||||
if (ply > ctx.seldepth)
|
||||
ctx.seldepth = ply;
|
||||
|
||||
int bestScore = NNUE::net.Evaluate(board);
|
||||
ctx->ss[ply].eval = bestScore;
|
||||
ctx.ss[ply].eval = bestScore;
|
||||
|
||||
if (!ctx->excluded) {
|
||||
TTEntry entry = ctx->TT.GetRawEntry(board.hashKey);
|
||||
if (entry.hashKey == board.hashKey) {
|
||||
bestScore = entry.score;
|
||||
}
|
||||
TTEntry *entry = ctx.TT.GetRawEntry(board.hashKey);
|
||||
if (entry->hashKey == board.hashKey) {
|
||||
bestScore = entry->score;
|
||||
}
|
||||
|
||||
|
||||
@@ -297,18 +258,14 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
|
||||
int isLegal = copy.MakeMove(board.moveList[i]);
|
||||
if (!isLegal) continue;
|
||||
|
||||
ctx->ss[ply].pieceType = board.GetPieceType(board.moveList[i].MoveFrom());
|
||||
ctx->ss[ply].moveTo = board.moveList[i].MoveTo();
|
||||
ctx->ss[ply].side = board.sideToMove;
|
||||
|
||||
if (!SEE(board, board.moveList[i], 0))
|
||||
continue;
|
||||
|
||||
if (copy.positionIndex >= ctx->positionHistory.size()) {
|
||||
ctx->positionHistory.resize(copy.positionIndex + 100);
|
||||
if (copy.positionIndex >= ctx.positionHistory.size()) {
|
||||
ctx.positionHistory.resize(copy.positionIndex + 100);
|
||||
}
|
||||
ctx->positionHistory[copy.positionIndex] = copy.hashKey;
|
||||
ctx->nodes++;
|
||||
ctx.positionHistory[copy.positionIndex] = copy.hashKey;
|
||||
ctx.nodes++;
|
||||
int score = -Quiescence<mode>(copy, -beta, -alpha, ply + 1, ctx).score;
|
||||
|
||||
if (score >= beta) {
|
||||
@@ -324,98 +281,87 @@ static SearchResults Quiescence(Board& board, int alpha, int beta, int ply, Sear
|
||||
}
|
||||
|
||||
results.score = bestScore;
|
||||
if (ctx->searchStopped) return 0;
|
||||
if (ctx.searchStopped) return 0;
|
||||
return results;
|
||||
}
|
||||
|
||||
template <bool isPV, searchMode mode>
|
||||
SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchContext* ctx, bool cutnode) {
|
||||
SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchContext& ctx, bool cutnode) {
|
||||
if constexpr (mode != bench && mode != nodesMode) {
|
||||
if (ctx->nodes % 1024 == 0) {
|
||||
if (ctx.nodes % 1024 == 0) {
|
||||
if constexpr (mode == normal) {
|
||||
if (ctx->sw.GetElapsedMS() >= ctx->timeToSearch) {
|
||||
ctx->searchStopped = true;
|
||||
if (ctx.sw.GetElapsedMS() >= ctx.timeToSearch) {
|
||||
ctx.searchStopped = true;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if constexpr (mode == nodesMode) {
|
||||
if (ctx->nodes > ctx->nodesToGo) {
|
||||
ctx->searchStopped = true;
|
||||
if (ctx.nodes > ctx.nodesToGo) {
|
||||
ctx.searchStopped = true;
|
||||
return 0;
|
||||
}
|
||||
} else if constexpr (mode == datagen) {
|
||||
if (ctx->nodes > DATAGEN::HARD_NODES) {
|
||||
ctx->searchStopped = true;
|
||||
if (ctx.nodes > DATAGEN::HARD_NODES) {
|
||||
ctx.searchStopped = true;
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
if (ply > ctx->seldepth)
|
||||
ctx->seldepth = ply;
|
||||
if (ply > ctx.seldepth)
|
||||
ctx.seldepth = ply;
|
||||
|
||||
|
||||
ctx->pvLine.SetLength(ply);
|
||||
ctx.pvLine.SetLength(ply);
|
||||
if (ply && (IsDraw(board, ctx))) return 0;
|
||||
|
||||
|
||||
TTEntry entry;
|
||||
if (!ctx->excluded)
|
||||
entry = ctx->TT.GetRawEntry(board.hashKey);
|
||||
|
||||
const bool ttHit = entry.hashKey == board.hashKey;
|
||||
|
||||
// if NOT PV node then we try to hit the TTable
|
||||
if constexpr (!isPV) {
|
||||
if (ttHit) {
|
||||
if (entry.depth >= depth &&
|
||||
((entry.nodeType == PV) ||
|
||||
(entry.nodeType == AllNode && entry.score <= alpha) ||
|
||||
(entry.nodeType == CutNode && entry.score >= beta))) {
|
||||
|
||||
return SearchResults(entry.score, entry.bestMove);
|
||||
}
|
||||
SearchResults entry = ctx.TT.ReadEntry(board.hashKey, depth, alpha, beta);
|
||||
if (entry.score != invalidEntry) {
|
||||
return entry;
|
||||
}
|
||||
}
|
||||
|
||||
if (depth <= 0) return Quiescence<mode>(board, alpha, beta, ply, ctx);
|
||||
|
||||
const int staticEval = NNUE::net.Evaluate(board);
|
||||
ctx->ss[ply].eval = staticEval;
|
||||
ctx.ss[ply].eval = staticEval;
|
||||
|
||||
const bool improving = [&]
|
||||
{
|
||||
if (board.InCheck())
|
||||
return false;
|
||||
if (ply > 1 && ctx->ss[ply - 2].eval != ScoreNone)
|
||||
return staticEval > ctx->ss[ply - 2].eval;
|
||||
if (ply > 3 && ctx->ss[ply - 4].eval != ScoreNone)
|
||||
return staticEval > ctx->ss[ply - 4].eval;
|
||||
if (ply > 1 && ctx.ss[ply - 2].eval != ScoreNone)
|
||||
return staticEval > ctx.ss[ply - 2].eval;
|
||||
if (ply > 3 && ctx.ss[ply - 4].eval != ScoreNone)
|
||||
return staticEval > ctx.ss[ply - 4].eval;
|
||||
|
||||
return true;
|
||||
}();
|
||||
|
||||
if (!board.InCheck() && !ctx->excluded) {
|
||||
if (!board.InCheck()) {
|
||||
if (ply) {
|
||||
// Reverse Futility Pruning
|
||||
int margin = 100 * (depth - improving);
|
||||
if (!ttHit && staticEval - margin >= beta && depth < 7) {
|
||||
if (staticEval - margin >= beta && depth < 7) {
|
||||
return (beta + (staticEval - beta) / 3);
|
||||
}
|
||||
|
||||
// Null Move Pruning
|
||||
if (!ctx->doingNullMove && staticEval >= beta) {
|
||||
if (depth > 1 && !board.InPossibleZug()) {
|
||||
if (!ctx.doingNullMove && staticEval >= beta) {
|
||||
if (depth >= 3 && !board.InPossibleZug()) {
|
||||
Board copy = board;
|
||||
copy.MakeMove(Move());
|
||||
|
||||
const int reduction = 3 + improving;
|
||||
|
||||
ctx->doingNullMove = true;
|
||||
int score = -PVS<false, mode>(copy, depth - reduction, -beta, -beta + 1, ply + 1, ctx, !cutnode).score;
|
||||
ctx->doingNullMove = false;
|
||||
|
||||
if (ctx->searchStopped) return 0;
|
||||
if (score >= beta) return score;
|
||||
bool isLegal = copy.MakeMove(Move());
|
||||
// Always legal so we dont check it
|
||||
|
||||
ctx.doingNullMove = true;
|
||||
int score = -PVS<false, mode>(copy, depth - 3, -beta, -beta + 1, ply + 1, ctx, !cutnode).score;
|
||||
ctx.doingNullMove = false;
|
||||
|
||||
if (ctx.searchStopped) return 0;
|
||||
if (score >= beta) return score;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -437,9 +383,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
for (int i = 0; i < board.currentMoveIndex; i++) {
|
||||
Move currMove = board.moveList[i];
|
||||
|
||||
if (ctx->excluded == currMove)
|
||||
continue;
|
||||
|
||||
bool notMated = results.score > (-MATE_SCORE + MAX_PLY);
|
||||
|
||||
// Late move pruning
|
||||
@@ -448,7 +391,6 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
if (!isPV && !board.InCheck() && currMove.IsQuiet() && notMated) {
|
||||
int lmpBase = 7;
|
||||
|
||||
|
||||
int lmpThreshold = lmpBase + 4 * depth;
|
||||
|
||||
if (moveSeen >= lmpThreshold) {
|
||||
@@ -459,49 +401,22 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
// Futility pruning
|
||||
// If our static eval is far below alpha, there is only a small chance
|
||||
// that a quiet move will help us so we skip them
|
||||
int historyScore = ctx->history[board.sideToMove][currMove.MoveFrom()][currMove.MoveTo()];
|
||||
int fpMargin = 100 * depth + historyScore / 32;
|
||||
|
||||
int fpMargin = 100 * depth;
|
||||
if (!isPV && ply && currMove.IsQuiet()
|
||||
&& depth <= 5 && staticEval + fpMargin < alpha && notMated) {
|
||||
&& depth <= 5 && staticEval + fpMargin < alpha && notMated) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
Board copy = board;
|
||||
bool isLegal = copy.MakeMove(currMove);
|
||||
|
||||
if (!isLegal) continue;
|
||||
|
||||
ctx->ss[ply].pieceType = board.GetPieceType(currMove.MoveFrom());
|
||||
ctx->ss[ply].moveTo = currMove.MoveTo();
|
||||
ctx->ss[ply].side = board.sideToMove;
|
||||
|
||||
if (copy.positionIndex >= ctx->positionHistory.size()) {
|
||||
ctx->positionHistory.resize(copy.positionIndex + 100);
|
||||
}
|
||||
ctx->positionHistory[copy.positionIndex] = copy.hashKey;
|
||||
ctx->nodes++;
|
||||
|
||||
int extension = 0;
|
||||
|
||||
if (ply
|
||||
&& depth >= 8
|
||||
&& ttHit
|
||||
&& currMove == entry.bestMove
|
||||
&& ctx->excluded == 0
|
||||
&& entry.depth >= depth - 3
|
||||
&& entry.nodeType != AllNode)
|
||||
{
|
||||
const int sBeta = std::max(-inf + 1, entry.score - depth * 2);
|
||||
const int sDepth = (depth - 1) / 2;
|
||||
|
||||
ctx->excluded = currMove;
|
||||
const int singularScore = PVS<false, mode>(board, sDepth, sBeta-1, sBeta, ply, ctx, cutnode).score;
|
||||
ctx->excluded = Move();
|
||||
|
||||
if (singularScore < sBeta)
|
||||
extension = 1;
|
||||
if (copy.positionIndex >= ctx.positionHistory.size()) {
|
||||
ctx.positionHistory.resize(copy.positionIndex + 100);
|
||||
}
|
||||
ctx.positionHistory[copy.positionIndex] = copy.hashKey;
|
||||
ctx.nodes++;
|
||||
|
||||
// PVS SEE
|
||||
int SEEThreshold = currMove.IsQuiet() ? -80 * depth : -30 * depth * depth;
|
||||
@@ -509,9 +424,10 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
if (ply && depth <= 10 && !SEE(board, currMove, SEEThreshold))
|
||||
continue;
|
||||
|
||||
int reductions = GetReductions<isPV>(board, currMove, depth, moveSeen, ply, cutnode, ctx);
|
||||
|
||||
int newDepth = depth + copy.InCheck() - 1 + extension;
|
||||
int reductions = GetReductions(board, currMove, depth, moveSeen, ply, cutnode, ctx);
|
||||
|
||||
int newDepth = depth + copy.InCheck() - 1;
|
||||
|
||||
// First move (suspected PV node)
|
||||
if (!moveSeen) {
|
||||
@@ -541,7 +457,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
|
||||
moveSeen++;
|
||||
|
||||
if (ctx->searchStopped) return 0;
|
||||
if (ctx.searchStopped) return 0;
|
||||
|
||||
if (currMove != 0 && currMove.IsQuiet()) {
|
||||
seenQuiets[seenQuietsCount] = currMove;
|
||||
@@ -551,57 +467,20 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
// Fail high (beta cutoff)
|
||||
if (score >= beta) {
|
||||
if (!currMove.IsCapture()) {
|
||||
ctx->killerMoves[1][ply] = ctx->killerMoves[0][ply];
|
||||
ctx->killerMoves[0][ply] = currMove;
|
||||
ctx.killerMoves[1][ply] = ctx.killerMoves[0][ply];
|
||||
ctx.killerMoves[0][ply] = currMove;
|
||||
|
||||
int bonus = 300 * depth - 250;
|
||||
|
||||
ctx->history.Update(board.sideToMove, currMove, bonus);
|
||||
|
||||
if (ply > 0) {
|
||||
int prevType = ctx->ss[ply-1].pieceType;
|
||||
int prevTo = ctx->ss[ply-1].moveTo;
|
||||
int pieceType = ctx->ss[ply].pieceType;
|
||||
int to = ctx->ss[ply].moveTo;
|
||||
bool otherColor = ctx->ss[ply-1].side;
|
||||
|
||||
ctx->conthist.Update(board.sideToMove, otherColor, prevType, prevTo, pieceType, to, bonus);
|
||||
|
||||
// Malus
|
||||
for (int moveIndex = 0; moveIndex < seenQuietsCount - 1; moveIndex++) {
|
||||
int pieceType = board.GetPieceType(seenQuiets[moveIndex].MoveFrom());
|
||||
int to = seenQuiets[moveIndex].MoveTo();
|
||||
|
||||
ctx->conthist.Update(board.sideToMove, otherColor, prevType, prevTo, pieceType, to, -bonus);
|
||||
}
|
||||
|
||||
if (ply > 1) {
|
||||
prevType = ctx->ss[ply-2].pieceType;
|
||||
prevTo = ctx->ss[ply-2].moveTo;
|
||||
otherColor = ctx->ss[ply-2].side;
|
||||
|
||||
ctx->conthist.Update(board.sideToMove, otherColor, prevType, prevTo, pieceType, to, bonus);
|
||||
|
||||
// Malus
|
||||
for (int moveIndex = 0; moveIndex < seenQuietsCount - 1; moveIndex++) {
|
||||
int pieceType = board.GetPieceType(seenQuiets[moveIndex].MoveFrom());
|
||||
int to = seenQuiets[moveIndex].MoveTo();
|
||||
|
||||
ctx->conthist.Update(board.sideToMove, otherColor, prevType, prevTo, pieceType, to, -bonus);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
ctx.history.Update(board.sideToMove, currMove, bonus);
|
||||
|
||||
// Malus
|
||||
for (int moveIndex = 0; moveIndex < seenQuietsCount - 1; moveIndex++) {
|
||||
ctx->history.Update(board.sideToMove, seenQuiets[moveIndex], -bonus);
|
||||
ctx.history.Update(board.sideToMove, seenQuiets[moveIndex], -bonus);
|
||||
}
|
||||
}
|
||||
|
||||
if (!ctx->excluded)
|
||||
ctx->TT.WriteEntry(board.hashKey, depth, score, CutNode, currMove);
|
||||
ctx.TT.WriteEntry(board.hashKey, depth, score, CutNode, Move());
|
||||
return score;
|
||||
}
|
||||
|
||||
@@ -611,7 +490,7 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
nodeType = PV;
|
||||
alpha = score;
|
||||
results.bestMove = currMove;
|
||||
ctx->pvLine.SetMove(ply, currMove);
|
||||
ctx.pvLine.SetMove(ply, currMove);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -623,9 +502,8 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
|
||||
}
|
||||
}
|
||||
|
||||
if (ctx->searchStopped) return 0;
|
||||
if (!ctx->excluded)
|
||||
ctx->TT.WriteEntry(board.hashKey, depth, results.score, nodeType, results.bestMove);
|
||||
if (ctx.searchStopped) return 0;
|
||||
ctx.TT.WriteEntry(board.hashKey, depth, results.score, nodeType, results.bestMove);
|
||||
return results;
|
||||
}
|
||||
|
||||
@@ -655,7 +533,7 @@ public:
|
||||
|
||||
// Iterative deepening
|
||||
template <searchMode mode>
|
||||
static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
|
||||
static SearchResults ID(Board &board, SearchParams params, SearchContext& ctx) {
|
||||
int fullTime = board.sideToMove ? params.btime : params.wtime;
|
||||
int inc = board.sideToMove ? params.binc : params.winc;
|
||||
int movesToGo = params.movesToGo ? params.movesToGo : 20;
|
||||
@@ -673,14 +551,14 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
|
||||
|
||||
int elapsed = 0;
|
||||
|
||||
ctx->sw.Restart();
|
||||
ctx.sw.Restart();
|
||||
|
||||
for (int depth = 1; depth <= toDepth; depth++) {
|
||||
ctx->timeToSearch = std::max((fullTime / movesToGo) + (inc / 2), 4);
|
||||
int softTime = ctx->timeToSearch * 0.65;
|
||||
ctx.timeToSearch = std::max((fullTime / movesToGo) + (inc / 2), 4);
|
||||
int softTime = ctx.timeToSearch * 0.65;
|
||||
|
||||
SearchResults currentResults = PVS<true, mode>(board, depth, aw.alpha, aw.beta, 0, ctx, false);
|
||||
elapsed = ctx->sw.GetElapsedMS();
|
||||
elapsed = ctx.sw.GetElapsedMS();
|
||||
|
||||
if (aw.alpha != -inf && currentResults.score <= aw.alpha) {
|
||||
aw.WidenDown();
|
||||
@@ -695,7 +573,7 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
|
||||
|
||||
aw.Set(currentResults.score);
|
||||
|
||||
if (ctx->searchStopped) {
|
||||
if (ctx.searchStopped) {
|
||||
break;
|
||||
} else {
|
||||
if (currentResults.bestMove) {
|
||||
@@ -705,24 +583,24 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
|
||||
if constexpr (mode == normal || mode == nodesMode) {
|
||||
std::cout << "info ";
|
||||
std::cout << "depth " << depth;
|
||||
std::cout << " seldepth " << ctx->seldepth;
|
||||
std::cout << " seldepth " << ctx.seldepth;
|
||||
std::cout << " time " << elapsed;
|
||||
std::cout << " score cp " << safeResults.score;
|
||||
std::cout << " nodes " << ctx->nodes << " nps " << int(ctx->nodes/ctx->sw.GetElapsedSec());
|
||||
std::cout << " hashfull " << ctx->TT.GetUsedPercentage();
|
||||
std::cout << " nodes " << ctx.nodes << " nps " << int(ctx.nodes/ctx.sw.GetElapsedSec());
|
||||
std::cout << " hashfull " << ctx.TT.GetUsedPercentage();
|
||||
std::cout << " pv ";
|
||||
ctx->pvLine.Print(0);
|
||||
ctx.pvLine.Print(0);
|
||||
std::cout << std::endl;
|
||||
|
||||
if constexpr (mode == normal) {
|
||||
if (ctx->sw.GetElapsedMS() >= softTime) {
|
||||
ctx->searchStopped = true;
|
||||
if (ctx.sw.GetElapsedMS() >= softTime) {
|
||||
ctx.searchStopped = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if constexpr (mode == datagen) {
|
||||
if (ctx->nodes >= DATAGEN::SOFT_NODES) {
|
||||
ctx->searchStopped = true;
|
||||
if (ctx.nodes >= DATAGEN::SOFT_NODES) {
|
||||
ctx.searchStopped = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
@@ -733,17 +611,17 @@ static SearchResults ID(Board &board, SearchParams params, SearchContext* ctx) {
|
||||
}
|
||||
|
||||
template <searchMode mode>
|
||||
SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* ctx) {
|
||||
ctx->searchStopped = false;
|
||||
ctx->seldepth = 0;
|
||||
SearchResults SearchPosition(Board &board, SearchParams params, SearchContext& ctx) {
|
||||
ctx.searchStopped = false;
|
||||
ctx.seldepth = 0;
|
||||
if constexpr (mode != bench) {
|
||||
ctx->nodes = 0;
|
||||
ctx.nodes = 0;
|
||||
|
||||
if constexpr (mode == nodesMode) {
|
||||
ctx->nodesToGo = params.nodes;
|
||||
ctx.nodesToGo = params.nodes;
|
||||
}
|
||||
}
|
||||
ctx->pvLine.Clear();
|
||||
ctx.pvLine.Clear();
|
||||
|
||||
SearchResults results = ID<mode>(board, params, ctx);
|
||||
|
||||
@@ -778,16 +656,16 @@ int MoveEstimatedValue(Board& board, Move& move) {
|
||||
return value;
|
||||
}
|
||||
|
||||
template SearchResults PVS<true, searchMode::bench>(Board&, int, int, int, int, SearchContext* ctx, bool cutnode);
|
||||
template SearchResults PVS<false, searchMode::bench>(Board&, int, int, int, int, SearchContext* ctx, bool cutnode);
|
||||
template SearchResults PVS<true, searchMode::normal>(Board&, int, int, int, int, SearchContext* ctx, bool cutnode);
|
||||
template SearchResults PVS<false, searchMode::normal>(Board&, int, int, int, int, SearchContext* ctx, bool cutnode);
|
||||
template SearchResults PVS<true, searchMode::datagen>(Board&, int, int, int, int, SearchContext* ctx, bool cutnode);
|
||||
template SearchResults PVS<false, searchMode::datagen>(Board&, int, int, int, int, SearchContext* ctx, bool cutnode);
|
||||
template SearchResults PVS<true, searchMode::bench>(Board&, int, int, int, int, SearchContext& ctx, bool cutnode);
|
||||
template SearchResults PVS<false, searchMode::bench>(Board&, int, int, int, int, SearchContext& ctx, bool cutnode);
|
||||
template SearchResults PVS<true, searchMode::normal>(Board&, int, int, int, int, SearchContext& ctx, bool cutnode);
|
||||
template SearchResults PVS<false, searchMode::normal>(Board&, int, int, int, int, SearchContext& ctx, bool cutnode);
|
||||
template SearchResults PVS<true, searchMode::datagen>(Board&, int, int, int, int, SearchContext& ctx, bool cutnode);
|
||||
template SearchResults PVS<false, searchMode::datagen>(Board&, int, int, int, int, SearchContext& ctx, bool cutnode);
|
||||
|
||||
template SearchResults SearchPosition<normal>(Board &board, SearchParams params, SearchContext* ctx);
|
||||
template SearchResults SearchPosition<bench>(Board &board, SearchParams params, SearchContext* ctx);
|
||||
template SearchResults SearchPosition<datagen>(Board &board, SearchParams params, SearchContext* ctx);
|
||||
template SearchResults SearchPosition<nodesMode>(Board &board, SearchParams params, SearchContext* ctx);
|
||||
template SearchResults SearchPosition<normal>(Board &board, SearchParams params, SearchContext& ctx);
|
||||
template SearchResults SearchPosition<bench>(Board &board, SearchParams params, SearchContext& ctx);
|
||||
template SearchResults SearchPosition<datagen>(Board &board, SearchParams params, SearchContext& ctx);
|
||||
template SearchResults SearchPosition<nodesMode>(Board &board, SearchParams params, SearchContext& ctx);
|
||||
|
||||
}
|
||||
+24
-45
@@ -7,8 +7,6 @@
|
||||
#include "stopwatch.h"
|
||||
#include "tt.h"
|
||||
|
||||
#include "../external/multi_array.h"
|
||||
|
||||
namespace SEARCH {
|
||||
|
||||
enum searchMode {
|
||||
@@ -19,8 +17,8 @@ enum searchMode {
|
||||
};
|
||||
|
||||
constexpr int MATE_SCORE = 32767;
|
||||
constexpr int MAX_DEPTH = 128;
|
||||
constexpr int MAX_PLY = 512;
|
||||
constexpr int MAX_DEPTH = 64;
|
||||
constexpr int MAX_PLY = 128;
|
||||
constexpr int MAX_HISTORY = 16384;
|
||||
|
||||
constexpr int32_t ScoreNone = -255000;
|
||||
@@ -33,35 +31,10 @@ constexpr std::array<int, 6> SEEPieceValues = {
|
||||
};
|
||||
|
||||
void InitLMRTable();
|
||||
class SearchContext;
|
||||
|
||||
class ContHistory {
|
||||
private:
|
||||
// indexed by [other color][prev move piece][stm][prev move to][piece][to]
|
||||
MultiArray<int16_t, 2, 6, 64, 2, 6, 64> contHistMoves;
|
||||
public:
|
||||
void Update(bool stm, bool otherColor, int prevType, int prevTo, int type, int to, int bonus) {
|
||||
int clampedBonus = std::clamp(bonus, -MAX_HISTORY, MAX_HISTORY);
|
||||
|
||||
contHistMoves[otherColor][prevType][prevTo][stm][type][to] +=
|
||||
clampedBonus - contHistMoves[otherColor][prevType][prevTo][stm][type][to] * std::abs(clampedBonus) / MAX_HISTORY;
|
||||
}
|
||||
|
||||
void Clear() {
|
||||
std::fill(&contHistMoves[0][0][0][0][0][0], &contHistMoves[0][0][0][0][0][0] + sizeof(contHistMoves) / sizeof(int16_t), 0);
|
||||
}
|
||||
|
||||
int16_t GetOnePly(Board& board, Move& move, SearchContext* ctx, int ply);
|
||||
int16_t GetTwoPly(Board& board, Move& move, SearchContext* ctx, int ply);
|
||||
|
||||
auto& operator[](int index) {
|
||||
return contHistMoves[index];
|
||||
}
|
||||
};
|
||||
|
||||
class History {
|
||||
private:
|
||||
MultiArray<int, 2, 64, 64> historyMoves;
|
||||
int historyMoves[2][64][64];
|
||||
public:
|
||||
void Update(bool stm, Move move, int bonus) {
|
||||
int clampedBonus = std::clamp(bonus, -MAX_HISTORY, MAX_HISTORY);
|
||||
@@ -70,7 +43,13 @@ public:
|
||||
}
|
||||
|
||||
void Clear() {
|
||||
std::fill(&historyMoves[0][0][0], &historyMoves[0][0][0] + sizeof(historyMoves) / sizeof(int), 0);
|
||||
for (auto &side : historyMoves) {
|
||||
for (auto &from : side) {
|
||||
for (auto &to : from) {
|
||||
to = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
auto& operator[](int index) {
|
||||
@@ -113,10 +92,6 @@ public:
|
||||
class Stack {
|
||||
public:
|
||||
int32_t eval = ScoreNone;
|
||||
|
||||
int pieceType = -1;
|
||||
int moveTo = -1;
|
||||
bool side = -1;
|
||||
};
|
||||
|
||||
class SearchContext {
|
||||
@@ -126,15 +101,12 @@ public:
|
||||
int timeToSearch = 0;
|
||||
|
||||
int seldepth = 0;
|
||||
|
||||
Move excluded = Move();
|
||||
|
||||
bool doingNullMove = false;
|
||||
bool searchStopped = false;
|
||||
|
||||
PVLine pvLine;
|
||||
History history;
|
||||
ContHistory conthist;
|
||||
|
||||
std::array<std::array<int, MAX_PLY>, 2> killerMoves{};
|
||||
|
||||
@@ -149,26 +121,33 @@ public:
|
||||
SearchContext(){
|
||||
pvLine.Clear();
|
||||
history.Clear();
|
||||
conthist.Clear();
|
||||
TT.Clear();
|
||||
sw.Restart();
|
||||
killerMoves = {};
|
||||
ss = {};
|
||||
positionHistory.resize(1000);
|
||||
positionHistory.reserve(1000);
|
||||
}
|
||||
};
|
||||
|
||||
bool SEE(Board& board, Move& move, int threshold);
|
||||
|
||||
template <bool isPV, searchMode mode>
|
||||
SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchContext* ctx, bool cutnode);
|
||||
SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchContext& ctx, bool cutnode);
|
||||
|
||||
template <searchMode mode>
|
||||
SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* ctx);
|
||||
SearchResults SearchPosition(Board &board, SearchParams params, SearchContext& ctx);
|
||||
|
||||
bool IsDraw(Board &board, SearchContext* ctx);
|
||||
bool IsDraw(Board &board, SearchContext& ctx);
|
||||
|
||||
void ListScores(Board &board, SearchContext* ctx);
|
||||
constexpr int moveScoreTable[6][6] = {
|
||||
105, 205, 305, 405, 505, 605,
|
||||
104, 204, 304, 404, 504, 604,
|
||||
103, 203, 303, 403, 503, 603,
|
||||
102, 202, 302, 402, 502, 602,
|
||||
101, 201, 301, 401, 501, 601,
|
||||
100, 200, 300, 400, 500, 600
|
||||
};
|
||||
|
||||
void ListScores(Board &board, SearchContext& ctx);
|
||||
|
||||
int MoveEstimatedValue(Board& board, Move& move);
|
||||
}
|
||||
+20
-1
@@ -1,5 +1,24 @@
|
||||
#include "tt.h"
|
||||
|
||||
SearchResults TTable::ReadEntry(U64 &hashKey, int depth, int alpha, int beta) {
|
||||
TTEntry *current = &table[hashKey % table.size()];
|
||||
|
||||
if (current->hashKey == hashKey) {
|
||||
if (current->depth >= depth) {
|
||||
if (current->nodeType == PV){
|
||||
return {current->score, current->bestMove};
|
||||
} else if (current->nodeType == AllNode && current->score <= alpha) {
|
||||
return current->score;
|
||||
} else if (current->nodeType == CutNode && current->score >= beta) {
|
||||
return current->score;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// returning invalid value
|
||||
return invalidEntry;
|
||||
}
|
||||
|
||||
void TTable::WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move bestMove) {
|
||||
TTEntry *current = &table[hashKey % table.size()];
|
||||
|
||||
@@ -8,4 +27,4 @@ void TTable::WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move b
|
||||
current->score = score;
|
||||
current->depth = depth;
|
||||
current->bestMove = bestMove;
|
||||
}
|
||||
}
|
||||
+4
-10
@@ -27,12 +27,6 @@ public:
|
||||
uint8_t depth = 0;
|
||||
uint8_t nodeType = 0;
|
||||
|
||||
TTEntry() {}
|
||||
|
||||
TTEntry(int16_t score) {
|
||||
this->score = score;
|
||||
}
|
||||
|
||||
operator U64() {
|
||||
return hashKey;
|
||||
}
|
||||
@@ -43,7 +37,7 @@ constexpr U64 maxHash = (1024 * 1000000) / sizeof(TTEntry);
|
||||
// 8 MB
|
||||
constexpr U64 defaultHash = (8 * 1000000) / sizeof(TTEntry);
|
||||
|
||||
constexpr int16_t invalidEntry = 11111;
|
||||
constexpr int invalidEntry = 111111;
|
||||
|
||||
class TTable {
|
||||
private:
|
||||
@@ -61,9 +55,9 @@ public:
|
||||
table.resize(size);
|
||||
}
|
||||
|
||||
TTEntry GetRawEntry(U64 &hashKey) {
|
||||
TTEntry* GetRawEntry(U64 &hashKey) {
|
||||
TTEntry *current = &table[hashKey % table.size()];
|
||||
return *current;
|
||||
return current;
|
||||
}
|
||||
|
||||
// returns used space per mill
|
||||
@@ -77,7 +71,7 @@ public:
|
||||
return count;
|
||||
}
|
||||
|
||||
TTEntry ReadEntry(U64 &hashKey, int depth, int alpha, int beta);
|
||||
SearchResults ReadEntry(U64 &hashKey, int depth, int alpha, int beta);
|
||||
|
||||
void WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move besteMove);
|
||||
};
|
||||
+28
-83
@@ -1,9 +1,9 @@
|
||||
#include "uci.h"
|
||||
#include <iostream>
|
||||
#include <algorithm>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <tuple>
|
||||
#include <memory>
|
||||
#include <thread>
|
||||
#include "types.h"
|
||||
#include "movegen.h"
|
||||
#include "search.h"
|
||||
@@ -12,14 +12,7 @@
|
||||
#include "utils.h"
|
||||
#include "datagen.h"
|
||||
|
||||
// OS-dependent threading includes
|
||||
#ifdef _WIN32
|
||||
#include <thread>
|
||||
#else
|
||||
#include <pthread.h>
|
||||
#endif
|
||||
|
||||
static void ParsePosition(Board &board, std::string_view command, SEARCH::SearchContext* ctx) {
|
||||
static void ParsePosition(Board &board, std::string_view command, SEARCH::SearchContext& ctx) {
|
||||
if (command.find("startpos") != std::string::npos) {
|
||||
board.SetByFen(StartingFen);
|
||||
}
|
||||
@@ -39,8 +32,8 @@ static void ParsePosition(Board &board, std::string_view command, SEARCH::Search
|
||||
std::vector<std::string> moves = UTILS::split(command.substr(movesIndex + 6, command.length() - (movesIndex + 5)), ' ');
|
||||
|
||||
for (std::string_view move : moves) {
|
||||
board.MakeMove(UTILS::parseMove(board, move));
|
||||
ctx->positionHistory[board.positionIndex] = board.hashKey;
|
||||
bool isLegal = board.MakeMove(UTILS::parseMove(board, move));
|
||||
ctx.positionHistory[board.positionIndex] = board.hashKey;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -76,56 +69,7 @@ static int ReadParam(std::string param, std::string &command) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
// Windows implementation using std::thread
|
||||
template <SEARCH::searchMode mode>
|
||||
static void ThreadFunc(Board* board, SearchParams params, SEARCH::SearchContext* ctx) {
|
||||
SEARCH::SearchPosition<mode>(*board, params, ctx);
|
||||
}
|
||||
|
||||
static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchContext* ctx) {
|
||||
std::thread searchThread;
|
||||
|
||||
if (params.nodes) {
|
||||
searchThread = std::thread(ThreadFunc<SEARCH::nodesMode>, &board, params, ctx);
|
||||
} else {
|
||||
searchThread = std::thread(ThreadFunc<SEARCH::normal>, &board, params, ctx);
|
||||
}
|
||||
|
||||
searchThread.detach();
|
||||
}
|
||||
|
||||
#else
|
||||
// Unix/Linux implementation using pthread
|
||||
template <SEARCH::searchMode mode>
|
||||
static void* ThreadFunc(void* arg) {
|
||||
auto* tup = static_cast<std::tuple<Board*, SearchParams, SEARCH::SearchContext*>*>(arg);
|
||||
SEARCH::SearchPosition<mode>(*std::get<0>(*tup), std::get<1>(*tup), std::get<2>(*tup));
|
||||
delete tup;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchContext* ctx) {
|
||||
pthread_attr_t attr;
|
||||
pthread_attr_init(&attr);
|
||||
pthread_attr_setstacksize(&attr, 8 * 1024 * 1024); // 8 MB stack
|
||||
|
||||
pthread_t thread;
|
||||
|
||||
if (params.nodes) {
|
||||
auto* arg = new std::tuple<Board*, SearchParams, SEARCH::SearchContext*>(&board, params, ctx);
|
||||
pthread_create(&thread, &attr, ThreadFunc<SEARCH::nodesMode>, arg);
|
||||
} else {
|
||||
auto* arg = new std::tuple<Board*, SearchParams, SEARCH::SearchContext*>(&board, params, ctx);
|
||||
pthread_create(&thread, &attr, ThreadFunc<SEARCH::normal>, arg);
|
||||
}
|
||||
|
||||
pthread_attr_destroy(&attr);
|
||||
pthread_detach(thread);
|
||||
}
|
||||
#endif
|
||||
|
||||
static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext* ctx) {
|
||||
static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext& ctx) {
|
||||
SearchParams params;
|
||||
|
||||
params.wtime = ReadParam("wtime", command);
|
||||
@@ -138,23 +82,26 @@ static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext* c
|
||||
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;
|
||||
}
|
||||
|
||||
StartSearchThread(board, params, ctx);
|
||||
if (params.nodes) {
|
||||
auto worker = std::thread(SEARCH::SearchPosition<SEARCH::nodesMode>, std::ref(board), params, std::ref(ctx));
|
||||
worker.detach();
|
||||
} else {
|
||||
auto worker = std::thread(SEARCH::SearchPosition<SEARCH::normal>, std::ref(board), params, std::ref(ctx));
|
||||
worker.detach();
|
||||
}
|
||||
}
|
||||
|
||||
static void SetOption(std::string &command, SEARCH::SearchContext* ctx) {
|
||||
static void SetOption(std::string &command, SEARCH::SearchContext& ctx) {
|
||||
if (command.find("Hash") != std::string::npos) {
|
||||
U64 hashSize = (ReadParam("value", command) * 1000000) / sizeof(TTEntry);
|
||||
ctx->TT.Resize(hashSize);
|
||||
ctx.TT.Resize(hashSize);
|
||||
}
|
||||
}
|
||||
|
||||
static void PrintEngineInfo() {
|
||||
std::cout << "id name Eleanor v2.0" << std::endl;
|
||||
std::cout << "id name Eleanor v1.0" << 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 1" << std::endl;
|
||||
@@ -164,7 +111,7 @@ static void PrintEngineInfo() {
|
||||
void UCILoop(Board &board) {
|
||||
std::string input = "";
|
||||
|
||||
auto ctx = std::make_unique<SEARCH::SearchContext>();
|
||||
SEARCH::SearchContext ctx;
|
||||
|
||||
// main loop
|
||||
while (true) {
|
||||
@@ -178,7 +125,7 @@ void UCILoop(Board &board) {
|
||||
|
||||
// parse UCI "position" command
|
||||
if (input.find("position") != std::string::npos) {
|
||||
ParsePosition(board, input, ctx.get());
|
||||
ParsePosition(board, input, ctx);
|
||||
|
||||
continue;
|
||||
}
|
||||
@@ -186,22 +133,20 @@ void UCILoop(Board &board) {
|
||||
// parse UCI "ucinewgame" command
|
||||
if (input.find("ucinewgame") != std::string::npos) {
|
||||
board.SetByFen(StartingFen);
|
||||
|
||||
|
||||
// Clearing
|
||||
ctx->TT.Clear();
|
||||
|
||||
ctx->killerMoves = {};
|
||||
ctx->history.Clear();
|
||||
ctx->conthist.Clear();
|
||||
ctx->positionHistory = {};
|
||||
ctx->ss = {};
|
||||
ctx.TT.Clear();
|
||||
|
||||
ctx.killerMoves = {};
|
||||
ctx.history.Clear();
|
||||
ctx.positionHistory = {};
|
||||
|
||||
continue;
|
||||
}
|
||||
|
||||
// parse UCI "go" command
|
||||
if (input.find("go") != std::string::npos) {
|
||||
ParseGo(board, input, ctx.get());
|
||||
ParseGo(board, input, ctx);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -214,7 +159,7 @@ void UCILoop(Board &board) {
|
||||
// parse UCI "stop" command
|
||||
if (input.find("stop") != std::string::npos) {
|
||||
// stop the loop
|
||||
ctx->searchStopped = true;
|
||||
ctx.searchStopped = true;
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -226,7 +171,7 @@ void UCILoop(Board &board) {
|
||||
}
|
||||
|
||||
if (input.find("setoption") != std::string::npos) {
|
||||
SetOption(input, ctx.get());
|
||||
SetOption(input, ctx);
|
||||
continue;
|
||||
}
|
||||
|
||||
@@ -261,4 +206,4 @@ void UCILoop(Board &board) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user