69 Commits
Author SHA1 Message Date
rektdie 3135f430ad fixed pthread bug on windows | bench 10419455 2025-08-23 23:57:36 +02:00
rektdie c07858dab4 added an import to uci.cpp | bench 10419455 2025-08-23 22:14:25 +02:00
rektdie 08ac91b842 changed uci print version | bench 10419455 2025-08-23 19:35:16 +02:00
rektdie 9cadd512cf increased max plies and depths | bench 10419455 2025-08-22 18:00:21 +02:00
rektdie 53cad5f0cb Merge pull request #89 from rektdie/tt-read-fix
Tt read fix bench 10419455
2025-08-22 14:31:24 +02:00
rektdie 817d589042 small bugfix in datagen | bench 10419455 2025-08-21 15:26:49 +02:00
rektdie ec46fddfe5 returning entry by copy instead of pointer | bench 10419455 2025-08-20 02:14:58 +02:00
rektdie 0fd1add2c4 Merge pull request #88 from rektdie/tthit-no-rfp
preventing rfp when tt hit | bench 10038648
2025-08-07 00:27:15 +02:00
rektdie d9f3d0f15f preventing rfp when tt hit | bench 10038648 2025-08-06 23:29:31 +02:00
rektdie da248009a4 Merge pull request #87 from rektdie/tt-test
Tt test bench 10099292
2025-08-06 16:53:28 +02:00
rektdie ff471034f7 changed thread stack size to 8MB | bench 10099292 2025-08-06 14:36:07 +02:00
rektdie 462cb5b8ef changed std::thread to pthread | bench 10099292 2025-08-06 14:17:52 +02:00
rektdie 82255ee46d debug build | bench 63246 2025-08-06 13:22:59 +02:00
rektdie 760894dd1a fixed ttHit bool | bench 10099292 2025-08-06 02:29:11 +02:00
rektdie 311fc28c1c removed ReadEntry function | bench 10412097 2025-08-06 01:54:04 +02:00
rektdie feb11b0b08 lowered bnch depth | bench 5442689 2025-08-05 15:57:33 +02:00
rektdie a4c1a87110 Merge pull request #86 from rektdie/lmr-conthist
added 1 ply conthist to lmr | bench 25271003
2025-08-05 12:00:49 +02:00
rektdie 5bd44bfd48 added 1 ply conthist to lmr | bench 25271003 2025-08-05 03:07:30 +02:00
rektdie 20f1202c45 Merge pull request #85 from rektdie/2-ply-conthist
contest helper functions bench 24146828
2025-08-05 02:57:49 +02:00
rektdie 0e88db9b4c removed git markers | bench 24146828 2025-08-05 02:57:11 +02:00
rektdie 21148655dd fixed move scores | bench 2451113 2025-08-05 02:54:12 +02:00
rektdie 092ca2a2d1 temporarily removed 2ply conthist | bench 24146828 2025-08-05 02:52:12 +02:00
rektdie b74f6f4cbb storing otherColor in stack | bench 2298837 2025-08-05 02:42:01 +02:00
rektdie f581d919b9 different indexing for conthist | bench 2298837 2025-08-05 02:42:01 +02:00
rektdie cdfb752bfa removed unused functions & variables | bench 24146828 2025-08-05 01:13:57 +02:00
rektdie f0280a77ff Update nnue.cpp
bench 24146828
2025-08-04 20:19:10 +02:00
rektdie 994f39421d added support for mac | bench 24146828 2025-08-04 19:46:55 +02:00
rektdie 8e56bd786b Merge pull request #84 from rektdie/net1.7
trained new 1024HL net on ~3b positions | bench 24146828
2025-08-02 19:53:24 +02:00
rektdie b60860b82d trained new 1024HL net on ~3b positions | bench 24146828 2025-08-02 13:46:23 +02:00
rektdie 720fd40176 removed adj and pruning disabling during datagen | bench 26088050 2025-07-31 07:34:34 +02:00
rektdie e6318f6ff4 added adj to datagen + skipping uneven starting positions + no pruninging in movesloop in datagen | bench 26088050 2025-07-30 09:48:13 +02:00
rektdie 7887e04cc5 renamed singular score variable | bench 26088050 2025-07-29 03:18:40 +02:00
rektdie efad38fb0f Merge pull request #83 from rektdie/SE
Se bench 26088050
2025-07-29 03:01:04 +02:00
rektdie dbeec1b9c6 removed cutnode from SE | bench 27398493 2025-07-28 23:37:02 +02:00
rektdie 68377cbf7b added cutnode to SE | bench 1894069 2025-07-28 23:10:51 +02:00
rektdie a077d9bd3e added SE | bench 3280769 2025-07-28 23:04:52 +02:00
rektdie 62b9e205fc printing remaining time during datagen | bench 2172902 2025-07-25 16:37:06 +02:00
rektdie eda2480d59 Merge pull request #82 from rektdie/nmp-improving
added including to nmp + lowered condition depth by one | bench 2172902
2025-07-23 08:17:42 +02:00
rektdie 31149c7450 added including to nmp + lowered condition depth by one | bench 2172902 2025-07-23 07:42:21 +02:00
rektdie 7dbde30f08 Merge pull request #81 from rektdie/lmr-move-number
changed lmr condition | bench 2450653
2025-07-22 07:36:38 +02:00
rektdie 82a4fcdeaf changed lmr condition | bench 2450653 2025-07-21 19:08:51 +02:00
rektdie 96411d9c8f Merge pull request #80 from rektdie/history-fp
added history to fp | bench 2298837
2025-07-21 12:47:03 +02:00
rektdie d85edd9faf added history to fp | bench 2298837 2025-07-21 12:26:15 +02:00
rektdie dbde65f083 reverted accidental push | bench 2985672 2025-07-20 15:07:40 +02:00
rektdie e435ae0818 Merge pull request #79 from rektdie/conthist
bench 2985672
2025-07-20 13:06:45 +02:00
rektdie f666d1ea05 bugfix: ScoreMove didnt score the passed move, but the last in the ss | bench 2985672 2025-07-20 12:14:35 +02:00
rektdie 1832d460c5 reverted lmp formula | bench 2734093 2025-07-20 04:45:49 +02:00
rektdie 43c59f29f9 diff lmp formula | bench 2941128 2025-07-20 04:45:49 +02:00
rektdie 20c636a3b4 added Eren's lmp formula too | bench 2097722 2025-07-20 04:45:49 +02:00
rektdie 33bafd461a changed move order values | bench 2734093 2025-07-20 04:45:49 +02:00
rektdie dab5bad089 forgot to reset on ucinewgame | bench 2533622 2025-07-20 04:45:49 +02:00
rektdie 2ab4868c75 resetting ss | bench 2533622 2025-07-20 04:45:49 +02:00
rektdie 4fe645ff1b changed move ordering values | bench 2533622 2025-07-20 04:45:49 +02:00
rektdie 2181d446bf changed move ordering values | bench 2589729 2025-07-20 04:45:49 +02:00
rektdie db565c6100 changed conthist max value to half of normal hist | bench 2646638 2025-07-20 04:45:49 +02:00
rektdie d7c4383783 changed conthist max value | bench 3012327 2025-07-20 04:45:49 +02:00
rektdie c58d29ac61 added conthist malus | bench 3731826 2025-07-20 04:45:49 +02:00
rektdie 84f2fd0ea8 added 1-ply conthist without malus | bench 3298447 2025-07-20 04:45:49 +02:00
rektdie 64a85bf780 bugfix: passed ctx as std::ref in ParseGo | bench 2695095 2025-07-20 04:45:10 +02:00
rektdie 8d6314aef3 Merge pull request #78 from rektdie/net1.6
new 512HL net trained on ~3billion positions | bench 2695095
2025-07-16 01:27:33 +02:00
rektdie 9979441138 new 512HL net trained on ~3billion positions | bench 2695095 2025-07-15 16:27:47 +02:00
rektdie 0e48eefc72 printing score cp correctly | bench 3509444 2025-06-09 13:11:11 +02:00
rektdie 5e4b1faa0a Merge pull request #76 from rektdie/tt-fix
storing currMove to tt when in cutnode | bench 3509444
2025-06-06 11:29:19 +02:00
rektdie c890b04a47 storing currMove to tt when in cutnode | bench 3509444 2025-06-06 11:16:40 +02:00
rektdie bec0f3275f Merge pull request #75 from rektdie/SE
minor rework in tt | bench 3415609
2025-06-06 09:58:43 +02:00
rektdie 4564d10bcf minor rework in tt | bench 3415609 2025-06-06 09:58:24 +02:00
rektdie dec219e4d7 changed raw ctx pointer to unique | bench 3415609 2025-06-06 06:18:57 +02:00
rektdie b1fd8e6021 Merge pull request #74 from rektdie/conthist
storing searchcontext on the heap instead of the stack | bench 3415609
2025-06-05 13:38:08 +02:00
rektdie 5a45d29f66 storing searchcontext on the heap instead of the stack | bench 3415609 2025-06-05 02:03:43 +02:00
14 changed files with 630 additions and 384 deletions

No files matched your search

+36 -8
View File
@@ -1,42 +1,70 @@
# 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))
# Final binary
$(EXE)$(EXE_EXT): $(OBJS)
$(CXX) -DEVALFILE=\"$(EVALFILE)\" $^ ./external/fmt/format.cc -o $@ -O3 -fuse-ld=lld -march=native -flto -static
FMT_SRC := $(FMT_DIR)/format.cc
FMT_OBJ := $(OBJ_DIR)/format.o
$(EXE)$(EXE_EXT): $(OBJS) $(FMT_OBJ)
$(CXX) $(CXXFLAGS) -DEVALFILE=\"$(EVALFILE)\" $^ -o $@ $(LDFLAGS)
# Compile .cpp -> .o
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp | $(OBJ_DIR)
$(CXX) -std=c++20 -c -o $@ $< -O3 -march=native -flto -static
$(CXX) $(CXXFLAGS) -c -o $@ $<
$(FMT_OBJ): $(FMT_SRC) | $(OBJ_DIR)
$(CXX) $(CXXFLAGS) -c -o $@ $<
# Create object directory
$(OBJ_DIR):
$(MKDIR) $(OBJ_DIR)
# Clean up and rebuild
.PHONY: clean
clean:
ifeq ($(OS),Windows_NT)
+23
View File
@@ -0,0 +1,23 @@
// 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;
BIN
View File
Binary file not shown.
+4 -4
View File
@@ -1,6 +1,7 @@
#include <cstring>
#include <string_view>
#include <array>
#include <memory>
#include "benchmark.h"
#include "search.h"
#include "stopwatch.h"
@@ -62,15 +63,14 @@ constexpr std::array<std::string_view, 50> fenPositions = {
void RunBenchmark() {
Board board;
int depth = BENCH_DEPTH;
SearchContext ctx;
auto ctx = std::make_unique<SearchContext>();
Stopwatch sw;
for (int i = 0; i < fenPositions.size(); i++) {
board.SetByFen(fenPositions[i]);
SearchPosition<bench>(board, SearchParams(), ctx);
SearchPosition<bench>(board, SearchParams(), ctx.get());
}
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
View File
@@ -1,6 +1,6 @@
#pragma once
#include <string>
constexpr int BENCH_DEPTH = 11;
constexpr int BENCH_DEPTH = 13;
void RunBenchmark();
+126 -37
View File
@@ -2,6 +2,7 @@
#include <fstream>
#include <iomanip>
#include <thread>
#include <tuple>
#include <atomic>
#include <mutex>
#include "datagen.h"
@@ -10,8 +11,11 @@
#include "movegen.h"
#include "utils.h"
// OS-dependent threading includes
#ifdef _WIN32
#include <windows.h>
#include <windows.h>
#else
#include <pthread.h>
#endif
#ifdef _WIN32
@@ -30,21 +34,21 @@ static void ShowCursor() {
cursorInfo.bVisible = TRUE;
SetConsoleCursorInfo(hConsole, &cursorInfo);
}
#endif
static void HideCursorLinux() {
#else
static void HideCursor() {
std::cout << "\033[?25l";
}
static void ShowCursorLinux() {
static void ShowCursor() {
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;
@@ -54,19 +58,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);
@@ -77,7 +81,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;
}
@@ -127,13 +131,32 @@ static void PlayGames(int id, std::atomic<int>& positions, std::atomic<bool>& st
exit(-1);
}
while (!stopFlag) {
Game game;
Board board;
SEARCH::SearchContext ctx;
PlayRandMoves(board, ctx);
if (IsGameOver(board, ctx)) continue;
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 startpos = board;
SearchResults safeResults;
@@ -141,24 +164,25 @@ 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)) {
SearchResults results = SEARCH::SearchPosition<SEARCH::datagen>(board, SearchParams(), ctx);
while (!IsGameOver(board, ctx.get())) {
SearchResults results = SEARCH::SearchPosition<SEARCH::datagen>(board, SearchParams(), ctx.get());
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)) {
if (!SEARCH::IsDraw(board, ctx.get())) {
wdl = board.sideToMove ? 2 : 0;
}
@@ -178,24 +202,62 @@ 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";
HideCursorLinux();
HideCursor();
#endif
std::atomic<int> positions = 0;
std::atomic<bool> stopFlag = false;
#ifdef _WIN32
// Windows implementation using std::thread
std::vector<std::thread> 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)));
for (int i = 0; i < threads - 1; ++i) {
CreateWorkerThread(i, positions, stopFlag, workerThreads);
}
#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) {
@@ -203,22 +265,28 @@ void Run(int targetPositions, int threads) {
std::this_thread::sleep_for(std::chrono::seconds(1));
}
PrintProgress(positions, targetPositions, sw, threads);
stopFlag = true;
for (auto& thread : workerThreads) {
#ifdef _WIN32
// Join Windows threads
for (std::thread& 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
ShowCursorLinux();
ShowCursor();
#endif
}
@@ -243,9 +311,6 @@ 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;
@@ -261,7 +326,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;
@@ -285,6 +350,31 @@ 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);
@@ -309,5 +399,4 @@ void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int
std::cout << std::endl;
}
}
}
-114
View File
@@ -299,120 +299,6 @@ 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;
+43 -8
View File
@@ -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,7 +74,6 @@ 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
@@ -93,6 +92,47 @@ 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");
@@ -128,17 +168,11 @@ 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);
@@ -147,6 +181,7 @@ int Forward(const Board& board, const Network& net) {
eval += net.output_bias[outputBucket];
return (eval * SCALE) / (QA * QB);
}
+2 -2
View File
@@ -8,7 +8,7 @@
class Board;
#ifdef __AVX512F__
constexpr usize ALIGNMENT = 64;
constexpr size_t 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 = 256;
constexpr size_t HL_SIZE = 1024;
constexpr size_t OUTPUT_BUCKETS = 8;
constexpr int16_t SCALE = 400;
+254 -132
View File
@@ -22,10 +22,30 @@ void InitLMRTable() {
}
}
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;
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;
}
if (move.IsCapture()) {
@@ -36,49 +56,60 @@ static int ScoreMove(Board &board, Move &move, int ply, SearchContext& ctx) {
targetType = Pawn;
}
return 30000 * ((SEE(board, move, -100))) + moveScoreTable[attackerType][targetType];
return 50000 * ((SEE(board, move, -100))) + (100 * targetType - attackerType + 105);
} else {
if (ctx.killerMoves[0][ply] == move) {
return 20000;
} else if (ctx.killerMoves[1][ply] == move) {
return 18000;
if (ctx->killerMoves[0][ply] == move) {
return 41000;
} else if (ctx->killerMoves[1][ply] == move) {
return 40000;
} else {
// Max 16384
return ctx.history[board.sideToMove][move.MoveFrom()][move.MoveTo()];
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;
}
}
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++) {
@@ -89,9 +120,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;
}
@@ -106,26 +137,32 @@ 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);
}
static int GetReductions(Board &board, Move &move, int depth, int moveSeen, int ply, bool cutnode, SearchContext& ctx) {
template <bool isPV>
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 >= 3 && !move.IsCapture()) {
if (depth >= 3 && moveSeen >= 2 + (2 * isPV) && !move.IsCapture()) {
reduction = lmrTable[depth][moveSeen];
if (cutnode)
reduction += 2;
// History LMR
int historyReduction = ctx.history[board.sideToMove][move.MoveFrom()][move.MoveTo()] / 8192;
int historyReduction = ctx->history[board.sideToMove][move.MoveFrom()][move.MoveTo()];
if (ply > 0)
historyReduction += ctx->conthist.GetOnePly(board, move, ctx, ply);
historyReduction /= 8192;
reduction -= historyReduction;
}
@@ -165,7 +202,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;
@@ -188,7 +225,7 @@ bool SEE(Board& board, Move& move, int threshold) {
attackers |= MOVEGEN::getRookAttack(to, occupied) & rooks;
attackers &= occupied;
color = !color;
balance = -balance - 1 - SEEPieceValues[nextVictim];
@@ -205,37 +242,39 @@ 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;
int bestScore = NNUE::net.Evaluate(board);
ctx.ss[ply].eval = bestScore;
if (ply > ctx->seldepth)
ctx->seldepth = ply;
TTEntry *entry = ctx.TT.GetRawEntry(board.hashKey);
if (entry->hashKey == board.hashKey) {
bestScore = entry->score;
int bestScore = NNUE::net.Evaluate(board);
ctx->ss[ply].eval = bestScore;
if (!ctx->excluded) {
TTEntry entry = ctx->TT.GetRawEntry(board.hashKey);
if (entry.hashKey == board.hashKey) {
bestScore = entry.score;
}
}
@@ -258,14 +297,18 @@ 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) {
@@ -281,87 +324,98 @@ 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;
// if NOT PV node then we try to hit the TTable
TTEntry entry;
if (!ctx->excluded)
entry = ctx->TT.GetRawEntry(board.hashKey);
const bool ttHit = entry.hashKey == board.hashKey;
if constexpr (!isPV) {
SearchResults entry = ctx.TT.ReadEntry(board.hashKey, depth, alpha, beta);
if (entry.score != invalidEntry) {
return entry;
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);
}
}
}
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()) {
if (!board.InCheck() && !ctx->excluded) {
if (ply) {
// Reverse Futility Pruning
int margin = 100 * (depth - improving);
if (staticEval - margin >= beta && depth < 7) {
if (!ttHit && staticEval - margin >= beta && depth < 7) {
return (beta + (staticEval - beta) / 3);
}
// Null Move Pruning
if (!ctx.doingNullMove && staticEval >= beta) {
if (depth >= 3 && !board.InPossibleZug()) {
if (!ctx->doingNullMove && staticEval >= beta) {
if (depth > 1 && !board.InPossibleZug()) {
Board copy = board;
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;
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;
}
}
}
@@ -383,6 +437,9 @@ 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
@@ -391,6 +448,7 @@ 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) {
@@ -401,22 +459,49 @@ 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 fpMargin = 100 * depth;
int historyScore = ctx->history[board.sideToMove][currMove.MoveFrom()][currMove.MoveTo()];
int fpMargin = 100 * depth + historyScore / 32;
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;
if (copy.positionIndex >= ctx.positionHistory.size()) {
ctx.positionHistory.resize(copy.positionIndex + 100);
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;
}
ctx.positionHistory[copy.positionIndex] = copy.hashKey;
ctx.nodes++;
// PVS SEE
int SEEThreshold = currMove.IsQuiet() ? -80 * depth : -30 * depth * depth;
@@ -424,10 +509,9 @@ 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 reductions = GetReductions(board, currMove, depth, moveSeen, ply, cutnode, ctx);
int newDepth = depth + copy.InCheck() - 1;
int newDepth = depth + copy.InCheck() - 1 + extension;
// First move (suspected PV node)
if (!moveSeen) {
@@ -457,7 +541,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;
@@ -467,20 +551,57 @@ 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);
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);
}
}
}
// 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);
}
}
ctx.TT.WriteEntry(board.hashKey, depth, score, CutNode, Move());
if (!ctx->excluded)
ctx->TT.WriteEntry(board.hashKey, depth, score, CutNode, currMove);
return score;
}
@@ -490,7 +611,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);
}
}
@@ -502,8 +623,9 @@ SearchResults PVS(Board& board, int depth, int alpha, int beta, int ply, SearchC
}
}
if (ctx.searchStopped) return 0;
ctx.TT.WriteEntry(board.hashKey, depth, results.score, nodeType, results.bestMove);
if (ctx->searchStopped) return 0;
if (!ctx->excluded)
ctx->TT.WriteEntry(board.hashKey, depth, results.score, nodeType, results.bestMove);
return results;
}
@@ -533,7 +655,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;
@@ -551,14 +673,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();
@@ -573,7 +695,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) {
@@ -583,24 +705,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 " << UTILS::ConvertToWhiteRelative(board, safeResults.score);
std::cout << " nodes " << ctx.nodes << " nps " << int(ctx.nodes/ctx.sw.GetElapsedSec());
std::cout << " hashfull " << ctx.TT.GetUsedPercentage();
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 << " 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;
}
}
@@ -611,17 +733,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);
@@ -656,16 +778,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);
}
+45 -24
View File
@@ -7,6 +7,8 @@
#include "stopwatch.h"
#include "tt.h"
#include "../external/multi_array.h"
namespace SEARCH {
enum searchMode {
@@ -17,8 +19,8 @@ enum searchMode {
};
constexpr int MATE_SCORE = 32767;
constexpr int MAX_DEPTH = 64;
constexpr int MAX_PLY = 128;
constexpr int MAX_DEPTH = 128;
constexpr int MAX_PLY = 512;
constexpr int MAX_HISTORY = 16384;
constexpr int32_t ScoreNone = -255000;
@@ -31,10 +33,35 @@ 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:
int historyMoves[2][64][64];
MultiArray<int, 2, 64, 64> historyMoves;
public:
void Update(bool stm, Move move, int bonus) {
int clampedBonus = std::clamp(bonus, -MAX_HISTORY, MAX_HISTORY);
@@ -43,13 +70,7 @@ public:
}
void Clear() {
for (auto &side : historyMoves) {
for (auto &from : side) {
for (auto &to : from) {
to = 0;
}
}
}
std::fill(&historyMoves[0][0][0], &historyMoves[0][0][0] + sizeof(historyMoves) / sizeof(int), 0);
}
auto& operator[](int index) {
@@ -92,6 +113,10 @@ public:
class Stack {
public:
int32_t eval = ScoreNone;
int pieceType = -1;
int moveTo = -1;
bool side = -1;
};
class SearchContext {
@@ -101,12 +126,15 @@ 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{};
@@ -121,33 +149,26 @@ public:
SearchContext(){
pvLine.Clear();
history.Clear();
conthist.Clear();
TT.Clear();
sw.Restart();
killerMoves = {};
positionHistory.reserve(1000);
ss = {};
positionHistory.resize(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);
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);
void ListScores(Board &board, SearchContext* ctx);
int MoveEstimatedValue(Board& board, Move& move);
}
+1 -20
View File
@@ -1,24 +1,5 @@
#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()];
@@ -27,4 +8,4 @@ void TTable::WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move b
current->score = score;
current->depth = depth;
current->bestMove = bestMove;
}
}
+12 -6
View File
@@ -27,17 +27,23 @@ public:
uint8_t depth = 0;
uint8_t nodeType = 0;
TTEntry() {}
TTEntry(int16_t score) {
this->score = score;
}
operator U64() {
return hashKey;
}
};
// 64 MB
// 1024 MB
constexpr U64 maxHash = (1024 * 1000000) / sizeof(TTEntry);
// 5 MB
// 8 MB
constexpr U64 defaultHash = (8 * 1000000) / sizeof(TTEntry);
constexpr int invalidEntry = 111111;
constexpr int16_t invalidEntry = 11111;
class TTable {
private:
@@ -55,9 +61,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
@@ -71,7 +77,7 @@ public:
return count;
}
SearchResults ReadEntry(U64 &hashKey, int depth, int alpha, int beta);
TTEntry ReadEntry(U64 &hashKey, int depth, int alpha, int beta);
void WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move besteMove);
};
+83 -28
View File
@@ -1,9 +1,9 @@
#include "uci.h"
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string>
#include <thread>
#include <tuple>
#include <memory>
#include "types.h"
#include "movegen.h"
#include "search.h"
@@ -12,7 +12,14 @@
#include "utils.h"
#include "datagen.h"
static void ParsePosition(Board &board, std::string_view command, SEARCH::SearchContext& ctx) {
// 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) {
if (command.find("startpos") != std::string::npos) {
board.SetByFen(StartingFen);
}
@@ -32,8 +39,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) {
bool isLegal = board.MakeMove(UTILS::parseMove(board, move));
ctx.positionHistory[board.positionIndex] = board.hashKey;
board.MakeMove(UTILS::parseMove(board, move));
ctx->positionHistory[board.positionIndex] = board.hashKey;
}
}
@@ -69,7 +76,56 @@ static int ReadParam(std::string param, std::string &command) {
return 0;
}
static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext& ctx) {
#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) {
SearchParams params;
params.wtime = ReadParam("wtime", command);
@@ -82,26 +138,23 @@ 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;
}
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();
}
StartSearchThread(board, params, ctx);
}
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 v1.0" << std::endl;
std::cout << "id name Eleanor v2.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;
@@ -111,7 +164,7 @@ static void PrintEngineInfo() {
void UCILoop(Board &board) {
std::string input = "";
SEARCH::SearchContext ctx;
auto ctx = std::make_unique<SEARCH::SearchContext>();
// main loop
while (true) {
@@ -125,7 +178,7 @@ void UCILoop(Board &board) {
// parse UCI "position" command
if (input.find("position") != std::string::npos) {
ParsePosition(board, input, ctx);
ParsePosition(board, input, ctx.get());
continue;
}
@@ -133,20 +186,22 @@ 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.positionHistory = {};
ctx->TT.Clear();
ctx->killerMoves = {};
ctx->history.Clear();
ctx->conthist.Clear();
ctx->positionHistory = {};
ctx->ss = {};
continue;
}
// parse UCI "go" command
if (input.find("go") != std::string::npos) {
ParseGo(board, input, ctx);
ParseGo(board, input, ctx.get());
continue;
}
@@ -159,7 +214,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;
}
@@ -171,7 +226,7 @@ void UCILoop(Board &board) {
}
if (input.find("setoption") != std::string::npos) {
SetOption(input, ctx);
SetOption(input, ctx.get());
continue;
}
@@ -206,4 +261,4 @@ void UCILoop(Board &board) {
continue;
}
}
}
}