Compare commits
294
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e172907038 | ||
|
|
69068acb99 | ||
|
|
cd2265a46b | ||
|
|
cae93f13a5 | ||
|
|
5a1bcf547c | ||
|
|
3a813876f4 | ||
|
|
a1115b3373 | ||
|
|
3b79f22ec7 | ||
|
|
f3411c524c | ||
|
|
134af1abde | ||
|
|
1e41671002 | ||
|
|
dd831d14bf | ||
|
|
ae3a39cf04 | ||
|
|
aa120b14f9 | ||
|
|
4c67267c8c | ||
|
|
2c4292c485 | ||
|
|
f77c4c1fbd | ||
|
|
e64c6c60b9 | ||
|
|
de1d0e22ff | ||
|
|
d593833e9e | ||
|
|
a2297ed04e | ||
|
|
ecd57607f3 | ||
|
|
be9982eb75 | ||
|
|
babe3d0db0 | ||
|
|
30e54c2b71 | ||
|
|
1470ad34a8 | ||
|
|
f23a59730b | ||
|
|
dbd56e0c21 | ||
|
|
390ee23e75 | ||
|
|
4ebdeb54f6 | ||
|
|
4e437d52fc | ||
|
|
a3255581fb | ||
|
|
24a36414f8 | ||
|
|
f0b4e42f17 | ||
|
|
4e95413c4d | ||
|
|
19ea29b902 | ||
|
|
9fcef9c3c8 | ||
|
|
7ab07c8c71 | ||
|
|
7e3287be71 | ||
|
|
9642d606dc | ||
|
|
dc52b7846a | ||
|
|
0b18805f00 | ||
|
|
469ff7237c | ||
|
|
0f410353d1 | ||
|
|
b2eb9ca81a | ||
|
|
e4d114a763 | ||
|
|
68d7dcbccb | ||
|
|
7db4fcf59c | ||
|
|
00f0d06381 | ||
|
|
0f849c1b7f | ||
|
|
4c4e6d15c8 | ||
|
|
d1bcec29ce | ||
|
|
c4886db1fe | ||
|
|
caac437db7 | ||
|
|
de6b96bbf8 | ||
|
|
34018414df | ||
|
|
d4ed1a3f40 | ||
|
|
f9160084a7 | ||
|
|
04b1187963 | ||
|
|
f69da36c7c | ||
|
|
e3184752c0 | ||
|
|
cfcd24318b | ||
|
|
13cb768c67 | ||
|
|
372ab43e8b | ||
|
|
65b809d115 | ||
|
|
b239ce6bf0 | ||
|
|
e69294dfa3 | ||
|
|
454d9e61c1 | ||
|
|
1f2bb52418 | ||
|
|
e6ec17090b | ||
|
|
67c9e59939 | ||
|
|
f1df87a22d | ||
|
|
9c5335b4ef | ||
|
|
e98241cc7f | ||
|
|
740be80922 | ||
|
|
eb133efba1 | ||
|
|
cfe58552f2 | ||
|
|
36640bfe7e | ||
|
|
a6549e256a | ||
|
|
21a64294cf | ||
|
|
ba4ffca56f | ||
|
|
081d54dc55 | ||
|
|
64981dad3e | ||
|
|
a6472893a8 | ||
|
|
81a9a89ac8 | ||
|
|
f9e0f5db1a | ||
|
|
aafc6af697 | ||
|
|
82737f243f | ||
|
|
0250f9e954 | ||
|
|
b3ffc1f32f | ||
|
|
5f8e143cf8 | ||
|
|
2e84a1e3ab | ||
|
|
9d7567dfea | ||
|
|
c9f6ac3849 | ||
|
|
feb441c380 | ||
|
|
0a7be07d0f | ||
|
|
61da1c4d58 | ||
|
|
2bde715482 | ||
|
|
41b421ded5 | ||
|
|
baf0741e0d | ||
|
|
d99a35fdf0 | ||
|
|
2e952b0f92 | ||
|
|
b3c3182fec | ||
|
|
20196cb545 | ||
|
|
e33b88277b | ||
|
|
9885596770 | ||
|
|
83c9a2c51c | ||
|
|
ad7041c0a4 | ||
|
|
73d2945e95 | ||
|
|
b1b7b8234d | ||
|
|
8a2ada7165 | ||
|
|
506487f396 | ||
|
|
05ce50e647 | ||
|
|
c2f2730114 | ||
|
|
e06e1cdac1 | ||
|
|
94eced67f6 | ||
|
|
b5a34eda5e | ||
|
|
8b2c55eae4 | ||
|
|
aea6985817 | ||
|
|
e7731361cd | ||
|
|
7586608aaa | ||
|
|
1814cbc755 | ||
|
|
020132ea3c | ||
|
|
1bdedebf96 | ||
|
|
692ec62aac | ||
|
|
ce3ed3b6d1 | ||
|
|
345c6d21d9 | ||
|
|
0d126aa6a7 | ||
|
|
5ca125e336 | ||
|
|
855e5c2377 | ||
|
|
7e621311e6 | ||
|
|
b2a475ff5f | ||
|
|
4b3e8020fa | ||
|
|
194c3d3bc4 | ||
|
|
b929963f91 | ||
|
|
079959e6d4 | ||
|
|
64b2e3d9b1 | ||
|
|
eac21b424a | ||
|
|
cce6f5dd0c | ||
|
|
7e4d5889a8 | ||
|
|
71d3b3309a | ||
|
|
d662594814 | ||
|
|
9be74da127 | ||
|
|
85cdb7e077 | ||
|
|
a3d2f352d3 | ||
|
|
4dcf0d04a0 | ||
|
|
91b5062549 | ||
|
|
a7ef4ee4a9 | ||
|
|
2e802d7dfe | ||
|
|
81bd4648e3 | ||
|
|
48bbfa7114 | ||
|
|
320c43cdd3 | ||
|
|
a9b51e384f | ||
|
|
1fb235fb3f | ||
|
|
0f748da56c | ||
|
|
fd2168d529 | ||
|
|
41dabc2150 | ||
|
|
f114a6d0bb | ||
|
|
7cf8b381ce | ||
|
|
1f0b36764d | ||
|
|
2fd3cf0d2a | ||
|
|
931b6fa999 | ||
|
|
ba3505afc8 | ||
|
|
6ed9e882f8 | ||
|
|
0df0921c47 | ||
|
|
865eac5782 | ||
|
|
9421d254f7 | ||
|
|
d71e264bb9 | ||
|
|
031b5285ed | ||
|
|
9e5f131105 | ||
|
|
f4bf94eb98 | ||
|
|
75022da950 | ||
|
|
5bc4459111 | ||
|
|
65f7b3f38a | ||
|
|
370dc43660 | ||
|
|
f1b99803a1 | ||
|
|
7595b0a3fd | ||
|
|
cdedcbb5f5 | ||
|
|
49994dc480 | ||
|
|
6c8869040f | ||
|
|
6288bdc3f8 | ||
|
|
9e068e3f7d | ||
|
|
7ac8efa027 | ||
|
|
5754772a70 | ||
|
|
90bdd3cc96 | ||
|
|
d35eb66dbc | ||
|
|
2e46f0d1cd | ||
|
|
9ce97946d5 | ||
|
|
90cfd93135 | ||
|
|
a56e983bf7 | ||
|
|
66865fa84e | ||
|
|
acee84c134 | ||
|
|
2474c13fe0 | ||
|
|
d37ba0cdaa | ||
|
|
925289015f | ||
|
|
318d52b2dd | ||
|
|
6ed9e6f0c8 | ||
|
|
c6f2c3cacb | ||
|
|
b3472092e2 | ||
|
|
d76e7796bc | ||
|
|
0d3c23ed73 | ||
|
|
222a079c1f | ||
|
|
d5d51c9888 | ||
|
|
3a02122fd4 | ||
|
|
e8aec47b71 | ||
|
|
17a0a97896 | ||
|
|
be6585268b | ||
|
|
916da35e4f | ||
|
|
5c247f5e1d | ||
|
|
a8ac4c7feb | ||
|
|
f71e6c20e1 | ||
|
|
1e62f6adef | ||
|
|
0ff5a226ee | ||
|
|
670907dd8c | ||
|
|
5c6d75e9ef | ||
|
|
6b5c1bbaa7 | ||
|
|
480216e1c8 | ||
|
|
5358bd599e | ||
|
|
435805a207 | ||
|
|
2ef378d4d2 | ||
|
|
0dfbb1c27b | ||
|
|
b152fd40eb | ||
|
|
93339c7728 | ||
|
|
4a050aeddb | ||
|
|
136af4adef | ||
|
|
307bbfede2 | ||
|
|
e7d8044745 | ||
|
|
10a0f502ae | ||
|
|
1dd0e33d2b | ||
|
|
729d24c7c8 | ||
|
|
e2eb763012 | ||
|
|
b4b804027c | ||
|
|
9d26dc028d | ||
|
|
ca51e59dd9 | ||
|
|
0cb4ba1a29 | ||
|
|
83e36b0883 | ||
|
|
bf9b97aaba | ||
|
|
861a354215 | ||
|
|
c108bfa786 | ||
|
|
271ec4dc2a | ||
|
|
78aa6e2338 | ||
|
|
5bf770c1a9 | ||
|
|
32b2b9c92e | ||
|
|
4c04bf2830 | ||
|
|
5519f300b5 | ||
|
|
1c4762e872 | ||
|
|
32691d2d65 | ||
|
|
3e652df8e8 | ||
|
|
f32251ac98 | ||
|
|
cabebb502e | ||
|
|
6d2500428e | ||
|
|
de2d441b0f | ||
|
|
4123ab731f | ||
|
|
014d5e05b1 | ||
|
|
f81a730994 | ||
|
|
07abe2529e | ||
|
|
d2586bec7d | ||
|
|
f5f51496b3 | ||
|
|
4579172fab | ||
|
|
a3d505aec4 | ||
|
|
9b86aaa0a1 | ||
|
|
1ca2ba0352 | ||
|
|
95945633f1 | ||
|
|
cc64cbd6a9 | ||
|
|
875363376b | ||
|
|
21b64a271a | ||
|
|
cba880886b | ||
|
|
768b8ed178 | ||
|
|
4b2f342d85 | ||
|
|
cb9051c477 | ||
|
|
9f28552643 | ||
|
|
070528286c | ||
|
|
b6c9bbbb8d | ||
|
|
c365bd58d8 | ||
|
|
40339b2d45 | ||
|
|
6ccd416840 | ||
|
|
2e1f84bda5 | ||
|
|
bf7adcb06b | ||
|
|
1cf5a2971d | ||
|
|
8d552cefd6 | ||
|
|
9bb603200c | ||
|
|
ee404a9992 | ||
|
|
cc8a9a625b | ||
|
|
f788005e40 | ||
|
|
1e073bb30d | ||
|
|
e46076116f | ||
|
|
ab68f5a6b6 | ||
|
|
769979cafe | ||
|
|
06b24ef1f2 | ||
|
|
3451f825bb | ||
|
|
a52bb1f967 | ||
|
|
86590918e1 | ||
|
|
5f0ce8c1cf | ||
|
|
e282098265 |
No files matched your search
@@ -1,45 +1,58 @@
|
|||||||
# Define directories
|
# Define directories
|
||||||
SRC_DIR := source
|
SRC_DIR := source
|
||||||
OBJ_DIR := obj
|
OBJ_DIR := obj
|
||||||
FMT_DIR := external/fmt
|
|
||||||
|
|
||||||
CXX := clang++
|
|
||||||
EXE ?= Eleanor
|
EXE ?= Eleanor
|
||||||
EVALFILE := ./nnue.bin
|
EVALFILE := ./nnue.bin
|
||||||
|
|
||||||
|
CXX := clang++
|
||||||
|
|
||||||
ifeq ($(OS),Windows_NT)
|
ifeq ($(OS),Windows_NT)
|
||||||
UNAME_S := Windows
|
UNAME_S := Windows
|
||||||
EXE_EXT := .exe
|
ARCH := x86_64
|
||||||
MKDIR := mkdir
|
EXE_EXT := .exe
|
||||||
RM := rmdir /s /q
|
MKDIR := mkdir
|
||||||
DEL := del /q
|
RM := rmdir /s /q
|
||||||
PLATFORM := windows
|
DEL := del /q
|
||||||
|
PLATFORM := windows
|
||||||
else
|
else
|
||||||
UNAME_S := $(shell uname -s)
|
UNAME_S := $(shell uname -s)
|
||||||
ARCH := $(shell uname -m)
|
ARCH := $(shell uname -m)
|
||||||
EXE_EXT :=
|
EXE_EXT :=
|
||||||
MKDIR := mkdir -p
|
MKDIR := mkdir -p
|
||||||
RM := rm -rf
|
RM := rm -rf
|
||||||
DEL := rm -f
|
DEL := rm -f
|
||||||
ifeq ($(UNAME_S),Darwin)
|
ifeq ($(UNAME_S),Darwin)
|
||||||
PLATFORM := mac
|
PLATFORM := mac
|
||||||
else
|
else
|
||||||
PLATFORM := unix
|
PLATFORM := unix
|
||||||
endif
|
endif
|
||||||
endif
|
endif
|
||||||
|
|
||||||
|
CXX_BASE := $(notdir $(firstword $(CXX)))
|
||||||
|
CXX_DRIVER_FLAGS :=
|
||||||
CXXFLAGS := -std=c++20 -O3 -flto -Wall
|
CXXFLAGS := -std=c++20 -O3 -flto -Wall
|
||||||
LDFLAGS := -O3 -flto
|
LDFLAGS := -O3 -flto
|
||||||
|
|
||||||
ifeq ($(PLATFORM),mac)
|
ifeq ($(PLATFORM),mac)
|
||||||
ifeq ($(ARCH),arm64)
|
ifeq ($(ARCH),arm64)
|
||||||
ARCH_FLAGS :=
|
ARCH_FLAGS := -mcpu=apple-m1
|
||||||
else
|
else
|
||||||
ARCH_FLAGS := -march=native
|
ARCH_FLAGS := -march=native
|
||||||
endif
|
endif
|
||||||
|
else ifeq ($(PLATFORM),windows)
|
||||||
|
ARCH_FLAGS := -march=native
|
||||||
|
CXX_DRIVER_FLAGS += --target=$(ARCH)-w64-windows-gnu
|
||||||
|
CXXFLAGS += -pthread
|
||||||
|
LDFLAGS += -pthread
|
||||||
|
LDFLAGS += -static -Wl,--stack,8388608
|
||||||
else
|
else
|
||||||
ARCH_FLAGS := -march=native
|
ifeq ($(ARCH),aarch64)
|
||||||
LDFLAGS += -fuse-ld=lld -static
|
ARCH_FLAGS := -mcpu=native
|
||||||
|
else
|
||||||
|
ARCH_FLAGS := -march=native
|
||||||
|
LDFLAGS += -fuse-ld=lld -static
|
||||||
|
endif
|
||||||
endif
|
endif
|
||||||
|
|
||||||
CXXFLAGS += $(ARCH_FLAGS)
|
CXXFLAGS += $(ARCH_FLAGS)
|
||||||
@@ -50,17 +63,11 @@ MAKEFLAGS += -j
|
|||||||
SRCS := $(wildcard $(SRC_DIR)/*.cpp)
|
SRCS := $(wildcard $(SRC_DIR)/*.cpp)
|
||||||
OBJS := $(patsubst $(SRC_DIR)/%.cpp, $(OBJ_DIR)/%.o, $(SRCS))
|
OBJS := $(patsubst $(SRC_DIR)/%.cpp, $(OBJ_DIR)/%.o, $(SRCS))
|
||||||
|
|
||||||
FMT_SRC := $(FMT_DIR)/format.cc
|
$(EXE)$(EXE_EXT): $(OBJS)
|
||||||
FMT_OBJ := $(OBJ_DIR)/format.o
|
$(CXX) $(CXX_DRIVER_FLAGS) $(CXXFLAGS) -DEVALFILE=\"$(EVALFILE)\" $^ -o $@ $(LDFLAGS)
|
||||||
|
|
||||||
$(EXE)$(EXE_EXT): $(OBJS) $(FMT_OBJ)
|
|
||||||
$(CXX) $(CXXFLAGS) -DEVALFILE=\"$(EVALFILE)\" $^ -o $@ $(LDFLAGS)
|
|
||||||
|
|
||||||
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp | $(OBJ_DIR)
|
$(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp | $(OBJ_DIR)
|
||||||
$(CXX) $(CXXFLAGS) -c -o $@ $<
|
$(CXX) $(CXX_DRIVER_FLAGS) $(CXXFLAGS) -c -o $@ $<
|
||||||
|
|
||||||
$(FMT_OBJ): $(FMT_SRC) | $(OBJ_DIR)
|
|
||||||
$(CXX) $(CXXFLAGS) -c -o $@ $<
|
|
||||||
|
|
||||||
$(OBJ_DIR):
|
$(OBJ_DIR):
|
||||||
$(MKDIR) $(OBJ_DIR)
|
$(MKDIR) $(OBJ_DIR)
|
||||||
@@ -74,4 +81,3 @@ else
|
|||||||
@$(RM) $(OBJ_DIR)
|
@$(RM) $(OBJ_DIR)
|
||||||
@$(DEL) $(EXE)$(EXE_EXT)
|
@$(DEL) $(EXE)$(EXE_EXT)
|
||||||
endif
|
endif
|
||||||
$(MAKE)
|
|
||||||
@@ -1,42 +1,39 @@
|
|||||||
|
<div align="center">
|
||||||
<p align="center">
|
<p>
|
||||||
<img src="https://i.postimg.cc/NjR2CdBB/Eleanor.png" alt="Eleanor Chess Engine">
|
<img src="https://i.postimg.cc/bvDr095w/image.png" alt="Eleanor Chess Engine" width="300">
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<h1 align="center">Eleanor Chess Engine</h1>
|
<h1 align="center">Eleanor Chess Engine</h1>
|
||||||
|
|
||||||
## Search Features
|

|
||||||
|
<br>
|
||||||
|
[](https://rektdie.pythonanywhere.com/)
|
||||||
|
[](https://rektgen.online/)<br>
|
||||||
|

|
||||||
|
|
||||||
|
|
||||||
|
| Version | Release Date | [CCRL 40/15](https://www.computerchess.org.uk/ccrl/4040/cgi/compare_engines.cgi?family=Eleanor&print=Rating+list&print=Results+table&print=LOS+table&print=Ponder+hit+table&print=Eval+difference+table&print=Comopp+gamenum+table&print=Overlap+table&print=Score+with+common+opponents) | [CCRL Blitz](https://www.computerchess.org.uk/ccrl/404/cgi/compare_engines.cgi?family=Eleanor&print=Rating+list&print=Results+table&print=LOS+table&print=Ponder+hit+table&print=Eval+difference+table&print=Comopp+gamenum+table&print=Overlap+table&print=Score+with+common+opponents) | [CEGT 40/20](http://www.cegt.net/40_40%20Rating%20List/40_40%20SingleVersion/rangliste.html)
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| 4.1 | 2026-04-22 | 3528 (#60-61) | 3590 (#64) | 3443 (#59)
|
||||||
|
| 3.0 | 2025-12-05 | 3405 (#84) | 3495 (#79-80) | -
|
||||||
|
| 2.0 | 2025-08-23 | 3312 (#115) | 3392 (#105) | -
|
||||||
|
| 1.0 | 2025-06-02 | 2856 (#244) | 2759 (#256) | -
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
- Negamax
|
|
||||||
- Quiescent Search
|
|
||||||
- Transposition Table
|
|
||||||
- Move Ordering (TT, SEE + MVV-LVA, Killers, History)
|
|
||||||
- Iterative Deepening
|
|
||||||
- Aspiration Windows
|
|
||||||
- Principal Variation Search
|
|
||||||
- Reverse Futility Pruning
|
|
||||||
- Improving
|
|
||||||
- Null Move Pruning
|
|
||||||
- Late Move Reductions
|
|
||||||
- Log formula
|
|
||||||
- Cutnode
|
|
||||||
- History
|
|
||||||
- Late Move Pruning
|
|
||||||
- Futility Pruning
|
|
||||||
- QS SEE Pruning
|
|
||||||
- PVS SEE Pruning
|
|
||||||
|
|
||||||
## Evaluation
|
## Evaluation
|
||||||
|
|
||||||
Eleanor uses a **fully neural network-based evaluation function**, entirely trained on self-play data from an initially simple HCE using the [bullet](https://github.com/jw1912/bullet) trainer.
|
Eleanor uses a **fully neural network-based evaluation function**, entirely trained on self-play data from an initially simple HCE using the [bullet](https://github.com/jw1912/bullet) trainer.
|
||||||
|
|
||||||
**Architecture:** `(768 -> 256)x2 -> 1x8`
|
**Architecture:** `(768x8hm -> 1536)x2 -> 1x8`
|
||||||
A basic 256-hidden-layer *perspective net* with 8 output buckets.
|
A 1536-hidden-layer *perspective net* with 8 input buckets, 8 output buckets and horizontal mirroring.
|
||||||
|
|
||||||
## Installation
|
## Installation
|
||||||
|
|
||||||
> **Prerequisites:**
|
> **Prerequisites:**
|
||||||
> - `clang++` compiler
|
> - `clang++` compiler
|
||||||
|
> - On Windows, `clang++` must have access to a MinGW GNU toolchain/runtime because the build targets `x86_64-w64-windows-gnu`
|
||||||
> - Access to `make` command
|
> - Access to `make` command
|
||||||
|
|
||||||
1. Clone the repository
|
1. Clone the repository
|
||||||
@@ -60,9 +57,12 @@ You can interact with the engine via these commands:
|
|||||||
|
|
||||||
- `stop` — Stops the current search
|
- `stop` — Stops the current search
|
||||||
- `bench` — Runs a speed benchmark on a set of positions
|
- `bench` — Runs a speed benchmark on a set of positions
|
||||||
|
- `nnue [full]` — Shows a detailed breakdown of the neural network evaluation for the current position (`full` adds histograms, per-step math and top 8 neurons)
|
||||||
|
|
||||||
The engine can be used in any GUI with **UCI support**.
|
The engine can be used in any GUI with **UCI support**.
|
||||||
|
|
||||||
|
[Testing site](https://rektdie.pythonanywhere.com/)
|
||||||
|
|
||||||
## Sources I Used
|
## Sources I Used
|
||||||
|
|
||||||
- [Stockfish Discord Community](https://discord.com/invite/GWDRS3kU6R) — The best possible source for an engine dev.
|
- [Stockfish Discord Community](https://discord.com/invite/GWDRS3kU6R) — The best possible source for an engine dev.
|
||||||
@@ -73,4 +73,4 @@ The engine can be used in any GUI with **UCI support**.
|
|||||||
|
|
||||||
**The project is a work in progress and actively developed. Contributions are highly appreciated.**
|
**The project is a work in progress and actively developed. Contributions are highly appreciated.**
|
||||||
|
|
||||||
###### Last updated: 2025-06-02
|
###### Last updated: 2026-04-18
|
||||||
@@ -0,0 +1,96 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
from __future__ import annotations
|
||||||
|
|
||||||
|
import re
|
||||||
|
import sys
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
SCRIPT_DIR = Path(__file__).resolve().parent
|
||||||
|
DEFAULT_INPUT = SCRIPT_DIR / "spsa_output.txt"
|
||||||
|
DEFAULT_TARGET = SCRIPT_DIR.parent / "source" / "tunables.h"
|
||||||
|
|
||||||
|
VALUE_RE = re.compile(r"^\s*([A-Za-z0-9_]+)\s*,\s*([^\s,]+)\s*$")
|
||||||
|
LINE_RE = re.compile(
|
||||||
|
r"^(?P<indent>\s*)X_(?P<kind>INT|DOUBLE)\("
|
||||||
|
r"(?P<name>[A-Za-z0-9_]+),\s*"
|
||||||
|
r"(?P<default>[^,]+),\s*"
|
||||||
|
r"(?P<rest>.+)\)\s*(?P<continuation>\\)?$"
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def update_line(line: str, updated_values: dict[str, str]) -> tuple[str, bool]:
|
||||||
|
match = LINE_RE.match(line)
|
||||||
|
if not match:
|
||||||
|
return line, False
|
||||||
|
|
||||||
|
name = match.group("name")
|
||||||
|
if name not in updated_values:
|
||||||
|
return line, False
|
||||||
|
|
||||||
|
continuation = " \\" if match.group("continuation") else ""
|
||||||
|
new_line = (
|
||||||
|
f"{match.group('indent')}X_{match.group('kind')}("
|
||||||
|
f"{name}, {updated_values[name]}, {match.group('rest')}){continuation}\n"
|
||||||
|
)
|
||||||
|
return new_line, True
|
||||||
|
|
||||||
|
|
||||||
|
def load_values(path: Path) -> dict[str, str]:
|
||||||
|
values = {}
|
||||||
|
|
||||||
|
for line in path.read_text().splitlines():
|
||||||
|
match = VALUE_RE.match(line)
|
||||||
|
if not match:
|
||||||
|
continue
|
||||||
|
values[match.group(1)] = match.group(2)
|
||||||
|
|
||||||
|
return values
|
||||||
|
|
||||||
|
|
||||||
|
def apply_updates(text: str, updated_values: dict[str, str]) -> tuple[str, set[str]]:
|
||||||
|
updated_lines: list[str] = []
|
||||||
|
seen: set[str] = set()
|
||||||
|
|
||||||
|
for line in text.splitlines(keepends=True):
|
||||||
|
new_line, changed = update_line(line, updated_values)
|
||||||
|
if changed:
|
||||||
|
match = LINE_RE.match(line)
|
||||||
|
if match:
|
||||||
|
seen.add(match.group("name"))
|
||||||
|
updated_lines.append(new_line)
|
||||||
|
|
||||||
|
return "".join(updated_lines), seen
|
||||||
|
|
||||||
|
|
||||||
|
def main() -> int:
|
||||||
|
input_path = Path(sys.argv[1]) if len(sys.argv) > 1 else DEFAULT_INPUT
|
||||||
|
target = Path(sys.argv[2]) if len(sys.argv) > 2 else DEFAULT_TARGET
|
||||||
|
|
||||||
|
if not input_path.exists():
|
||||||
|
print(f"Input file not found: {input_path}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
updated_values = load_values(input_path)
|
||||||
|
if not updated_values:
|
||||||
|
print(f"No tunable values found in {input_path}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
if not target.exists():
|
||||||
|
print(f"Target file not found: {target}", file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
text = target.read_text()
|
||||||
|
updated_text, seen = apply_updates(text, updated_values)
|
||||||
|
|
||||||
|
missing = sorted(set(updated_values) - seen)
|
||||||
|
if missing:
|
||||||
|
print("Missing tunables:", ", ".join(missing), file=sys.stderr)
|
||||||
|
return 1
|
||||||
|
|
||||||
|
target.write_text(updated_text)
|
||||||
|
print(f"Updated {len(seen)} tunables in {target} from {input_path}")
|
||||||
|
return 0
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
raise SystemExit(main())
|
||||||
+68
-39
@@ -1,45 +1,74 @@
|
|||||||
[Event "?"]
|
[Event "?"]
|
||||||
[Site "?"]
|
[Site "?"]
|
||||||
[Date "2025.04.01"]
|
[Date "2026.03.26"]
|
||||||
[Round "1"]
|
[Round "1"]
|
||||||
[White "Eleanor-base"]
|
[White "Eleanor-dev"]
|
||||||
[Black "Eleanor-dev"]
|
[Black "Eleanor-base"]
|
||||||
[Result "1-0"]
|
[Result "0-1"]
|
||||||
[FEN "2r5/1k6/2p4p/4p3/3b1p1B/5B1P/2R5/7K b - - 0 1"]
|
[FEN "rn1qk1nr/pbp1ppbp/1p1p2p1/3P4/5P2/2N1P3/PPPB2PP/R2QKBNR b KQkq - 0 1"]
|
||||||
[GameDuration "00:00:05"]
|
[GameDuration "00:00:14"]
|
||||||
[GameEndTime "2025-04-01T18:10:20.331 Central Europe Daylight Time"]
|
[GameEndTime "2026-03-26T20:42:15.476 CET"]
|
||||||
[GameStartTime "2025-04-01T18:10:14.365 Central Europe Daylight Time"]
|
[GameStartTime "2026-03-26T20:42:00.864 CET"]
|
||||||
[PlyCount "58"]
|
[PlyCount "115"]
|
||||||
[SetUp "1"]
|
[SetUp "1"]
|
||||||
[Termination "abandoned"]
|
[Termination "abandoned"]
|
||||||
[TimeControl "2.53+0.03"]
|
[TimeControl "5.17+0.05"]
|
||||||
|
|
||||||
1... Kb6 {-0.43 11/0 127 176492} 2. Kg2 {+0.45 10/0 117 182773}
|
1... Nf6 {+0.25 16/24 256 274740} 2. Bb5+ {-0.31 14/28 286 222469}
|
||||||
Kb5 {-0.43 10/0 139 43190} 3. Bf2 {+0.48 10/0 94 154681}
|
c6 {+0.30 14/30 154 175813} 3. dxc6 {-0.31 15/29 214 240246}
|
||||||
Rg8+ {-0.41 10/0 104 181006} 4. Kf1 {+0.43 11/0 137 107880}
|
Nxc6 {+0.29 15/25 271 56301} 4. Nf3 {-0.25 16/25 174 198800}
|
||||||
c5 {-0.42 11/0 114 186919} 5. Ke2 {+0.42 10/0 131 26558}
|
O-O {+0.25 14/29 260 157287} 5. O-O {-0.28 15/26 245 287541}
|
||||||
Rd8 {-0.31 11/0 126 178073} 6. Rd2 {+0.36 8/0 129 64726}
|
a6 {+0.24 17/35 224 246704} 6. Bd3 {-0.22 14/27 136 153559}
|
||||||
c4 {+0.11 11/0 124 101858} 7. Bxd4 {-0.11 11/0 86 135900}
|
b5 {+0.24 17/31 241 178951} 7. Qe1 {-0.24 14/28 245 274939}
|
||||||
Rxd4 {+0.10 11/0 124 121262} 8. Rxd4 {-0.01 13/0 117 207646}
|
Qb6 {+0.25 16/25 230 190364} 8. a3 {-0.25 14/25 207 226160}
|
||||||
exd4 {0.00 14/0 95 197856} 9. h4 {0.00 13/0 105 197264}
|
e5 {+0.26 14/27 221 86623} 9. fxe5 {-0.10 14/27 158 172124}
|
||||||
Kb4 {0.00 14/0 91 195163} 10. Kd2 {0.00 13/0 111 105382}
|
Nxe5 {+0.28 13/27 214 129429} 10. Nxe5 {-0.39 13/24 170 177476}
|
||||||
Kc5 {0.00 13/0 109 62420} 11. h5 {0.00 14/0 78 150612} Kb4 {0.00 16/0 79 181784}
|
dxe5 {+0.26 15/27 100 113069} 11. Kh1 {-0.18 13/23 121 136389}
|
||||||
12. Bd1 {0.00 15/0 86 193192} Kc5 {0.00 16/0 97 111839}
|
e4 {+0.32 13/18 202 26644} 12. Be2 {-0.19 15/28 182 213316}
|
||||||
13. Kc2 {0.00 17/0 90 192373} Kb4 {0.00 17/0 95 120438}
|
Rfc8 {+0.19 13/23 194 212538} 13. a4 {-0.12 13/24 207 126167}
|
||||||
14. Bf3 {0.00 17/0 76 176571} Kc5 {0.00 17/0 101 66844}
|
b4 {+0.22 13/25 187 192683} 14. a5 {-0.18 14/26 101 112261}
|
||||||
15. Ba8 {0.00 18/0 75 165249} Kb4 {0.00 18/0 86 198233}
|
Qd8 {+0.15 14/31 111 123537} 15. Na4 {-0.19 14/34 196 210792}
|
||||||
16. Bf3 {0.00 18/0 77 183908} d3+ {+0.01 16/0 69 164278}
|
Nd5 {+0.23 15/29 157 177113} 16. Qf2 {-0.22 14/25 188 135679}
|
||||||
17. Kd2 {-0.03 16/0 81 145118} Kb3 {0.00 17/0 84 107987}
|
f5 {+0.22 15/28 130 130850} 17. c4 {-0.23 13/25 182 139155}
|
||||||
18. Be4 {0.00 16/0 61 125373} f3 {+0.09 17/0 75 163654}
|
bxc3 {+0.24 15/25 98 105292} 18. bxc3 {-0.24 13/25 175 94316}
|
||||||
19. Bxd3 {-0.01 16/0 86 109653} cxd3 {+0.57 18/0 55 140500}
|
Bc6 {+0.23 14/17 166 18894} 19. Bc4 {-0.20 14/29 97 108937}
|
||||||
20. Kxd3 {-0.97 22/0 73 227257} f2 {+0.98 22/0 71 204108}
|
Bxa4 {+0.20 13/24 81 86007} 20. Rxa4 {-0.21 16/30 85 101741}
|
||||||
21. Ke2 {-0.99 20/0 81 29772} Kc4 {+1.48 22/0 62 180691}
|
h5 {+0.25 13/20 159 95557} 21. Qe2 {-0.25 12/30 165 163762}
|
||||||
22. Kxf2 {-2.11 23/0 59 175088} Kd4 {+2.51 27/0 52 189697}
|
Kh7 {+0.36 12/21 98 103093} 22. Rxf5 {-0.39 12/27 159 75820}
|
||||||
23. Kf3 {-3.34 26/0 62 187791} Ke5 {+2.50 32/0 48 167062}
|
gxf5 {+0.34 12/26 101 110999} 23. Qxh5+ {-0.45 13/38 107 119594}
|
||||||
24. Ke3 {-2.24 28/0 54 178563} Kf5 {+2.15 31/0 72 166014}
|
Kg8 {+0.33 13/23 149 16142} 24. Qxf5 {-0.39 14/26 74 84084}
|
||||||
25. Kf3 {-2.22 32/0 52 188757} Kg5 {0.00 35/0 49 143292}
|
Rc5 {+0.40 13/23 144 140578} 25. Qe6+ {-0.37 12/36 150 138869}
|
||||||
26. Ke4 {-2.09 32/0 62 209505} Kxh5 {0.00 39/0 48 159744}
|
Kf8 {+0.53 14/27 138 120201} 26. Bc1 {-0.45 14/30 144 132855}
|
||||||
27. Kf5 {-2.09 33/0 70 226933} Kh4 {0.00 52/0 46 161548}
|
Rb8 {+0.59 14/33 74 90173} 27. Ra1 {-0.55 14/36 130 123759}
|
||||||
28. Kf4 {0.00 37/0 51 178144} h5 {0.00 64/0 29 95868}
|
Qf6 {+0.63 14/35 82 98374} 28. Qxf6+ {-0.21 14/39 132 146058}
|
||||||
29. Kf3 {0.00 51/0 46 165319} Kh3 {0.00 64/0 15 14259}
|
Bxf6 {+0.61 15/35 100 125452} 29. Ba3 {-0.59 14/29 86 103103}
|
||||||
30. Kf4 {0.00 52/0 64 186059, Black disconnects} 1-0
|
Nb4 {+0.57 16/29 129 51381} 30. Bxb4 {-0.57 15/25 64 80650}
|
||||||
|
Rxb4 {+0.53 14/29 91 125806} 31. cxb4 {-0.49 15/23 129 48919}
|
||||||
|
Rxc4 {+0.47 15/27 122 47840} 32. Rb1 {-0.45 15/30 67 91596}
|
||||||
|
Be7 {+0.46 14/24 92 126553} 33. g4 {-0.44 15/26 124 72397}
|
||||||
|
Rxb4 {+0.49 14/25 73 87941} 34. Rf1+ {-0.49 14/28 121 72810}
|
||||||
|
Ke8 {+0.45 15/36 89 113698} 35. Rf5 {-0.45 13/22 117 70248}
|
||||||
|
Kd7 {+0.45 14/30 115 74784} 36. Re5 {-0.45 13/22 82 101380}
|
||||||
|
Bd6 {+0.50 14/33 87 110879} 37. Rh5 {-0.45 12/34 113 72228}
|
||||||
|
Rb1+ {+0.50 15/32 56 64801} 38. Kg2 {-0.46 14/29 74 94136}
|
||||||
|
Rb2+ {+0.50 14/17 108 4246} 39. Kh1 {-0.48 15/25 108 48523}
|
||||||
|
Re2 {+0.53 14/27 78 96242} 40. Rh7+ {-0.56 13/28 105 70703}
|
||||||
|
Ke6 {+0.59 13/25 67 86840} 41. Rh6+ {-0.61 14/29 87 110057}
|
||||||
|
Kd5 {+0.59 15/27 91 103932} 42. Rh5+ {-0.65 14/28 100 108417}
|
||||||
|
Be5 {+0.70 14/33 94 110182} 43. Rh3 {-0.67 14/30 86 100550}
|
||||||
|
Kc4 {+0.83 13/27 100 123700} 44. Rh5 {-0.75 12/24 96 56083}
|
||||||
|
Bc3 {+0.88 12/26 47 63602} 45. Rh6 {-0.73 12/23 95 70966}
|
||||||
|
Rxe3 {+0.92 12/31 96 115497} 46. h4 {-0.83 10/24 91 46076}
|
||||||
|
Re1+ {+0.98 12/25 94 124212} 47. Kg2 {-0.92 13/29 45 57555}
|
||||||
|
Bd4 {+0.94 14/28 86 116606} 48. Rxa6 {-0.93 13/26 90 42707}
|
||||||
|
e3 {+0.95 13/23 90 44547} 49. Re6 {-0.92 12/40 88 86679}
|
||||||
|
e2 {+0.99 13/23 88 36470} 50. a6 {-0.96 13/40 86 89628}
|
||||||
|
Kd5 {+0.97 12/27 86 80236} 51. a7 {-0.97 12/30 84 17470}
|
||||||
|
Bxa7 {+1.08 13/30 84 33077} 52. Re7 {-1.12 12/28 82 71784}
|
||||||
|
Rg1+ {+1.17 13/28 53 70853} 53. Kf3 {-1.21 13/30 81 51340}
|
||||||
|
e1=Q {+1.21 13/30 83 51082} 54. Rxe1 {-1.51 14/31 59 80154}
|
||||||
|
Rxe1 {+1.25 13/29 41 59171} 55. h5 {-1.31 14/29 40 55864}
|
||||||
|
Bd4 {+1.29 12/29 81 48179} 56. g5 {-1.23 11/26 80 30276}
|
||||||
|
Rf1+ {+1.33 12/20 80 18531} 57. Kg2 {-3.99 12/39 78 76309}
|
||||||
|
Rf5 {+1.56 12/26 79 58979} 58. g6 {-M18 12/38 76 76733}
|
||||||
|
Ke4 {+M19 13/35 46 55731, White disconnects} 0-1
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
lmrBaseQuiet, 1.1029723689888005
|
||||||
|
lmrDivisorQuiet, 2.3063513397139945
|
||||||
|
lmrBaseNoisy, 0.451805556082857
|
||||||
|
lmrDivisorNoisy, 3.1355330830404338
|
||||||
|
lmrCutnode, 2005
|
||||||
|
lmrIsPV, 982
|
||||||
|
lmrTTPV, 936
|
||||||
|
lmrHistoryDivisor, 8377
|
||||||
|
lmrImproving, 1131
|
||||||
|
lmrCorrplexity, 830
|
||||||
|
lmrTTPVFailLow, 913
|
||||||
|
lmrDeeperBase, 46
|
||||||
|
rfpBase, 21
|
||||||
|
rfpMargin, 97
|
||||||
|
fpMargin, 86
|
||||||
|
probcutBetaMargin, 190
|
||||||
|
razoringScalar, 195
|
||||||
|
doubleExtMargin, 32
|
||||||
|
seeQuietThreshold, -81
|
||||||
|
seeNoisyThreshold, -32
|
||||||
|
aspInitialDelta, 26
|
||||||
|
nmpBetaMargin, 25
|
||||||
|
seePawnValue, 98
|
||||||
|
seeKnightValue, 301
|
||||||
|
seeBishopValue, 346
|
||||||
|
seeRookValue, 507
|
||||||
|
seeQueenValue, 924
|
||||||
|
seeQsThreshold, -13
|
||||||
|
seeOrderingThreshold, -102
|
||||||
|
ldseMargin, 26
|
||||||
|
historyBonusMultiplier, 306
|
||||||
|
historyBonusSub, 252
|
||||||
|
historyMalusMultiplier, 301
|
||||||
|
historyMalusSub, 250
|
||||||
|
contHistoryBonusMultiplier, 300
|
||||||
|
contHistoryBonusSub, 252
|
||||||
|
contHistoryMalusMultiplier, 300
|
||||||
|
contHistoryMalusSub, 249
|
||||||
|
captHistoryBonusMultiplier, 302
|
||||||
|
captHistoryBonusSub, 249
|
||||||
|
captHistoryMalusMultiplier, 300
|
||||||
|
captHistoryMalusSub, 249
|
||||||
Vendored
-2985
File diff suppressed because it is too large.
Load diff
Vendored
-1949
File diff suppressed because it is too large.
Load diff
Vendored
-4244
File diff suppressed because it is too large.
Load diff
Vendored
-46
@@ -1,46 +0,0 @@
|
|||||||
// Formatting library for C++
|
|
||||||
//
|
|
||||||
// Copyright (c) 2012 - 2016, Victor Zverovich
|
|
||||||
// All rights reserved.
|
|
||||||
//
|
|
||||||
// For the license information refer to format.h.
|
|
||||||
|
|
||||||
#include "fmt/format-inl.h"
|
|
||||||
|
|
||||||
FMT_BEGIN_NAMESPACE
|
|
||||||
namespace detail {
|
|
||||||
|
|
||||||
template FMT_API auto dragonbox::to_decimal(float x) noexcept
|
|
||||||
-> dragonbox::decimal_fp<float>;
|
|
||||||
template FMT_API auto dragonbox::to_decimal(double x) noexcept
|
|
||||||
-> dragonbox::decimal_fp<double>;
|
|
||||||
|
|
||||||
#if FMT_USE_LOCALE
|
|
||||||
// DEPRECATED! locale_ref in the detail namespace
|
|
||||||
template FMT_API locale_ref::locale_ref(const std::locale& loc);
|
|
||||||
template FMT_API auto locale_ref::get<std::locale>() const -> std::locale;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Explicit instantiations for char.
|
|
||||||
|
|
||||||
template FMT_API auto thousands_sep_impl(locale_ref)
|
|
||||||
-> thousands_sep_result<char>;
|
|
||||||
template FMT_API auto decimal_point_impl(locale_ref) -> char;
|
|
||||||
|
|
||||||
// DEPRECATED!
|
|
||||||
template FMT_API void buffer<char>::append(const char*, const char*);
|
|
||||||
|
|
||||||
// DEPRECATED!
|
|
||||||
template FMT_API void vformat_to(buffer<char>&, string_view,
|
|
||||||
typename vformat_args<>::type, locale_ref);
|
|
||||||
|
|
||||||
// Explicit instantiations for wchar_t.
|
|
||||||
|
|
||||||
template FMT_API auto thousands_sep_impl(locale_ref)
|
|
||||||
-> thousands_sep_result<wchar_t>;
|
|
||||||
template FMT_API auto decimal_point_impl(locale_ref) -> wchar_t;
|
|
||||||
|
|
||||||
template FMT_API void buffer<wchar_t>::append(const wchar_t*, const wchar_t*);
|
|
||||||
|
|
||||||
} // namespace detail
|
|
||||||
FMT_END_NAMESPACE
|
|
||||||
+153
-53
@@ -4,83 +4,183 @@
|
|||||||
|
|
||||||
namespace ACC {
|
namespace ACC {
|
||||||
|
|
||||||
int CalculateIndex(bool perspective, bool side, int pieceType, int square) {
|
int CalculateIndex(bool perspective, bool side, int pieceType, int square, bool mirrored) {
|
||||||
if (perspective == Black)
|
if (perspective == Black)
|
||||||
{
|
{
|
||||||
side = 1 - side; // Flip side
|
side = 1 - side;
|
||||||
square = square ^ 0b111000; // Mirror square
|
square = square ^ 0b111000;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (mirrored)
|
||||||
|
square ^= 7;
|
||||||
|
|
||||||
return side * 64 * 6 + pieceType * 64 + square;
|
return side * 64 * 6 + pieceType * 64 + square;
|
||||||
}
|
}
|
||||||
|
|
||||||
// All friendly, for quiets
|
const int16_t* Row(int bucket, int index) {
|
||||||
void AccumulatorPair::addSub(bool stm, int add, int addPT, int sub, int subPT) {
|
return &NNUE::net.accumulator_weights[bucket][static_cast<size_t>(index) * NNUE::HL_SIZE];
|
||||||
int addW = CalculateIndex(White, stm, addPT, add);
|
}
|
||||||
int addB = CalculateIndex(Black, stm, addPT, add);
|
|
||||||
|
|
||||||
int subW = CalculateIndex(White, stm, subPT, sub);
|
void FinnyTable::Reset() {
|
||||||
int subB = CalculateIndex(Black, stm, subPT, sub);
|
for (auto& perspective : entries) {
|
||||||
|
for (auto& mirror : perspective) {
|
||||||
for (int i = 0; i < NNUE::HL_SIZE; i++) {
|
for (auto& entry : mirror) {
|
||||||
white[i] += NNUE::net.accumulator_weights[addW * NNUE::HL_SIZE + i];
|
entry.acc = NNUE::net.accumulator_biases;
|
||||||
black[i] += NNUE::net.accumulator_weights[addB * NNUE::HL_SIZE + i];
|
for (auto& color : entry.bb)
|
||||||
|
for (auto& bb : color)
|
||||||
white[i] -= NNUE::net.accumulator_weights[subW * NNUE::HL_SIZE + i];
|
bb = 0;
|
||||||
black[i] -= NNUE::net.accumulator_weights[subB * NNUE::HL_SIZE + i];
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Captures
|
#if defined(_MSC_VER) && !defined(__clang__)
|
||||||
void AccumulatorPair::addSubSub(bool stm, int add, int addPT, int sub1, int subPT1, int sub2, int subPT2) {
|
#define ACC_NOINLINE __declspec(noinline)
|
||||||
int addW = CalculateIndex(White, stm, addPT, add);
|
#else
|
||||||
int addB = CalculateIndex(Black, stm, addPT, add);
|
#define ACC_NOINLINE __attribute__((noinline))
|
||||||
|
#endif
|
||||||
|
|
||||||
int subW1 = CalculateIndex(White, stm, subPT1, sub1);
|
#if defined(__AVX512F__) && defined(__AVX512BW__)
|
||||||
int subB1 = CalculateIndex(Black, stm, subPT1, sub1);
|
#include <immintrin.h>
|
||||||
|
using Vec = __m512i;
|
||||||
|
static inline Vec vLoad(const int16_t* p) { return _mm512_loadu_si512(p); }
|
||||||
|
static inline void vStore(int16_t* p, Vec v) { _mm512_storeu_si512(p, v); }
|
||||||
|
static inline Vec vAdd(Vec a, Vec b) { return _mm512_add_epi16(a, b); }
|
||||||
|
static inline Vec vSub(Vec a, Vec b) { return _mm512_sub_epi16(a, b); }
|
||||||
|
#define ACC_SIMD 1
|
||||||
|
#elif defined(__AVX2__)
|
||||||
|
#include <immintrin.h>
|
||||||
|
using Vec = __m256i;
|
||||||
|
static inline Vec vLoad(const int16_t* p) { return _mm256_loadu_si256(reinterpret_cast<const __m256i*>(p)); }
|
||||||
|
static inline void vStore(int16_t* p, Vec v) { _mm256_storeu_si256(reinterpret_cast<__m256i*>(p), v); }
|
||||||
|
static inline Vec vAdd(Vec a, Vec b) { return _mm256_add_epi16(a, b); }
|
||||||
|
static inline Vec vSub(Vec a, Vec b) { return _mm256_sub_epi16(a, b); }
|
||||||
|
#define ACC_SIMD 1
|
||||||
|
#elif defined(__SSE2__) || defined(_M_X64) || defined(_M_AMD64)
|
||||||
|
#include <immintrin.h>
|
||||||
|
using Vec = __m128i;
|
||||||
|
static inline Vec vLoad(const int16_t* p) { return _mm_loadu_si128(reinterpret_cast<const __m128i*>(p)); }
|
||||||
|
static inline void vStore(int16_t* p, Vec v) { _mm_storeu_si128(reinterpret_cast<__m128i*>(p), v); }
|
||||||
|
static inline Vec vAdd(Vec a, Vec b) { return _mm_add_epi16(a, b); }
|
||||||
|
static inline Vec vSub(Vec a, Vec b) { return _mm_sub_epi16(a, b); }
|
||||||
|
#define ACC_SIMD 1
|
||||||
|
#elif defined(__aarch64__)
|
||||||
|
#include <arm_neon.h>
|
||||||
|
using Vec = int16x8_t;
|
||||||
|
static inline Vec vLoad(const int16_t* p) { return vld1q_s16(p); }
|
||||||
|
static inline void vStore(int16_t* p, Vec v) { vst1q_s16(p, v); }
|
||||||
|
static inline Vec vAdd(Vec a, Vec b) { return vaddq_s16(a, b); }
|
||||||
|
static inline Vec vSub(Vec a, Vec b) { return vsubq_s16(a, b); }
|
||||||
|
#define ACC_SIMD 1
|
||||||
|
#endif
|
||||||
|
|
||||||
int subW2 = CalculateIndex(White, !stm, subPT2, sub2);
|
#ifdef ACC_SIMD
|
||||||
int subB2 = CalculateIndex(Black, !stm, subPT2, sub2);
|
|
||||||
|
|
||||||
for (int i = 0; i < NNUE::HL_SIZE; i++) {
|
constexpr size_t LANES = sizeof(Vec) / sizeof(int16_t);
|
||||||
white[i] += NNUE::net.accumulator_weights[addW * NNUE::HL_SIZE + i];
|
constexpr size_t TILE = 4;
|
||||||
black[i] += NNUE::net.accumulator_weights[addB * NNUE::HL_SIZE + i];
|
constexpr size_t STEP = LANES * TILE;
|
||||||
|
static_assert(NNUE::HL_SIZE % STEP == 0, "HL size must be divisible by the SIMD tile size");
|
||||||
|
|
||||||
white[i] -= NNUE::net.accumulator_weights[subW1 * NNUE::HL_SIZE + i];
|
template <int NA, int NS>
|
||||||
black[i] -= NNUE::net.accumulator_weights[subB1 * NNUE::HL_SIZE + i];
|
ACC_NOINLINE static void ApplyKernel(int16_t* dst, const int16_t* src,
|
||||||
|
const int16_t* a1, const int16_t* a2,
|
||||||
|
const int16_t* s1, const int16_t* s2) {
|
||||||
|
for (size_t i = 0; i < NNUE::HL_SIZE; i += STEP) {
|
||||||
|
Vec r[TILE];
|
||||||
|
|
||||||
white[i] -= NNUE::net.accumulator_weights[subW2 * NNUE::HL_SIZE + i];
|
for (size_t u = 0; u < TILE; u++) r[u] = vLoad(src + i + u * LANES);
|
||||||
black[i] -= NNUE::net.accumulator_weights[subB2 * NNUE::HL_SIZE + i];
|
for (size_t u = 0; u < TILE; u++) r[u] = vAdd(r[u], vLoad(a1 + i + u * LANES));
|
||||||
|
if constexpr (NA > 1)
|
||||||
|
for (size_t u = 0; u < TILE; u++) r[u] = vAdd(r[u], vLoad(a2 + i + u * LANES));
|
||||||
|
for (size_t u = 0; u < TILE; u++) r[u] = vSub(r[u], vLoad(s1 + i + u * LANES));
|
||||||
|
if constexpr (NS > 1)
|
||||||
|
for (size_t u = 0; u < TILE; u++) r[u] = vSub(r[u], vLoad(s2 + i + u * LANES));
|
||||||
|
|
||||||
|
for (size_t u = 0; u < TILE; u++) vStore(dst + i + u * LANES, r[u]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Castling
|
ACC_NOINLINE static void InPlaceKernel(int16_t* acc, const int16_t* const* adds, int nAdds,
|
||||||
void AccumulatorPair::addAddSubSub(bool stm, int add1, int addPT1, int add2, int addPT2, int sub1, int subPT1, int sub2, int subPT2) {
|
const int16_t* const* subs, int nSubs) {
|
||||||
int addW1 = CalculateIndex(White, stm, addPT1, add1);
|
for (size_t i = 0; i < NNUE::HL_SIZE; i += STEP) {
|
||||||
int addB1 = CalculateIndex(Black, stm, addPT1, add1);
|
Vec r[TILE];
|
||||||
|
|
||||||
int addW2 = CalculateIndex(White, stm, addPT2, add2);
|
for (size_t u = 0; u < TILE; u++) r[u] = vLoad(acc + i + u * LANES);
|
||||||
int addB2 = CalculateIndex(Black, stm, addPT2, add2);
|
|
||||||
|
|
||||||
int subW1 = CalculateIndex(White, stm, subPT1, sub1);
|
for (int j = 0; j < nAdds; j++)
|
||||||
int subB1 = CalculateIndex(Black, stm, subPT1, sub1);
|
for (size_t u = 0; u < TILE; u++) r[u] = vAdd(r[u], vLoad(adds[j] + i + u * LANES));
|
||||||
|
|
||||||
int subW2 = CalculateIndex(White, stm, subPT2, sub2);
|
for (int j = 0; j < nSubs; j++)
|
||||||
int subB2 = CalculateIndex(Black, stm, subPT2, sub2);
|
for (size_t u = 0; u < TILE; u++) r[u] = vSub(r[u], vLoad(subs[j] + i + u * LANES));
|
||||||
|
|
||||||
for (int i = 0; i < NNUE::HL_SIZE; i++) {
|
for (size_t u = 0; u < TILE; u++) vStore(acc + i + u * LANES, r[u]);
|
||||||
white[i] += NNUE::net.accumulator_weights[addW1 * NNUE::HL_SIZE + i];
|
|
||||||
black[i] += NNUE::net.accumulator_weights[addB1 * NNUE::HL_SIZE + i];
|
|
||||||
|
|
||||||
white[i] += NNUE::net.accumulator_weights[addW2 * NNUE::HL_SIZE + i];
|
|
||||||
black[i] += NNUE::net.accumulator_weights[addB2 * NNUE::HL_SIZE + i];
|
|
||||||
|
|
||||||
white[i] -= NNUE::net.accumulator_weights[subW1 * NNUE::HL_SIZE + i];
|
|
||||||
black[i] -= NNUE::net.accumulator_weights[subB1 * NNUE::HL_SIZE + i];
|
|
||||||
|
|
||||||
white[i] -= NNUE::net.accumulator_weights[subW2 * NNUE::HL_SIZE + i];
|
|
||||||
black[i] -= NNUE::net.accumulator_weights[subB2 * NNUE::HL_SIZE + i];
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void Apply(Accumulator& dst, const Accumulator& src, const int16_t* a1, const int16_t* a2, const int16_t* s1, const int16_t* s2) {
|
||||||
|
if (a2)
|
||||||
|
ApplyKernel<2, 2>(dst.data(), src.data(), a1, a2, s1, s2);
|
||||||
|
else if (s2)
|
||||||
|
ApplyKernel<1, 2>(dst.data(), src.data(), a1, nullptr, s1, s2);
|
||||||
|
else
|
||||||
|
ApplyKernel<1, 1>(dst.data(), src.data(), a1, nullptr, s1, nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ApplyInPlace(Accumulator& acc, const int16_t* const* adds, int nAdds, const int16_t* const* subs, int nSubs) {
|
||||||
|
InPlaceKernel(acc.data(), adds, nAdds, subs, nSubs);
|
||||||
|
}
|
||||||
|
|
||||||
|
void AddRow(Accumulator& acc, const int16_t* row) {
|
||||||
|
const int16_t* rows[1] = {row};
|
||||||
|
InPlaceKernel(acc.data(), rows, 1, nullptr, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#else
|
||||||
|
|
||||||
|
using Ptr = int16_t* __restrict;
|
||||||
|
using CPtr = const int16_t* __restrict;
|
||||||
|
|
||||||
|
ACC_NOINLINE static void Kernel1p1m(Ptr dst, CPtr src, CPtr a, CPtr s) {
|
||||||
|
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
|
||||||
|
dst[i] = static_cast<int16_t>(src[i] + a[i] - s[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
ACC_NOINLINE static void Kernel1p2m(Ptr dst, CPtr src, CPtr a, CPtr s1, CPtr s2) {
|
||||||
|
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
|
||||||
|
dst[i] = static_cast<int16_t>(src[i] + a[i] - s1[i] - s2[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
ACC_NOINLINE static void Kernel2p2m(Ptr dst, CPtr src, CPtr a1, CPtr a2, CPtr s1, CPtr s2) {
|
||||||
|
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
|
||||||
|
dst[i] = static_cast<int16_t>(src[i] + a1[i] + a2[i] - s1[i] - s2[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
void Apply(Accumulator& dst, const Accumulator& src, const int16_t* a1, const int16_t* a2, const int16_t* s1, const int16_t* s2) {
|
||||||
|
if (a2)
|
||||||
|
Kernel2p2m(dst.data(), src.data(), a1, a2, s1, s2);
|
||||||
|
else if (s2)
|
||||||
|
Kernel1p2m(dst.data(), src.data(), a1, s1, s2);
|
||||||
|
else
|
||||||
|
Kernel1p1m(dst.data(), src.data(), a1, s1);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ApplyInPlace(Accumulator& acc, const int16_t* const* adds, int nAdds, const int16_t* const* subs, int nSubs) {
|
||||||
|
int16_t* p = acc.data();
|
||||||
|
|
||||||
|
for (int j = 0; j < nAdds; j++)
|
||||||
|
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
|
||||||
|
p[i] = static_cast<int16_t>(p[i] + adds[j][i]);
|
||||||
|
|
||||||
|
for (int j = 0; j < nSubs; j++)
|
||||||
|
for (size_t i = 0; i < NNUE::HL_SIZE; i++)
|
||||||
|
p[i] = static_cast<int16_t>(p[i] - subs[j][i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
void AddRow(Accumulator& acc, const int16_t* row) {
|
||||||
|
const int16_t* rows[1] = {row};
|
||||||
|
ApplyInPlace(acc, rows, 1, nullptr, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
#endif
|
||||||
|
|
||||||
}
|
}
|
||||||
+85
-7
@@ -1,20 +1,98 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
#include <array>
|
||||||
|
#include <vector>
|
||||||
|
#include <cstdint>
|
||||||
#include "nnue.h"
|
#include "nnue.h"
|
||||||
|
|
||||||
namespace ACC {
|
namespace ACC {
|
||||||
|
|
||||||
|
struct BucketPair {
|
||||||
|
int white;
|
||||||
|
int black;
|
||||||
|
};
|
||||||
|
|
||||||
using Accumulator = std::array<int16_t, NNUE::HL_SIZE>;
|
using Accumulator = std::array<int16_t, NNUE::HL_SIZE>;
|
||||||
|
|
||||||
struct AccumulatorPair {
|
struct AccumulatorPair {
|
||||||
alignas(32) Accumulator white;
|
alignas(ALIGNMENT) Accumulator white;
|
||||||
alignas(32) Accumulator black;
|
alignas(ALIGNMENT) Accumulator black;
|
||||||
|
|
||||||
// yoinked from Quinniboi - Prelude
|
Accumulator& get(bool perspective) { return perspective ? black : white; }
|
||||||
void addSub(bool stm, int add, int addPT, int sub, int subPT);
|
const Accumulator& get(bool perspective) const { return perspective ? black : white; }
|
||||||
void addSubSub(bool stm, int add, int addPT, int sub1, int subPT1, int sub2, int subPT2);
|
|
||||||
void addAddSubSub(bool stm, int add1, int addPT1, int add2, int addPT2, int sub1, int subPT1, int sub2, int subPT2);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
int CalculateIndex(bool perspective, bool side, int pieceType, int square);
|
enum class UpdateType : uint8_t {
|
||||||
|
None,
|
||||||
|
Refresh,
|
||||||
|
Copy,
|
||||||
|
Delta
|
||||||
|
};
|
||||||
|
|
||||||
|
struct Update {
|
||||||
|
UpdateType type = UpdateType::None;
|
||||||
|
uint8_t refreshMask = 0;
|
||||||
|
bool stm = false;
|
||||||
|
bool sub2Opp = false;
|
||||||
|
uint8_t nAdd = 0, nSub = 0;
|
||||||
|
int8_t add1 = 0, addPT1 = 0, add2 = 0, addPT2 = 0;
|
||||||
|
int8_t sub1 = 0, subPT1 = 0, sub2 = 0, subPT2 = 0;
|
||||||
|
|
||||||
|
void setAddSub(bool s, int add, int addPT, int sub, int subPT) {
|
||||||
|
type = UpdateType::Delta;
|
||||||
|
stm = s; sub2Opp = false; nAdd = 1; nSub = 1;
|
||||||
|
add1 = add; addPT1 = addPT; sub1 = sub; subPT1 = subPT;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setAddSubSub(bool s, int add, int addPT, int sub1_, int subPT1_, int sub2_, int subPT2_) {
|
||||||
|
type = UpdateType::Delta;
|
||||||
|
stm = s; sub2Opp = true; nAdd = 1; nSub = 2;
|
||||||
|
add1 = add; addPT1 = addPT;
|
||||||
|
sub1 = sub1_; subPT1 = subPT1_; sub2 = sub2_; subPT2 = subPT2_;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setAddAddSubSub(bool s, int add1_, int addPT1_, int add2_, int addPT2_, int sub1_, int subPT1_, int sub2_, int subPT2_) {
|
||||||
|
type = UpdateType::Delta;
|
||||||
|
stm = s; sub2Opp = false; nAdd = 2; nSub = 2;
|
||||||
|
add1 = add1_; addPT1 = addPT1_; add2 = add2_; addPT2 = addPT2_;
|
||||||
|
sub1 = sub1_; subPT1 = subPT1_; sub2 = sub2_; subPT2 = subPT2_;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setRefresh() {
|
||||||
|
*this = Update();
|
||||||
|
type = UpdateType::Refresh;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
struct FinnyEntry {
|
||||||
|
alignas(ALIGNMENT) Accumulator acc;
|
||||||
|
uint64_t bb[2][6];
|
||||||
|
};
|
||||||
|
|
||||||
|
struct FinnyTable {
|
||||||
|
FinnyEntry entries[2][2][NNUE::INPUT_BUCKETS];
|
||||||
|
|
||||||
|
void Reset();
|
||||||
|
};
|
||||||
|
|
||||||
|
struct AccStack {
|
||||||
|
std::vector<AccumulatorPair> slots;
|
||||||
|
std::vector<const AccumulatorPair*> cur;
|
||||||
|
FinnyTable finny;
|
||||||
|
|
||||||
|
explicit AccStack(size_t n) : slots(n), cur(n, nullptr) { finny.Reset(); }
|
||||||
|
|
||||||
|
AccStack(const AccStack& other) : AccStack(other.slots.size()) {}
|
||||||
|
AccStack& operator=(const AccStack&) { return *this; }
|
||||||
|
};
|
||||||
|
|
||||||
|
int CalculateIndex(bool perspective, bool side, int pieceType, int square, bool mirrored);
|
||||||
|
|
||||||
|
const int16_t* Row(int bucket, int index);
|
||||||
|
|
||||||
|
void Apply(Accumulator& dst, const Accumulator& src, const int16_t* a1, const int16_t* a2, const int16_t* s1, const int16_t* s2);
|
||||||
|
|
||||||
|
void ApplyInPlace(Accumulator& acc, const int16_t* const* adds, int nAdds, const int16_t* const* subs, int nSubs);
|
||||||
|
|
||||||
|
void AddRow(Accumulator& acc, const int16_t* row);
|
||||||
|
|
||||||
}
|
}
|
||||||
+147
-3
@@ -1,13 +1,131 @@
|
|||||||
#include <cstring>
|
#include <cstring>
|
||||||
#include <string_view>
|
#include <string_view>
|
||||||
#include <array>
|
#include <array>
|
||||||
|
#include <iostream>
|
||||||
|
#include <iomanip>
|
||||||
|
#include <sstream>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
#include "benchmark.h"
|
#include "benchmark.h"
|
||||||
#include "search.h"
|
#include "search.h"
|
||||||
#include "stopwatch.h"
|
#include "stopwatch.h"
|
||||||
|
#include "wdl.h"
|
||||||
|
|
||||||
using namespace SEARCH;
|
using namespace SEARCH;
|
||||||
|
|
||||||
|
static std::string BenchScoreString(int score, bool &isMate) {
|
||||||
|
std::stringstream ss;
|
||||||
|
isMate = std::abs(score) + MAX_DEPTH >= MATE_SCORE;
|
||||||
|
if (isMate) {
|
||||||
|
int mateIn = (MATE_SCORE - (std::abs(score) - 1)) / 2;
|
||||||
|
mateIn = score < 0 ? mateIn * -1 : mateIn;
|
||||||
|
if (mateIn < 0) {
|
||||||
|
ss << "-M" << std::abs(mateIn);
|
||||||
|
} else {
|
||||||
|
ss << "+M" << mateIn;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
ss << std::showpos << std::fixed << std::setprecision(2)
|
||||||
|
<< (score / 100.0) << std::noshowpos;
|
||||||
|
}
|
||||||
|
return ss.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::string BenchCountString(U64 count, const char* suffix) {
|
||||||
|
std::stringstream ss;
|
||||||
|
if (count >= 1000000) {
|
||||||
|
ss << std::fixed << std::setprecision(1) << (count / 1000000.0) << "M" << suffix;
|
||||||
|
} else if (count >= 1000) {
|
||||||
|
ss << std::fixed << std::setprecision(1) << (count / 1000.0) << "k" << suffix;
|
||||||
|
} else {
|
||||||
|
ss << count << suffix;
|
||||||
|
}
|
||||||
|
return ss.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void PrintBenchHeader() {
|
||||||
|
std::cout << termcolor::bold << termcolor::color<244>;
|
||||||
|
std::cout << std::setw(4) << std::right << "#";
|
||||||
|
std::cout << std::setw(8) << std::left << " Depth";
|
||||||
|
std::cout << std::setw(9) << std::right << "Score";
|
||||||
|
std::cout << std::setw(10) << std::right << "Nodes";
|
||||||
|
std::cout << std::setw(9) << std::right << "Time";
|
||||||
|
std::cout << std::setw(9) << std::right << "NPS";
|
||||||
|
std::cout << " Best";
|
||||||
|
std::cout << termcolor::reset << std::endl;
|
||||||
|
|
||||||
|
std::cout << termcolor::color<238>;
|
||||||
|
for (int i = 0; i < 64; i++)
|
||||||
|
std::cout << '-';
|
||||||
|
std::cout << termcolor::reset << std::endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void PrintBenchLine(int index, Board& board, SearchResults& results, SearchContext* ctx, U64 posNodes, int elapsedMs) {
|
||||||
|
if (index % 2 == 0) {
|
||||||
|
std::cout << termcolor::color<247>;
|
||||||
|
} else {
|
||||||
|
std::cout << termcolor::color<251>;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::cout << std::setw(4) << std::right << index;
|
||||||
|
|
||||||
|
std::stringstream depthStr;
|
||||||
|
depthStr << BENCH_DEPTH << '/' << ctx->seldepth;
|
||||||
|
std::cout << termcolor::bold << termcolor::bright_white;
|
||||||
|
std::cout << std::setw(8) << std::left << (" " + depthStr.str());
|
||||||
|
std::cout << termcolor::reset;
|
||||||
|
if (index % 2 == 0) {
|
||||||
|
std::cout << termcolor::color<247>;
|
||||||
|
} else {
|
||||||
|
std::cout << termcolor::color<251>;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bool isMateScore = std::abs(results.score) + MAX_DEPTH >= MATE_SCORE;
|
||||||
|
const int normalizedScore = isMateScore ? results.score : scaleEval(results.score, board);
|
||||||
|
bool isMate = false;
|
||||||
|
std::string scoreStr = BenchScoreString(normalizedScore, isMate);
|
||||||
|
if (isMate) {
|
||||||
|
int mateIn = (MATE_SCORE - (std::abs(normalizedScore) - 1)) / 2;
|
||||||
|
mateIn = normalizedScore < 0 ? mateIn * -1 : mateIn;
|
||||||
|
if (mateIn > 0) {
|
||||||
|
std::cout << termcolor::bold << termcolor::bright_green;
|
||||||
|
} else {
|
||||||
|
std::cout << termcolor::bold << termcolor::bright_red;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if (normalizedScore > 0) {
|
||||||
|
std::cout << termcolor::bold << termcolor::green;
|
||||||
|
} else if (normalizedScore < 0) {
|
||||||
|
std::cout << termcolor::bold << termcolor::red;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::cout << std::setw(9) << std::right << scoreStr;
|
||||||
|
std::cout << termcolor::reset;
|
||||||
|
if (index % 2 == 0) {
|
||||||
|
std::cout << termcolor::color<247>;
|
||||||
|
} else {
|
||||||
|
std::cout << termcolor::color<251>;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::cout << std::setw(10) << std::right << BenchCountString(posNodes, "");
|
||||||
|
|
||||||
|
std::stringstream timeStr;
|
||||||
|
if (elapsedMs >= 1000) {
|
||||||
|
timeStr << std::fixed << std::setprecision(1) << (elapsedMs / 1000.0) << "s";
|
||||||
|
} else {
|
||||||
|
timeStr << elapsedMs << "ms";
|
||||||
|
}
|
||||||
|
std::cout << std::setw(9) << std::right << timeStr.str();
|
||||||
|
|
||||||
|
double elapsedSec = elapsedMs / 1000.0;
|
||||||
|
U64 nps = elapsedSec > 0 ? U64(posNodes / elapsedSec) : posNodes;
|
||||||
|
std::cout << std::setw(9) << std::right << BenchCountString(nps, "/s");
|
||||||
|
|
||||||
|
std::cout << " ";
|
||||||
|
std::cout << termcolor::bold << termcolor::bright_cyan;
|
||||||
|
std::cout << results.bestMove.GetMoveString();
|
||||||
|
std::cout << termcolor::reset << std::endl;
|
||||||
|
}
|
||||||
|
|
||||||
constexpr std::array<std::string_view, 50> fenPositions = {
|
constexpr std::array<std::string_view, 50> fenPositions = {
|
||||||
"rnbq1k1r/ppp1bppp/4pn2/8/2B5/2NP1N2/PPP2PPP/R1BQR1K1 b - - 2 8",
|
"rnbq1k1r/ppp1bppp/4pn2/8/2B5/2NP1N2/PPP2PPP/R1BQR1K1 b - - 2 8",
|
||||||
"rnbq1k1r/pp2bppp/4pn2/2p5/2B2B2/2NP1N2/PPP2PPP/R2QR1K1 b - - 1 9",
|
"rnbq1k1r/pp2bppp/4pn2/2p5/2B2B2/2NP1N2/PPP2PPP/R2QR1K1 b - - 1 9",
|
||||||
@@ -64,13 +182,39 @@ constexpr std::array<std::string_view, 50> fenPositions = {
|
|||||||
void RunBenchmark() {
|
void RunBenchmark() {
|
||||||
Board board;
|
Board board;
|
||||||
|
|
||||||
|
TTable BenchTT;
|
||||||
auto ctx = std::make_unique<SearchContext>();
|
auto ctx = std::make_unique<SearchContext>();
|
||||||
|
ctx->TT = &BenchTT;
|
||||||
|
|
||||||
|
PrintBenchHeader();
|
||||||
|
|
||||||
Stopwatch sw;
|
Stopwatch sw;
|
||||||
for (int i = 0; i < fenPositions.size(); i++) {
|
for (size_t i = 0; i < fenPositions.size(); i++) {
|
||||||
board.SetByFen(fenPositions[i]);
|
board.SetByFen(fenPositions[i]);
|
||||||
SearchPosition<bench>(board, SearchParams(), ctx.get());
|
U64 nodesBefore = ctx->nodes;
|
||||||
|
Stopwatch posSw;
|
||||||
|
SearchResults results = SearchPosition<bench>(board, SearchParams(), ctx.get());
|
||||||
|
int elapsedMs = posSw.GetElapsedMS();
|
||||||
|
PrintBenchLine(int(i + 1), board, results, ctx.get(), ctx->nodes - nodesBefore, elapsedMs);
|
||||||
}
|
}
|
||||||
|
double totalSec = sw.GetElapsedSec();
|
||||||
|
|
||||||
std::cout << ctx->nodes << " nodes " << int(ctx->nodes/sw.GetElapsedSec()) << " nps" << std::endl;
|
std::cout << termcolor::color<238>;
|
||||||
|
for (int i = 0; i < 64; i++)
|
||||||
|
std::cout << '-';
|
||||||
|
std::cout << termcolor::reset << std::endl;
|
||||||
|
|
||||||
|
std::cout << termcolor::bold << termcolor::bright_white;
|
||||||
|
std::cout << "Positions: " << fenPositions.size();
|
||||||
|
std::cout << " Nodes: " << BenchCountString(ctx->nodes, "");
|
||||||
|
std::cout << " Time: ";
|
||||||
|
if (totalSec >= 1.0) {
|
||||||
|
std::cout << std::fixed << std::setprecision(1) << totalSec << "s";
|
||||||
|
} else {
|
||||||
|
std::cout << int(totalSec * 1000) << "ms";
|
||||||
|
}
|
||||||
|
std::cout << " Avg: " << BenchCountString(totalSec > 0 ? U64(ctx->nodes / totalSec) : ctx->nodes, "/s");
|
||||||
|
std::cout << termcolor::reset << std::endl;
|
||||||
|
|
||||||
|
std::cout << ctx->nodes << " nodes " << int(ctx->nodes/totalSec) << " nps" << std::endl;
|
||||||
}
|
}
|
||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
constexpr int BENCH_DEPTH = 13;
|
constexpr int BENCH_DEPTH = 11;
|
||||||
|
|
||||||
void RunBenchmark();
|
void RunBenchmark();
|
||||||
+1101
-89
File diff suppressed because it is too large.
Load diff
+32
-4
@@ -16,12 +16,19 @@ public:
|
|||||||
SetByFen(StartingFen);
|
SetByFen(StartingFen);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::array<int, 64> mailbox;
|
||||||
|
|
||||||
std::array<Bitboard, 6> pieces;
|
std::array<Bitboard, 6> pieces;
|
||||||
std::array<Bitboard, 2> colors;
|
std::array<Bitboard, 2> colors;
|
||||||
|
|
||||||
Bitboard occupied;
|
Bitboard occupied;
|
||||||
|
|
||||||
ACC::AccumulatorPair accPair;
|
std::array<Bitboard, 2> pinned;
|
||||||
|
Bitboard checkers;
|
||||||
|
|
||||||
|
ACC::Update accUpdate;
|
||||||
|
bool mirroredWhite = false;
|
||||||
|
bool mirroredBlack = false;
|
||||||
|
|
||||||
std::array<Bitboard, 6> pieceThreats;
|
std::array<Bitboard, 6> pieceThreats;
|
||||||
std::array<Bitboard, 2> colorThreats;
|
std::array<Bitboard, 2> colorThreats;
|
||||||
@@ -40,19 +47,29 @@ public:
|
|||||||
int fullMoves = 1;
|
int fullMoves = 1;
|
||||||
|
|
||||||
U64 hashKey = 0ULL;
|
U64 hashKey = 0ULL;
|
||||||
|
U64 pawnKey = 0ULL;
|
||||||
|
U64 nonPawnKey = 0ULL;
|
||||||
|
U64 majorKey = 0ULL;
|
||||||
|
|
||||||
|
std::array<Bitboard, 4> checkZones;
|
||||||
|
|
||||||
void Reset();
|
void Reset();
|
||||||
void SetByFen(std::string_view fen);
|
void SetByFen(std::string_view fen);
|
||||||
std::string GetFen();
|
std::string GetFen();
|
||||||
void PrintBoard();
|
void PrintBoard();
|
||||||
|
|
||||||
void PrintNNUE();
|
void PrintNNUE(bool full = false);
|
||||||
|
|
||||||
void AddMove(Move move);
|
void AddMove(Move move);
|
||||||
void ResetMoves();
|
void ResetMoves();
|
||||||
void ListMoves();
|
void ListMoves();
|
||||||
|
|
||||||
void ResetAccPair();
|
ACC::BucketPair GetBuckets();
|
||||||
|
void RefreshAccumulator(ACC::AccumulatorPair& out) const;
|
||||||
|
void UpdateAccumulator(ACC::AccStack& stack, int ply);
|
||||||
|
void RefreshPerspective(ACC::FinnyTable& finny, bool perspective, ACC::Accumulator& out) const;
|
||||||
|
void ApplyDeltaPerspective(bool perspective, ACC::Accumulator& dst, const ACC::Accumulator& src) const;
|
||||||
|
void MarkAccumulatorDirty() { accUpdate.setRefresh(); }
|
||||||
|
|
||||||
int GetPieceType(int square);
|
int GetPieceType(int square);
|
||||||
int GetPieceColor(int square);
|
int GetPieceColor(int square);
|
||||||
@@ -63,9 +80,20 @@ public:
|
|||||||
void RemovePiece(int piece, int square, bool color);
|
void RemovePiece(int piece, int square, bool color);
|
||||||
|
|
||||||
void Promote(int square, int pieceType, int color, bool isCapture);
|
void Promote(int square, int pieceType, int color, bool isCapture);
|
||||||
bool MakeMove(Move move);
|
void MakeMove(Move move);
|
||||||
|
|
||||||
bool InPossibleZug();
|
bool InPossibleZug();
|
||||||
|
|
||||||
Bitboard AttacksTo(int square, Bitboard occupancy);
|
Bitboard AttacksTo(int square, Bitboard occupancy);
|
||||||
|
|
||||||
|
bool IsSquareThreatened(bool side, int square);
|
||||||
|
|
||||||
|
Bitboard CalcCheckers();
|
||||||
|
Bitboard CalcPinned(bool color);
|
||||||
|
|
||||||
|
void CalcCheckZones();
|
||||||
|
bool GivesDirectCheck(Move &move);
|
||||||
|
|
||||||
|
bool IsLegal(Move &move);
|
||||||
|
bool IsPseudoLegal(Move &move);
|
||||||
};
|
};
|
||||||
+599
-211
@@ -5,19 +5,64 @@
|
|||||||
#include <tuple>
|
#include <tuple>
|
||||||
#include <atomic>
|
#include <atomic>
|
||||||
#include <mutex>
|
#include <mutex>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <iostream>
|
||||||
|
#include <string>
|
||||||
|
#include <chrono>
|
||||||
|
#include <sstream>
|
||||||
|
#include <csignal>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <cerrno>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
#include "datagen.h"
|
#include "datagen.h"
|
||||||
|
#include "datagenui.h"
|
||||||
#include "movegen.h"
|
#include "movegen.h"
|
||||||
#include "search.h"
|
#include "search.h"
|
||||||
#include "movegen.h"
|
|
||||||
#include "utils.h"
|
#include "utils.h"
|
||||||
|
|
||||||
// OS-dependent threading includes
|
// OS-dependent threading includes
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
#include <windows.h>
|
#include <windows.h>
|
||||||
|
#include <io.h>
|
||||||
|
#include <process.h>
|
||||||
#else
|
#else
|
||||||
#include <pthread.h>
|
#include <pthread.h>
|
||||||
|
#include <unistd.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
static std::filesystem::path MakeTempPath(const std::string& prefix, const std::string& ext) {
|
||||||
|
namespace fs = std::filesystem;
|
||||||
|
fs::path dir = fs::temp_directory_path();
|
||||||
|
|
||||||
|
std::random_device rd;
|
||||||
|
std::mt19937_64 gen(rd());
|
||||||
|
std::uniform_int_distribution<uint64_t> dist;
|
||||||
|
auto name = prefix + std::to_string(dist(gen)) + ext;
|
||||||
|
|
||||||
|
return dir / name;
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::string ShellQuote(const std::string& s) {
|
||||||
|
#ifdef _WIN32
|
||||||
|
std::string out = "\"";
|
||||||
|
for (char c : s) {
|
||||||
|
if (c == '"') out += "\\\"";
|
||||||
|
else out += c;
|
||||||
|
}
|
||||||
|
out += "\"";
|
||||||
|
return out;
|
||||||
|
#else
|
||||||
|
std::string out = "'";
|
||||||
|
for (char c : s) {
|
||||||
|
if (c == '\'') out += "'\\''";
|
||||||
|
else out += c;
|
||||||
|
}
|
||||||
|
out += "'";
|
||||||
|
return out;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
static void HideCursor() {
|
static void HideCursor() {
|
||||||
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
|
HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||||
@@ -35,18 +80,158 @@ static void ShowCursor() {
|
|||||||
SetConsoleCursorInfo(hConsole, &cursorInfo);
|
SetConsoleCursorInfo(hConsole, &cursorInfo);
|
||||||
}
|
}
|
||||||
#else
|
#else
|
||||||
static void HideCursor() {
|
static void HideCursor() { std::cout << "\033[?25l"; }
|
||||||
std::cout << "\033[?25l";
|
static void ShowCursor() { std::cout << "\033[?25h"; }
|
||||||
}
|
|
||||||
|
|
||||||
static void ShowCursor() {
|
|
||||||
std::cout << "\033[?25h";
|
|
||||||
}
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
namespace DATAGEN {
|
namespace DATAGEN {
|
||||||
|
|
||||||
static std::mutex fileOpenMutex;
|
|
||||||
|
static bool PostJSON(const std::string& url, const std::string& jsonBody, std::string& response) {
|
||||||
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
|
fs::path tempFile = MakeTempPath("datagen_request_", ".json");
|
||||||
|
fs::path responseFile = MakeTempPath("datagen_response_", ".txt");
|
||||||
|
|
||||||
|
std::ofstream out(tempFile);
|
||||||
|
if (!out) {
|
||||||
|
std::cerr << "Failed to create temp file for request: " << tempFile.string() << "\n";
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
out << jsonBody;
|
||||||
|
out.close();
|
||||||
|
|
||||||
|
std::ostringstream cmd;
|
||||||
|
cmd << "curl -s -X POST "
|
||||||
|
<< ShellQuote(url) << " "
|
||||||
|
<< "-H " << ShellQuote("Content-Type: application/json") << " "
|
||||||
|
<< "-d " << ShellQuote("@" + tempFile.string()) << " "
|
||||||
|
<< "-o " << ShellQuote(responseFile.string()) << " ";
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
cmd << "2>nul";
|
||||||
|
#else
|
||||||
|
cmd << "2>/dev/null";
|
||||||
|
#endif
|
||||||
|
|
||||||
|
int result = system(cmd.str().c_str());
|
||||||
|
|
||||||
|
std::ifstream responseIn(responseFile);
|
||||||
|
if (responseIn) {
|
||||||
|
std::stringstream buffer;
|
||||||
|
buffer << responseIn.rdbuf();
|
||||||
|
response = buffer.str();
|
||||||
|
} else {
|
||||||
|
response.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::error_code ec;
|
||||||
|
fs::remove(tempFile, ec);
|
||||||
|
fs::remove(responseFile, ec);
|
||||||
|
|
||||||
|
return (result == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool UploadFile(const std::string& url,
|
||||||
|
const std::string& filepath,
|
||||||
|
const std::string& username,
|
||||||
|
int positions) {
|
||||||
|
std::ostringstream cmd;
|
||||||
|
|
||||||
|
cmd << "curl -s -X POST "
|
||||||
|
<< ShellQuote(url) << " "
|
||||||
|
<< "-F " << ShellQuote("file=@" + filepath) << " "
|
||||||
|
<< "-F " << ShellQuote("user=" + username) << " "
|
||||||
|
<< "-F " << ShellQuote("positions=" + std::to_string(positions)) << " ";
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
cmd << "2>nul";
|
||||||
|
#else
|
||||||
|
cmd << "2>/dev/null";
|
||||||
|
#endif
|
||||||
|
|
||||||
|
int result = system(cmd.str().c_str());
|
||||||
|
return (result == 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::string BuildStartJSON(const std::string& username, int targetPositions) {
|
||||||
|
std::ostringstream json;
|
||||||
|
json << "{"
|
||||||
|
<< "\"user\":\"" << username << "\","
|
||||||
|
<< "\"target\":" << targetPositions
|
||||||
|
<< "}";
|
||||||
|
return json.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::string BuildHeartbeatJSON(const std::string& username, int threads) {
|
||||||
|
std::ostringstream json;
|
||||||
|
json << "{"
|
||||||
|
<< "\"user\":\"" << username << "\","
|
||||||
|
<< "\"threads\":" << threads
|
||||||
|
<< "}";
|
||||||
|
return json.str();
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::string ExtractJSONValue(const std::string& json, const std::string& key) {
|
||||||
|
std::string searchKey = "\"" + key + "\":";
|
||||||
|
size_t pos = json.find(searchKey);
|
||||||
|
if (pos == std::string::npos) return "";
|
||||||
|
|
||||||
|
pos += searchKey.length();
|
||||||
|
|
||||||
|
while (pos < json.length() && (json[pos] == ' ' || json[pos] == '\t' || json[pos] == '\n')) {
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
if (pos >= json.length()) return "";
|
||||||
|
|
||||||
|
if (json[pos] == '"') {
|
||||||
|
pos++;
|
||||||
|
size_t endPos = json.find("\"", pos);
|
||||||
|
if (endPos == std::string::npos) return "";
|
||||||
|
return json.substr(pos, endPos - pos);
|
||||||
|
} else {
|
||||||
|
size_t endPos = pos;
|
||||||
|
while (endPos < json.length() && json[endPos] != ',' && json[endPos] != '}' && json[endPos] != ']') {
|
||||||
|
endPos++;
|
||||||
|
}
|
||||||
|
return json.substr(pos, endPos - pos);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
static void HeartbeatThread(const std::string& username, int threads,
|
||||||
|
std::atomic<bool>& stopFlag, const std::string& serverUrl) {
|
||||||
|
while (!stopFlag) {
|
||||||
|
for (int i = 0; i < 15 && !stopFlag; ++i) {
|
||||||
|
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stopFlag) break;
|
||||||
|
|
||||||
|
std::string response;
|
||||||
|
std::string heartbeatJSON = BuildHeartbeatJSON(username, threads);
|
||||||
|
PostJSON(serverUrl + "/api/session/heartbeat", heartbeatJSON, response);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Signal handling globals
|
||||||
|
static std::atomic<bool> g_shutdownRequested(false);
|
||||||
|
|
||||||
|
static void SignalHandler(int signal) {
|
||||||
|
if (signal == SIGINT || signal == SIGTERM) {
|
||||||
|
std::cout << "\n\nShutdown signal received. Saving data safely...\n" << std::flush;
|
||||||
|
g_shutdownRequested.store(true);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void SetupSignalHandlers() {
|
||||||
|
std::signal(SIGINT, SignalHandler);
|
||||||
|
std::signal(SIGTERM, SignalHandler);
|
||||||
|
|
||||||
|
#ifndef _WIN32
|
||||||
|
std::signal(SIGHUP, SignalHandler);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
static bool IsGameOver(Board &board, SEARCH::SearchContext* ctx) {
|
static bool IsGameOver(Board &board, SEARCH::SearchContext* ctx) {
|
||||||
if (SEARCH::IsDraw(board, ctx)) return true;
|
if (SEARCH::IsDraw(board, ctx)) return true;
|
||||||
@@ -54,10 +239,9 @@ static bool IsGameOver(Board &board, SEARCH::SearchContext* ctx) {
|
|||||||
int moveSeen = 0;
|
int moveSeen = 0;
|
||||||
|
|
||||||
for (int i = 0; i < board.currentMoveIndex; i++) {
|
for (int i = 0; i < board.currentMoveIndex; i++) {
|
||||||
|
if (!board.IsLegal(board.moveList[i])) continue;
|
||||||
Board copy = board;
|
Board copy = board;
|
||||||
bool isLegal = copy.MakeMove(board.moveList[i]);
|
copy.MakeMove(board.moveList[i]);
|
||||||
|
|
||||||
if (!isLegal) continue;
|
|
||||||
moveSeen++;
|
moveSeen++;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,22 +256,33 @@ static void PlayRandMoves(Board &board, SEARCH::SearchContext* ctx) {
|
|||||||
bool plusOne = moveDist(rng);
|
bool plusOne = moveDist(rng);
|
||||||
|
|
||||||
for (int count = 0; count < RAND_MOVES + plusOne; count++) {
|
for (int count = 0; count < RAND_MOVES + plusOne; count++) {
|
||||||
MOVEGEN::GenerateMoves<All>(board);
|
MOVEGEN::GenerateMoves<All>(board, true);
|
||||||
|
|
||||||
|
if (board.currentMoveIndex <= 0) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
std::uniform_int_distribution<int> dist(0, board.currentMoveIndex - 1);
|
std::uniform_int_distribution<int> dist(0, board.currentMoveIndex - 1);
|
||||||
bool isLegal = board.MakeMove(board.moveList[dist(rng)]);
|
|
||||||
|
|
||||||
if (!isLegal) {
|
Move currMove = board.moveList[dist(rng)];
|
||||||
|
if (!board.IsLegal(currMove)) {
|
||||||
count--;
|
count--;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
board.MakeMove(currMove);
|
||||||
|
|
||||||
ctx->positionHistory[board.positionIndex] = board.hashKey;
|
ctx->positionHistory[board.positionIndex] = board.hashKey;
|
||||||
MOVEGEN::GenerateMoves<All>(board);
|
|
||||||
|
MOVEGEN::GenerateMoves<All>(board, true);
|
||||||
if (IsGameOver(board, ctx)) break;
|
if (IsGameOver(board, ctx)) break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static void WriteToFile(std::vector<Game> &gamesBuffer, std::ofstream &file) {
|
static void WriteToFile(std::vector<Game> &gamesBuffer, const std::string& basePath, int& fileCounter,
|
||||||
|
std::atomic<int>& files) {
|
||||||
|
if (gamesBuffer.empty()) return;
|
||||||
|
|
||||||
int32_t zeroes = 0;
|
int32_t zeroes = 0;
|
||||||
std::vector<char> buffer;
|
std::vector<char> buffer;
|
||||||
|
|
||||||
@@ -110,142 +305,289 @@ static void WriteToFile(std::vector<Game> &gamesBuffer, std::ofstream &file) {
|
|||||||
buffer.insert(buffer.end(), zeroesPtr, zeroesPtr + sizeof(zeroes));
|
buffer.insert(buffer.end(), zeroesPtr, zeroesPtr + sizeof(zeroes));
|
||||||
}
|
}
|
||||||
|
|
||||||
file.write(buffer.data(), buffer.size());
|
std::string tmpFileName = basePath + std::to_string(fileCounter) + ".tmp";
|
||||||
file.flush();
|
std::string finalFileName = basePath + std::to_string(fileCounter) + ".binpack";
|
||||||
|
|
||||||
|
std::ofstream tmpFile(tmpFileName, std::ios::binary);
|
||||||
|
if (!tmpFile.is_open()) {
|
||||||
|
std::cerr << "Failed to create temporary file: " << tmpFileName << std::endl;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
tmpFile.write(buffer.data(), buffer.size());
|
||||||
|
tmpFile.flush();
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
tmpFile.close();
|
||||||
|
#else
|
||||||
|
tmpFile.close();
|
||||||
|
sync();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
std::error_code ec;
|
||||||
|
std::filesystem::rename(tmpFileName, finalFileName, ec);
|
||||||
|
if (ec) {
|
||||||
|
std::cerr << "Failed to rename " << tmpFileName << " to " << finalFileName
|
||||||
|
<< ": " << ec.message() << std::endl;
|
||||||
|
std::filesystem::remove(tmpFileName, ec);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
files.fetch_add(1, std::memory_order_relaxed);
|
||||||
|
fileCounter++;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void PlayGames(int id, std::atomic<int>& positions, std::atomic<bool>& stopFlag) {
|
static std::string MergeThreadFiles() {
|
||||||
|
namespace fs = std::filesystem;
|
||||||
|
|
||||||
|
fs::create_directories("data");
|
||||||
|
|
||||||
|
auto now = std::chrono::system_clock::now();
|
||||||
|
std::time_t now_time = std::chrono::system_clock::to_time_t(now);
|
||||||
|
std::tm tm = *std::localtime(&now_time);
|
||||||
|
|
||||||
|
std::ostringstream oss;
|
||||||
|
oss << "data/datagen_"
|
||||||
|
<< std::put_time(&tm, "%Y-%m-%d_%H-%M")
|
||||||
|
<< ".binpack";
|
||||||
|
std::string finalFileName = oss.str();
|
||||||
|
|
||||||
|
std::ofstream finalFile(finalFileName, std::ios::binary);
|
||||||
|
if (!finalFile.is_open()) {
|
||||||
|
std::cerr << "Failed to create final merged file: " << finalFileName << std::endl;
|
||||||
|
return "";
|
||||||
|
}
|
||||||
|
|
||||||
|
fs::path dataDir("data");
|
||||||
|
for (const auto& entry : fs::directory_iterator(dataDir)) {
|
||||||
|
if (!entry.is_regular_file()) continue;
|
||||||
|
std::string filename = entry.path().filename().string();
|
||||||
|
|
||||||
|
if (filename.find("thread") == 0 && filename.find(".binpack") != std::string::npos) {
|
||||||
|
std::ifstream threadFile(entry.path(), std::ios::binary);
|
||||||
|
if (!threadFile.is_open()) {
|
||||||
|
std::cerr << "Failed to open " << filename << std::endl;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
finalFile << threadFile.rdbuf();
|
||||||
|
threadFile.close();
|
||||||
|
|
||||||
|
std::error_code ec;
|
||||||
|
fs::remove(entry.path(), ec);
|
||||||
|
if (ec) {
|
||||||
|
std::cerr << "Failed to delete " << filename << ": " << ec.message() << std::endl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const auto& entry : fs::directory_iterator(dataDir)) {
|
||||||
|
if (!entry.is_regular_file()) continue;
|
||||||
|
std::string filename = entry.path().filename().string();
|
||||||
|
|
||||||
|
if (filename.find("thread") == 0 && filename.find(".tmp") != std::string::npos) {
|
||||||
|
std::error_code ec;
|
||||||
|
fs::remove(entry.path(), ec);
|
||||||
|
if (ec) {
|
||||||
|
std::cerr << "Failed to delete incomplete temp file " << filename << ": " << ec.message() << std::endl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
finalFile.close();
|
||||||
|
std::cout << "Merged all thread files into: " << finalFileName << std::endl;
|
||||||
|
return finalFileName;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void PlayGames(int id, DatagenStats& stats, std::atomic<bool>& stopFlag) {
|
||||||
std::vector<Game> gamesBuffer;
|
std::vector<Game> gamesBuffer;
|
||||||
gamesBuffer.reserve(GAME_BUFFER);
|
gamesBuffer.reserve(GAME_BUFFER);
|
||||||
|
|
||||||
std::string fileName = "thread" + std::to_string(id) + ".binpack";
|
std::filesystem::create_directories("data");
|
||||||
|
|
||||||
std::ofstream file;
|
std::string basePath = "data/thread" + std::to_string(id) + "_";
|
||||||
{
|
int fileCounter = 0;
|
||||||
std::lock_guard<std::mutex> lock(fileOpenMutex);
|
|
||||||
file.open(fileName, std::ios::app | std::ios::binary);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!file.is_open()) {
|
|
||||||
std::cerr << "Failed to open file: " << fileName << std::endl;
|
|
||||||
exit(-1);
|
|
||||||
}
|
|
||||||
|
|
||||||
const int evenityMargin = 200;
|
const int evenityMargin = 200;
|
||||||
|
|
||||||
/*
|
try {
|
||||||
const int winAdjMoveCount = 3;
|
while (!stopFlag && !g_shutdownRequested) {
|
||||||
const int winAdjScore = 400;
|
Board board;
|
||||||
|
TTable DatagenTT;
|
||||||
|
auto ctx = std::make_unique<SEARCH::SearchContext>();
|
||||||
|
ctx->TT = &DatagenTT;
|
||||||
|
|
||||||
const int drawAdjMoveNumber = 40;
|
PlayRandMoves(board, ctx.get());
|
||||||
const int drawAdjMoveCount = 8;
|
if (IsGameOver(board, ctx.get())) continue;
|
||||||
const int drawAdjScore = 10;
|
|
||||||
*/
|
|
||||||
|
|
||||||
while (!stopFlag) {
|
ctx->nodes = 0;
|
||||||
Board board;
|
const int startingScore = SEARCH::SearchPosition<SEARCH::datagen>(board, SearchParams(), ctx.get()).score;
|
||||||
auto ctx = std::make_unique<SEARCH::SearchContext>();
|
|
||||||
|
|
||||||
PlayRandMoves(board, ctx.get());
|
stats.nodes.fetch_add(ctx->nodes, std::memory_order_relaxed);
|
||||||
if (IsGameOver(board, ctx.get())) continue;
|
|
||||||
|
|
||||||
// Filter out games with a highly uneven starting position
|
if (std::abs(startingScore) >= evenityMargin) {
|
||||||
const int startingScore = SEARCH::SearchPosition<SEARCH::datagen>(board, SearchParams(), ctx.get()).score;
|
stats.rejected.fetch_add(1, std::memory_order_relaxed);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
if (std::abs(startingScore) >= evenityMargin) continue;
|
ctx->nodes = 0;
|
||||||
|
|
||||||
ctx->nodes = 0;
|
Game game;
|
||||||
|
Board startpos = board;
|
||||||
|
|
||||||
Game game;
|
SearchResults safeResults;
|
||||||
Board startpos = board;
|
|
||||||
|
|
||||||
SearchResults safeResults;
|
int staticEval = UTILS::ConvertToWhiteRelative(board, NNUE::net.Evaluate(board, true));
|
||||||
|
int wdl = 1;
|
||||||
|
|
||||||
int staticEval = UTILS::ConvertToWhiteRelative(board, NNUE::net.Evaluate(board));
|
while (!IsGameOver(board, ctx.get())) {
|
||||||
int wdl = 1;
|
if (g_shutdownRequested) break;
|
||||||
|
|
||||||
while (!IsGameOver(board, ctx.get())) {
|
ctx->nodes = 0;
|
||||||
SearchResults results = SEARCH::SearchPosition<SEARCH::datagen>(board, SearchParams(), ctx.get());
|
SearchResults results = SEARCH::SearchPosition<SEARCH::datagen>(board, SearchParams(), ctx.get());
|
||||||
|
stats.nodes.fetch_add(ctx->nodes, std::memory_order_relaxed);
|
||||||
|
|
||||||
if (!results.bestMove) break;
|
if (!results.bestMove) break;
|
||||||
safeResults = results;
|
safeResults = results;
|
||||||
|
|
||||||
game.moves.emplace_back(ScoredMove(results.bestMove.ConvertToViriMoveFormat(),
|
game.moves.emplace_back(ScoredMove(results.bestMove.ConvertToViriMoveFormat(),
|
||||||
UTILS::ConvertToWhiteRelative(board, results.score)));
|
UTILS::ConvertToWhiteRelative(board, results.score)));
|
||||||
|
|
||||||
board.MakeMove(results.bestMove);
|
board.MakeMove(results.bestMove);
|
||||||
ctx->positionHistory[board.positionIndex] = board.hashKey;
|
ctx->positionHistory[board.positionIndex] = board.hashKey;
|
||||||
|
|
||||||
positions++;
|
stats.positions.fetch_add(1, std::memory_order_relaxed);
|
||||||
|
|
||||||
|
MOVEGEN::GenerateMoves<All>(board, true);
|
||||||
|
}
|
||||||
|
|
||||||
MOVEGEN::GenerateMoves<All>(board);
|
if (!SEARCH::IsDraw(board, ctx.get())) {
|
||||||
|
wdl = board.sideToMove ? 2 : 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
game.format.packFrom(startpos, staticEval, wdl);
|
||||||
|
gamesBuffer.emplace_back(game);
|
||||||
|
stats.games.fetch_add(1, std::memory_order_relaxed);
|
||||||
|
|
||||||
|
if (gamesBuffer.size() >= GAME_BUFFER) {
|
||||||
|
WriteToFile(gamesBuffer, basePath, fileCounter, stats.files);
|
||||||
|
gamesBuffer.clear();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
} catch (...) {
|
||||||
if (!SEARCH::IsDraw(board, ctx.get())) {
|
if (!gamesBuffer.empty()) {
|
||||||
wdl = board.sideToMove ? 2 : 0;
|
WriteToFile(gamesBuffer, basePath, fileCounter, stats.files);
|
||||||
}
|
|
||||||
|
|
||||||
game.format.packFrom(startpos, staticEval, wdl);
|
|
||||||
gamesBuffer.emplace_back(game);
|
|
||||||
|
|
||||||
if (gamesBuffer.size() >= GAME_BUFFER) {
|
|
||||||
WriteToFile(gamesBuffer, file);
|
|
||||||
gamesBuffer.clear();
|
|
||||||
}
|
}
|
||||||
|
throw;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Write remaining games to file
|
if (!gamesBuffer.empty()) {
|
||||||
if (gamesBuffer.size() > 0) {
|
WriteToFile(gamesBuffer, basePath, fileCounter, stats.files);
|
||||||
WriteToFile(gamesBuffer, file);
|
|
||||||
gamesBuffer.clear();
|
gamesBuffer.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!stopFlag.load() && !g_shutdownRequested.load()) {
|
||||||
|
std::abort();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#ifdef _WIN32
|
#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) {
|
struct WinThreadArgs {
|
||||||
threads.emplace_back(PlayGames, id, std::ref(positions), std::ref(stopFlag));
|
int id;
|
||||||
|
DatagenStats* stats;
|
||||||
|
std::atomic<bool>* stopFlag;
|
||||||
|
};
|
||||||
|
|
||||||
|
static unsigned __stdcall WinThreadEntry(void* p) {
|
||||||
|
std::unique_ptr<WinThreadArgs> args(static_cast<WinThreadArgs*>(p));
|
||||||
|
PlayGames(args->id, *args->stats, *args->stopFlag);
|
||||||
|
_endthreadex(0);
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
static bool CreateWorkerThread(int id,
|
||||||
|
DatagenStats& stats,
|
||||||
|
std::atomic<bool>& stopFlag,
|
||||||
|
std::vector<HANDLE>& threads,
|
||||||
|
size_t stackSizeBytes) {
|
||||||
|
auto* args = new WinThreadArgs{ id, &stats, &stopFlag };
|
||||||
|
|
||||||
|
unsigned tid = 0;
|
||||||
|
HANDLE h = reinterpret_cast<HANDLE>(
|
||||||
|
_beginthreadex(
|
||||||
|
nullptr,
|
||||||
|
static_cast<unsigned>(stackSizeBytes),
|
||||||
|
&WinThreadEntry,
|
||||||
|
args,
|
||||||
|
0,
|
||||||
|
&tid
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!h) {
|
||||||
|
std::cerr << "Failed to create thread " << id << " (errno=" << errno << ")\n";
|
||||||
|
delete args;
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
threads.push_back(h);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void JoinWorkerThreads(std::vector<HANDLE>& threads) {
|
||||||
|
for (HANDLE h : threads) {
|
||||||
|
if (h) {
|
||||||
|
WaitForSingleObject(h, INFINITE);
|
||||||
|
CloseHandle(h);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
threads.clear();
|
||||||
|
}
|
||||||
|
|
||||||
#else
|
#else
|
||||||
// Unix/Linux implementation using pthread
|
|
||||||
static void* ThreadFunc(void* arg) {
|
static void* ThreadFunc(void* arg) {
|
||||||
auto* tup = static_cast<std::tuple<int, std::atomic<int>*, std::atomic<bool>*>*>(arg);
|
auto* tup = static_cast<std::tuple<int, DatagenStats*, std::atomic<bool>*>*>(arg);
|
||||||
PlayGames(std::get<0>(*tup), *std::get<1>(*tup), *std::get<2>(*tup));
|
PlayGames(std::get<0>(*tup), *std::get<1>(*tup), *std::get<2>(*tup));
|
||||||
delete tup;
|
delete tup;
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
void Run(int targetPositions, int threads) {
|
void Run(int targetPositions, int threads) {
|
||||||
#ifdef _WIN32
|
SetupSignalHandlers();
|
||||||
system("cls");
|
|
||||||
HideCursor();
|
|
||||||
#else
|
|
||||||
std::cout << "\033[2J\033[H";
|
|
||||||
HideCursor();
|
|
||||||
#endif
|
|
||||||
|
|
||||||
std::atomic<int> positions = 0;
|
#ifdef _WIN32
|
||||||
|
system("cls");
|
||||||
|
HideCursor();
|
||||||
|
#else
|
||||||
|
std::cout << "\033[2J\033[H";
|
||||||
|
HideCursor();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
DatagenStats stats;
|
||||||
std::atomic<bool> stopFlag = false;
|
std::atomic<bool> stopFlag = false;
|
||||||
|
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
// Windows implementation using std::thread
|
std::vector<HANDLE> workerThreads;
|
||||||
std::vector<std::thread> workerThreads;
|
workerThreads.reserve((threads > 1) ? (threads - 1) : 0);
|
||||||
|
|
||||||
|
const size_t stackSizeBytes = 8ull * 1024ull * 1024ull;
|
||||||
|
|
||||||
for (int i = 0; i < threads - 1; ++i) {
|
for (int i = 0; i < threads - 1; ++i) {
|
||||||
CreateWorkerThread(i, positions, stopFlag, workerThreads);
|
CreateWorkerThread(i, stats, stopFlag, workerThreads, stackSizeBytes);
|
||||||
}
|
}
|
||||||
#else
|
#else
|
||||||
// Unix/Linux implementation using pthread
|
|
||||||
std::vector<pthread_t> workerThreads;
|
std::vector<pthread_t> workerThreads;
|
||||||
|
|
||||||
for (int i = 0; i < threads - 1; ++i) {
|
for (int i = 0; i < threads - 1; ++i) {
|
||||||
pthread_attr_t attr;
|
pthread_attr_t attr;
|
||||||
pthread_attr_init(&attr);
|
pthread_attr_init(&attr);
|
||||||
pthread_attr_setstacksize(&attr, 8 * 1024 * 1024); // 8 MB stack
|
pthread_attr_setstacksize(&attr, 8 * 1024 * 1024);
|
||||||
|
|
||||||
auto* args = new std::tuple<int, std::atomic<int>*, std::atomic<bool>*>(i, &positions, &stopFlag);
|
auto* args = new std::tuple<int, DatagenStats*, std::atomic<bool>*>(i, &stats, &stopFlag);
|
||||||
|
|
||||||
pthread_t thread;
|
pthread_t thread;
|
||||||
if (pthread_create(&thread, &attr, ThreadFunc, args) == 0) {
|
if (pthread_create(&thread, &attr, ThreadFunc, args) == 0) {
|
||||||
@@ -260,143 +602,189 @@ void Run(int targetPositions, int threads) {
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
Stopwatch sw;
|
Stopwatch sw;
|
||||||
while (positions < targetPositions) {
|
while (stats.positions.load(std::memory_order_relaxed) < targetPositions && !g_shutdownRequested) {
|
||||||
PrintProgress(positions, targetPositions, sw, threads);
|
PrintProgress(stats, targetPositions, sw, threads);
|
||||||
std::this_thread::sleep_for(std::chrono::seconds(1));
|
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||||
}
|
}
|
||||||
|
|
||||||
PrintProgress(positions, targetPositions, sw, threads);
|
PrintProgress(stats, targetPositions, sw, threads);
|
||||||
|
PrintSummary(stats, targetPositions, sw, threads);
|
||||||
|
|
||||||
stopFlag = true;
|
stopFlag = true;
|
||||||
|
|
||||||
|
std::cout << "\n\nWaiting for threads to finish writing..." << std::endl;
|
||||||
|
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
// Join Windows threads
|
JoinWorkerThreads(workerThreads);
|
||||||
for (std::thread& thread : workerThreads) {
|
|
||||||
if (thread.joinable()) {
|
|
||||||
thread.join();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#else
|
#else
|
||||||
// Join pthread threads
|
|
||||||
for (pthread_t& thread : workerThreads) {
|
for (pthread_t& thread : workerThreads) {
|
||||||
pthread_join(thread, nullptr);
|
pthread_join(thread, nullptr);
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
#ifdef _WIN32
|
std::cout << "All threads completed. Merging files..." << std::endl;
|
||||||
ShowCursor();
|
MergeThreadFiles();
|
||||||
#else
|
|
||||||
ShowCursor();
|
#ifdef _WIN32
|
||||||
#endif
|
ShowCursor();
|
||||||
|
#else
|
||||||
|
ShowCursor();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
std::cout << "\nShutdown complete. All data saved safely." << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int threads) {
|
void RunOnline(const std::string& username, int targetPositions, int threads) {
|
||||||
// Define ANSI escape codes for colors as std::string
|
const std::string SERVER_URL = "http://13.60.26.163:3000";
|
||||||
const std::string COLOR_RESET = "\033[0m";
|
|
||||||
const std::string COLOR_TITLE = "\033[1;36m"; // Bright cyan
|
|
||||||
const std::string COLOR_SECTION = "\033[1;33m"; // Bright yellow
|
|
||||||
const std::string COLOR_VALUE = "\033[1;32m"; // Bright green
|
|
||||||
const std::string COLOR_BAR = "\033[1;34m"; // Bright blue
|
|
||||||
|
|
||||||
static double lastPositions = 0;
|
SetupSignalHandlers();
|
||||||
static double lastElapsed = 0;
|
|
||||||
static double refreshInterval = 1.0;
|
|
||||||
|
|
||||||
double elapsed = stopwatch.GetElapsedSec();
|
std::cout << "=== ONLINE MODE ===" << std::endl;
|
||||||
double positionsPerSec = 0;
|
std::cout << "User: " << username << std::endl;
|
||||||
|
std::cout << "Target positions per cycle: " << targetPositions << std::endl;
|
||||||
|
std::cout << "Threads: " << threads << std::endl;
|
||||||
|
std::cout << "===================" << std::endl << std::endl;
|
||||||
|
|
||||||
if (elapsed - lastElapsed >= refreshInterval) {
|
while (!g_shutdownRequested) {
|
||||||
positionsPerSec = (positions - lastPositions) / (elapsed - lastElapsed);
|
std::cout << "Sending heartbeat..." << std::endl;
|
||||||
lastPositions = positions;
|
std::string heartbeatResponse;
|
||||||
lastElapsed = elapsed;
|
std::string heartbeatJSON = BuildHeartbeatJSON(username, threads);
|
||||||
}
|
|
||||||
|
|
||||||
std::cout << "\033[H";
|
if (!PostJSON(SERVER_URL + "/api/session/heartbeat", heartbeatJSON, heartbeatResponse)) {
|
||||||
|
std::cerr << "Failed to send heartbeat. Retrying in 10 seconds..." << std::endl;
|
||||||
int width = 60;
|
std::this_thread::sleep_for(std::chrono::seconds(10));
|
||||||
|
continue;
|
||||||
std::string title = "Eleanor - Datagen";
|
|
||||||
int titlePadding = (width - title.length()) / 2;
|
|
||||||
std::cout << COLOR_TITLE << std::setw(titlePadding + title.length()) << title << COLOR_RESET << std::endl;
|
|
||||||
|
|
||||||
std::cout << std::string(width, '=') << std::endl;
|
|
||||||
|
|
||||||
std::cout << std::endl;
|
|
||||||
|
|
||||||
std::cout << std::fixed << std::setprecision(0);
|
|
||||||
|
|
||||||
std::ostringstream datagenTextStream;
|
|
||||||
datagenTextStream << std::fixed << std::setprecision(2)
|
|
||||||
<< "Positions processed: " << positions / 1000.0 << "K | Target: " << targetPositions / 1000.0 << "K";
|
|
||||||
std::string datagenText = datagenTextStream.str();
|
|
||||||
int datagenPadding = (width - datagenText.length()) / 2;
|
|
||||||
std::cout << COLOR_SECTION << std::setw(datagenPadding + datagenText.length()) << datagenText << COLOR_RESET << std::endl;
|
|
||||||
|
|
||||||
std::cout << std::endl;
|
|
||||||
|
|
||||||
std::string elapsedText = "Elapsed Time: " + std::to_string(static_cast<int>(round(elapsed))) + " sec";
|
|
||||||
int elapsedPadding = (width - elapsedText.length()) / 2;
|
|
||||||
std::cout << COLOR_SECTION << std::setw(elapsedPadding + elapsedText.length()) << elapsedText << COLOR_RESET << std::endl;
|
|
||||||
|
|
||||||
std::string positionsPerSecText = "Positions/sec: " + std::to_string(static_cast<int>(round(positionsPerSec)));
|
|
||||||
int positionsPerSecPadding = (width - positionsPerSecText.length()) / 2;
|
|
||||||
std::cout << COLOR_VALUE << std::setw(positionsPerSecPadding + positionsPerSecText.length()) << positionsPerSecText << COLOR_RESET << std::endl;
|
|
||||||
|
|
||||||
std::cout << std::endl;
|
|
||||||
|
|
||||||
std::string threadsText = "Threads: " + std::to_string(static_cast<int>(threads));
|
|
||||||
int threadsTextPadding = (width - threadsText.length()) / 2;
|
|
||||||
std::cout << COLOR_SECTION << std::setw(threadsTextPadding + threadsText.length()) << threadsText << COLOR_RESET << std::endl;
|
|
||||||
|
|
||||||
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);
|
|
||||||
|
|
||||||
std::string progressBar = "[";
|
|
||||||
|
|
||||||
for (int i = 0; i < barWidth; ++i) {
|
|
||||||
if (i < pos) {
|
|
||||||
progressBar += "=";
|
|
||||||
} else if (i == pos) {
|
|
||||||
progressBar += ">";
|
|
||||||
} else {
|
|
||||||
progressBar += " ";
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::cout << "Heartbeat response: " << heartbeatResponse << std::endl;
|
||||||
|
|
||||||
|
std::string startResponse;
|
||||||
|
std::string startJSON = BuildStartJSON(username, targetPositions);
|
||||||
|
|
||||||
|
std::cout << "Starting new session..." << std::endl;
|
||||||
|
if (!PostJSON(SERVER_URL + "/api/session/start", startJSON, startResponse)) {
|
||||||
|
std::cerr << "Failed to start session. Retrying in 10 seconds..." << std::endl;
|
||||||
|
std::this_thread::sleep_for(std::chrono::seconds(10));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::cout << "Server response: " << startResponse << std::endl;
|
||||||
|
|
||||||
|
std::string sessionId = ExtractJSONValue(startResponse, "session_id");
|
||||||
|
if (sessionId.empty()) {
|
||||||
|
std::cerr << "Failed to parse session ID. Retrying..." << std::endl;
|
||||||
|
std::this_thread::sleep_for(std::chrono::seconds(10));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::cout << "Session ID: " << sessionId << std::endl;
|
||||||
|
|
||||||
|
std::atomic<bool> heartbeatStop(false);
|
||||||
|
std::thread heartbeat(HeartbeatThread, username, threads, std::ref(heartbeatStop), SERVER_URL);
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
system("cls");
|
||||||
|
HideCursor();
|
||||||
|
#else
|
||||||
|
std::cout << "\033[2J\033[H";
|
||||||
|
HideCursor();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
DatagenStats stats;
|
||||||
|
std::atomic<bool> stopFlag = false;
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
std::vector<HANDLE> workerThreads;
|
||||||
|
workerThreads.reserve((threads > 1) ? (threads - 1) : 0);
|
||||||
|
|
||||||
|
const size_t stackSizeBytes = 8ull * 1024ull * 1024ull;
|
||||||
|
|
||||||
|
for (int i = 0; i < threads - 1; ++i) {
|
||||||
|
CreateWorkerThread(i, stats, stopFlag, workerThreads, stackSizeBytes);
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
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);
|
||||||
|
|
||||||
|
auto* args = new std::tuple<int, DatagenStats*, std::atomic<bool>*>(i, &stats, &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 (stats.positions.load(std::memory_order_relaxed) < targetPositions && !g_shutdownRequested) {
|
||||||
|
PrintProgress(stats, targetPositions, sw, threads);
|
||||||
|
std::this_thread::sleep_for(std::chrono::seconds(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
PrintProgress(stats, targetPositions, sw, threads);
|
||||||
|
PrintSummary(stats, targetPositions, sw, threads);
|
||||||
|
|
||||||
|
stopFlag = true;
|
||||||
|
|
||||||
|
std::cout << "\n\nWaiting for threads to finish writing..." << std::endl;
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
JoinWorkerThreads(workerThreads);
|
||||||
|
#else
|
||||||
|
for (pthread_t& thread : workerThreads) {
|
||||||
|
pthread_join(thread, nullptr);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
heartbeatStop = true;
|
||||||
|
if (heartbeat.joinable()) {
|
||||||
|
heartbeat.join();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (g_shutdownRequested) break;
|
||||||
|
|
||||||
|
std::cout << "All threads completed. Merging files..." << std::endl;
|
||||||
|
std::string mergedFile = MergeThreadFiles();
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
ShowCursor();
|
||||||
|
#else
|
||||||
|
ShowCursor();
|
||||||
|
#endif
|
||||||
|
|
||||||
|
if (!mergedFile.empty()) {
|
||||||
|
std::cout << "Uploading file to server..." << std::endl;
|
||||||
|
std::string uploadUrl = SERVER_URL + "/api/upload/" + sessionId;
|
||||||
|
|
||||||
|
if (UploadFile(uploadUrl, mergedFile, username, stats.positions.load())) {
|
||||||
|
std::cout << "Upload successful!" << std::endl;
|
||||||
|
|
||||||
|
std::error_code ec;
|
||||||
|
std::filesystem::remove(mergedFile, ec);
|
||||||
|
if (!ec) {
|
||||||
|
std::cout << "Local file cleaned up." << std::endl;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
std::cerr << "Upload failed. File kept locally: " << mergedFile << std::endl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (g_shutdownRequested) break;
|
||||||
|
|
||||||
|
std::cout << "\n=== Starting next cycle ===" << std::endl << std::endl;
|
||||||
|
std::this_thread::sleep_for(std::chrono::seconds(2));
|
||||||
}
|
}
|
||||||
|
|
||||||
progressBar += "] " + std::to_string(static_cast<int>(round(progress * 100.0))) + " %";
|
std::cout << "\nOnline mode shutdown complete." << std::endl;
|
||||||
|
|
||||||
int progressPadding = (width - progressBar.length()) / 2;
|
|
||||||
std::cout << COLOR_BAR << std::setw(progressPadding + progressBar.length()) << progressBar << COLOR_RESET << std::endl;
|
|
||||||
|
|
||||||
std::cout << std::endl;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
} // namespace DATAGEN
|
||||||
+12
-22
@@ -1,16 +1,26 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
#include "board.h"
|
#include "board.h"
|
||||||
#include "utils.h"
|
#include "utils.h"
|
||||||
|
#include <atomic>
|
||||||
#include <fstream>
|
#include <fstream>
|
||||||
#include "stopwatch.h"
|
#include "stopwatch.h"
|
||||||
|
|
||||||
namespace DATAGEN {
|
namespace DATAGEN {
|
||||||
|
|
||||||
constexpr int GAME_BUFFER = 1000;
|
constexpr int GAME_BUFFER = 500;
|
||||||
constexpr int SOFT_NODES = 5000;
|
constexpr int SOFT_NODES = 5000;
|
||||||
constexpr int HARD_NODES = 100000;
|
constexpr int HARD_NODES = 100000;
|
||||||
constexpr int RAND_MOVES = 8;
|
constexpr int RAND_MOVES = 8;
|
||||||
|
|
||||||
|
// Live counters shared between the worker threads and the frontend.
|
||||||
|
struct DatagenStats {
|
||||||
|
std::atomic<int> positions{0};
|
||||||
|
std::atomic<int> games{0};
|
||||||
|
std::atomic<int> files{0};
|
||||||
|
std::atomic<long long> nodes{0};
|
||||||
|
std::atomic<int> rejected{0};
|
||||||
|
};
|
||||||
|
|
||||||
struct MarlinFormat {
|
struct MarlinFormat {
|
||||||
uint64_t occupancy; // 8 bytes: Bitboard representing all occupied squares (includes all pieces)
|
uint64_t occupancy; // 8 bytes: Bitboard representing all occupied squares (includes all pieces)
|
||||||
std::array<uint8_t, 16> pieces; // 16 bytes: 64 squares stored in 4-bit format (2 squares per byte)
|
std::array<uint8_t, 16> pieces; // 16 bytes: 64 squares stored in 4-bit format (2 squares per byte)
|
||||||
@@ -34,25 +44,6 @@ struct MarlinFormat {
|
|||||||
this->wdl = wdl;
|
this->wdl = wdl;
|
||||||
extra = 0;
|
extra = 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
void writeToFile(const std::string& filename) const {
|
|
||||||
std::ofstream outFile(filename, std::ios::binary);
|
|
||||||
if (!outFile) {
|
|
||||||
std::cerr << "Error opening file for writing!" << std::endl;
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
outFile.write(reinterpret_cast<const char*>(&occupancy), sizeof(occupancy));
|
|
||||||
outFile.write(reinterpret_cast<const char*>(&pieces), sizeof(pieces));
|
|
||||||
outFile.write(reinterpret_cast<const char*>(&stmEPSquare), sizeof(stmEPSquare));
|
|
||||||
outFile.write(reinterpret_cast<const char*>(&halfmoveClock), sizeof(halfmoveClock));
|
|
||||||
outFile.write(reinterpret_cast<const char*>(&fullmoveNumber), sizeof(fullmoveNumber));
|
|
||||||
outFile.write(reinterpret_cast<const char*>(&eval), sizeof(eval));
|
|
||||||
outFile.write(reinterpret_cast<const char*>(&wdl), sizeof(wdl));
|
|
||||||
outFile.write(reinterpret_cast<const char*>(&extra), sizeof(extra));
|
|
||||||
|
|
||||||
outFile.close();
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
struct ScoredMove {
|
struct ScoredMove {
|
||||||
@@ -80,6 +71,5 @@ struct Game {
|
|||||||
};
|
};
|
||||||
|
|
||||||
void Run(int targetPositions, int threads);
|
void Run(int targetPositions, int threads);
|
||||||
|
void RunOnline(const std::string& username, int targetPositions, int threads);
|
||||||
void PrintProgress(int positions, int targetPositions, Stopwatch &stopwatch, int threads);
|
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,639 @@
|
|||||||
|
#include <algorithm>
|
||||||
|
#include <cctype>
|
||||||
|
#include <clocale>
|
||||||
|
#include <cmath>
|
||||||
|
#include <cstdio>
|
||||||
|
#include <cstdlib>
|
||||||
|
#include <cstring>
|
||||||
|
#include <deque>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#include "datagenui.h"
|
||||||
|
#include "datagen.h"
|
||||||
|
#include "stopwatch.h"
|
||||||
|
|
||||||
|
// OS-dependent terminal detection includes
|
||||||
|
#ifdef _WIN32
|
||||||
|
#include <windows.h>
|
||||||
|
#include <io.h>
|
||||||
|
#else
|
||||||
|
#include <unistd.h>
|
||||||
|
#include <langinfo.h>
|
||||||
|
#include <sys/ioctl.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace DATAGEN {
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
constexpr int kMinWidth = 64;
|
||||||
|
constexpr int kMaxWidth = 96;
|
||||||
|
constexpr std::size_t kMaxSamples = 720;
|
||||||
|
|
||||||
|
bool Interactive() {
|
||||||
|
static const bool value = [] {
|
||||||
|
#ifdef _WIN32
|
||||||
|
return _isatty(_fileno(stdout)) != 0;
|
||||||
|
#else
|
||||||
|
return isatty(STDOUT_FILENO) != 0;
|
||||||
|
#endif
|
||||||
|
}();
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool UseColor() {
|
||||||
|
static const bool value = [] {
|
||||||
|
#ifdef _WIN32
|
||||||
|
HANDLE out = GetStdHandle(STD_OUTPUT_HANDLE);
|
||||||
|
DWORD mode = 0;
|
||||||
|
if (out != INVALID_HANDLE_VALUE && GetConsoleMode(out, &mode))
|
||||||
|
SetConsoleMode(out, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING);
|
||||||
|
return Interactive() && std::getenv("NO_COLOR") == nullptr;
|
||||||
|
#else
|
||||||
|
return Interactive() && std::getenv("NO_COLOR") == nullptr;
|
||||||
|
#endif
|
||||||
|
}();
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool UseUnicode() {
|
||||||
|
static const bool value = [] {
|
||||||
|
std::setlocale(LC_ALL, "");
|
||||||
|
#ifdef _WIN32
|
||||||
|
SetConsoleOutputCP(CP_UTF8);
|
||||||
|
return true;
|
||||||
|
#else
|
||||||
|
const char* codeset = nl_langinfo(CODESET);
|
||||||
|
return codeset != nullptr
|
||||||
|
&& (std::strstr(codeset, "UTF-8") != nullptr || std::strstr(codeset, "UTF8") != nullptr);
|
||||||
|
#endif
|
||||||
|
}();
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
int DetectWidth() {
|
||||||
|
#ifdef _WIN32
|
||||||
|
CONSOLE_SCREEN_BUFFER_INFO info;
|
||||||
|
if (GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &info))
|
||||||
|
return info.srWindow.Right - info.srWindow.Left + 1;
|
||||||
|
#else
|
||||||
|
struct winsize ws;
|
||||||
|
if (ioctl(STDOUT_FILENO, TIOCGWINSZ, &ws) == 0 && ws.ws_col > 0)
|
||||||
|
return ws.ws_col;
|
||||||
|
#endif
|
||||||
|
return 80;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string Sgr(const char* code) {
|
||||||
|
return UseColor() ? "\033[" + std::string(code) + "m" : std::string();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string Reset() { return Sgr("0"); }
|
||||||
|
|
||||||
|
std::string Fg(int r, int g, int b) {
|
||||||
|
if (!UseColor()) return "";
|
||||||
|
return "\033[38;2;" + std::to_string(r) + ";" + std::to_string(g) + ";" + std::to_string(b) + "m";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Cyan -> spring green across the progress bar.
|
||||||
|
std::string GradientAt(double t) {
|
||||||
|
t = std::clamp(t, 0.0, 1.0);
|
||||||
|
return Fg(static_cast<int>(std::lround(0 + t * 80)),
|
||||||
|
static_cast<int>(std::lround(180 + t * 75)),
|
||||||
|
static_cast<int>(std::lround(255 - t * 115)));
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Glyphs {
|
||||||
|
const char* tl;
|
||||||
|
const char* tr;
|
||||||
|
const char* bl;
|
||||||
|
const char* br;
|
||||||
|
const char* h;
|
||||||
|
const char* v;
|
||||||
|
const char* full;
|
||||||
|
const char* empty;
|
||||||
|
const char* dot;
|
||||||
|
};
|
||||||
|
|
||||||
|
Glyphs PickGlyphs() {
|
||||||
|
if (UseUnicode()) {
|
||||||
|
return {"\u256D", "\u256E", "\u2570", "\u256F", "\u2500",
|
||||||
|
"\u2502", "\u2588", "\u2591", "\u00B7"};
|
||||||
|
}
|
||||||
|
return {"+", "+", "+", "+", "-", "|", "#", ".", "."};
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> SparkLevels() {
|
||||||
|
if (UseUnicode()) {
|
||||||
|
return {"\u2581", "\u2582", "\u2583", "\u2584", "\u2585", "\u2586", "\u2587", "\u2588"};
|
||||||
|
}
|
||||||
|
return {"_", ".", "-", "=", "+", "*", "#", "%", "@"};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Width in terminal cells, ignoring ANSI escapes and counting UTF-8 sequences once.
|
||||||
|
int VisibleWidth(const std::string& s) {
|
||||||
|
int len = 0;
|
||||||
|
for (std::size_t i = 0; i < s.size(); ++i) {
|
||||||
|
if (s[i] == '\033') {
|
||||||
|
std::size_t j = i + 1;
|
||||||
|
if (j < s.size() && s[j] == '[') {
|
||||||
|
++j;
|
||||||
|
while (j < s.size()
|
||||||
|
&& (std::isdigit(static_cast<unsigned char>(s[j])) || s[j] == ';')) {
|
||||||
|
++j;
|
||||||
|
}
|
||||||
|
if (j < s.size()) ++j;
|
||||||
|
i = j - 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ((static_cast<unsigned char>(s[i]) & 0xC0) != 0x80) ++len;
|
||||||
|
}
|
||||||
|
return len;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string PadRight(const std::string& s, int width) {
|
||||||
|
const int pad = width - VisibleWidth(s);
|
||||||
|
return pad > 0 ? s + std::string(pad, ' ') : s;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Hard guarantee that nothing ever escapes the frame, whatever the contents.
|
||||||
|
std::string Truncate(const std::string& s, int maxWidth) {
|
||||||
|
if (VisibleWidth(s) <= maxWidth) return s;
|
||||||
|
|
||||||
|
std::string out;
|
||||||
|
int len = 0;
|
||||||
|
bool colored = false;
|
||||||
|
|
||||||
|
for (std::size_t i = 0; i < s.size(); ++i) {
|
||||||
|
if (s[i] == '\033') {
|
||||||
|
std::size_t j = i + 1;
|
||||||
|
if (j < s.size() && s[j] == '[') {
|
||||||
|
++j;
|
||||||
|
while (j < s.size()
|
||||||
|
&& (std::isdigit(static_cast<unsigned char>(s[j])) || s[j] == ';')) {
|
||||||
|
++j;
|
||||||
|
}
|
||||||
|
if (j < s.size()) ++j;
|
||||||
|
out.append(s, i, j - i);
|
||||||
|
colored = true;
|
||||||
|
i = j - 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((static_cast<unsigned char>(s[i]) & 0xC0) == 0x80) {
|
||||||
|
out += s[i];
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (len >= maxWidth) break;
|
||||||
|
out += s[i];
|
||||||
|
++len;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (colored) out += Reset();
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string Rule(const char* left, const char* right, const Glyphs& g, int inner,
|
||||||
|
const std::string& color) {
|
||||||
|
std::string s = color + left;
|
||||||
|
for (int i = 0; i < inner; ++i) s += g.h;
|
||||||
|
s += right;
|
||||||
|
s += Reset();
|
||||||
|
return s;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string Row(const std::string& content, const Glyphs& g, int inner, const std::string& border) {
|
||||||
|
return border + g.v + Reset() + PadRight(Truncate(content, inner), inner) + border + g.v + Reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string SplitRow(const std::string& left, const std::string& right, const Glyphs& g, int inner,
|
||||||
|
const std::string& border) {
|
||||||
|
const int gap = inner - VisibleWidth(left) - VisibleWidth(right);
|
||||||
|
return Row(left + std::string(gap > 0 ? gap : 1, ' ') + right, g, inner, border);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string DotLeaders(const std::string& key, const std::string& value, int width,
|
||||||
|
const std::string& keyColor, const std::string& valueColor,
|
||||||
|
const Glyphs& g) {
|
||||||
|
const int dots = width - VisibleWidth(key) - VisibleWidth(value) - 2;
|
||||||
|
std::string s = keyColor + key + Reset();
|
||||||
|
|
||||||
|
if (dots > 0) {
|
||||||
|
s += ' ';
|
||||||
|
for (int i = 0; i < dots; ++i) s += g.dot;
|
||||||
|
}
|
||||||
|
|
||||||
|
return s + ' ' + valueColor + value + Reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string FormatCount(long long value) {
|
||||||
|
char buf[64];
|
||||||
|
const double d = static_cast<double>(value);
|
||||||
|
const double a = std::abs(d);
|
||||||
|
|
||||||
|
if (a >= 1e9) std::snprintf(buf, sizeof(buf), "%.2fB", d / 1e9);
|
||||||
|
else if (a >= 1e6) std::snprintf(buf, sizeof(buf), "%.2fM", d / 1e6);
|
||||||
|
else if (a >= 1e3) std::snprintf(buf, sizeof(buf), "%.1fK", d / 1e3);
|
||||||
|
else std::snprintf(buf, sizeof(buf), "%lld", value);
|
||||||
|
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string FormatThousands(long long value) {
|
||||||
|
std::string digits = std::to_string(value);
|
||||||
|
for (int i = static_cast<int>(digits.size()) - 3; i > 0; i -= 3)
|
||||||
|
digits.insert(i, ",");
|
||||||
|
return digits;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string FormatDuration(double seconds) {
|
||||||
|
if (!std::isfinite(seconds) || seconds < 0) return "--";
|
||||||
|
|
||||||
|
const long long total = static_cast<long long>(seconds);
|
||||||
|
const long long h = total / 3600;
|
||||||
|
const long long m = (total % 3600) / 60;
|
||||||
|
const long long s = total % 60;
|
||||||
|
|
||||||
|
char buf[64];
|
||||||
|
if (h > 0) std::snprintf(buf, sizeof(buf), "%lldh %02lldm", h, m);
|
||||||
|
else if (m > 0) std::snprintf(buf, sizeof(buf), "%lldm %02llds", m, s);
|
||||||
|
else std::snprintf(buf, sizeof(buf), "%llds", s);
|
||||||
|
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string BuildSparkline(const std::deque<double>& samples, int width,
|
||||||
|
const std::vector<std::string>& levels, const std::string& color) {
|
||||||
|
if (width <= 0 || samples.empty()) return "";
|
||||||
|
|
||||||
|
const int count = static_cast<int>(samples.size());
|
||||||
|
const int take = std::min(count, width);
|
||||||
|
const int start = count - take;
|
||||||
|
|
||||||
|
double lo = samples[start];
|
||||||
|
double hi = samples[start];
|
||||||
|
for (int i = start; i < count; ++i) {
|
||||||
|
lo = std::min(lo, samples[i]);
|
||||||
|
hi = std::max(hi, samples[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
const double range = hi - lo;
|
||||||
|
const int last = static_cast<int>(levels.size()) - 1;
|
||||||
|
|
||||||
|
std::string bar;
|
||||||
|
// Pad the left side with blanks so "no data yet" is not confused with a low sample.
|
||||||
|
for (int i = 0; i < width - take; ++i) bar += ' ';
|
||||||
|
|
||||||
|
for (int i = start; i < count; ++i) {
|
||||||
|
const int idx = range > 1e-9
|
||||||
|
? static_cast<int>(std::lround((samples[i] - lo) / range * last))
|
||||||
|
: last;
|
||||||
|
bar += levels[std::clamp(idx, 0, last)];
|
||||||
|
}
|
||||||
|
|
||||||
|
return color + bar + Reset();
|
||||||
|
}
|
||||||
|
|
||||||
|
struct RateTracker {
|
||||||
|
std::deque<double> samples;
|
||||||
|
double lastTime = 0.0;
|
||||||
|
double lastCount = 0.0;
|
||||||
|
double current = 0.0;
|
||||||
|
double smoothed = 0.0;
|
||||||
|
double peak = 0.0;
|
||||||
|
|
||||||
|
void sample(double count, double elapsed) {
|
||||||
|
if (elapsed - lastTime < 1.0) return;
|
||||||
|
|
||||||
|
const double window = elapsed - lastTime;
|
||||||
|
const double instant = window > 0 ? (count - lastCount) / window : 0.0;
|
||||||
|
|
||||||
|
lastTime = elapsed;
|
||||||
|
lastCount = count;
|
||||||
|
|
||||||
|
samples.push_back(instant);
|
||||||
|
if (samples.size() > kMaxSamples) samples.pop_front();
|
||||||
|
|
||||||
|
current = instant;
|
||||||
|
smoothed = smoothed == 0.0 ? instant : smoothed * 0.65 + instant * 0.35;
|
||||||
|
peak = std::max(peak, instant);
|
||||||
|
}
|
||||||
|
|
||||||
|
void reset() {
|
||||||
|
samples.clear();
|
||||||
|
lastTime = lastCount = current = smoothed = peak = 0.0;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
RateTracker& PositionsRate() {
|
||||||
|
static RateTracker tracker;
|
||||||
|
return tracker;
|
||||||
|
}
|
||||||
|
|
||||||
|
RateTracker& NodesRate() {
|
||||||
|
static RateTracker tracker;
|
||||||
|
return tracker;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Shared header row: "ELEANOR - DATAGEN" on the left, a status pill on the right.
|
||||||
|
std::string HeaderRow(const Glyphs& g, int inner, const std::string& border,
|
||||||
|
const std::string& status, const std::string& statusColor) {
|
||||||
|
const std::string bullet = UseUnicode() ? "\u25CF" : "*";
|
||||||
|
const std::string left = Sgr("1") + Fg(190, 220, 255) + "ELEANOR"
|
||||||
|
+ Fg(90, 100, 120) + " " + g.dot + " " + Sgr("0") + Fg(140, 150, 170) + "DATAGEN";
|
||||||
|
const std::string pill = statusColor + bullet + " " + Sgr("1") + status + Reset();
|
||||||
|
return SplitRow(" " + left, pill + " ", g, inner, border);
|
||||||
|
}
|
||||||
|
|
||||||
|
struct Snapshot {
|
||||||
|
long long positions = 0;
|
||||||
|
long long games = 0;
|
||||||
|
long long files = 0;
|
||||||
|
long long nodes = 0;
|
||||||
|
long long rejected = 0;
|
||||||
|
double elapsed = 0;
|
||||||
|
double posSpeed = 0;
|
||||||
|
double posPeak = 0;
|
||||||
|
double nodeSpeed = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
Snapshot TakeSnapshot(const DatagenStats& stats, Stopwatch& stopwatch) {
|
||||||
|
Snapshot snap;
|
||||||
|
snap.positions = stats.positions.load(std::memory_order_relaxed);
|
||||||
|
snap.games = stats.games.load(std::memory_order_relaxed);
|
||||||
|
snap.files = stats.files.load(std::memory_order_relaxed);
|
||||||
|
snap.nodes = stats.nodes.load(std::memory_order_relaxed);
|
||||||
|
snap.rejected = stats.rejected.load(std::memory_order_relaxed);
|
||||||
|
snap.elapsed = stopwatch.GetElapsedSec();
|
||||||
|
|
||||||
|
PositionsRate().sample(static_cast<double>(snap.positions), snap.elapsed);
|
||||||
|
NodesRate().sample(static_cast<double>(snap.nodes), snap.elapsed);
|
||||||
|
|
||||||
|
snap.posSpeed = PositionsRate().smoothed;
|
||||||
|
snap.posPeak = PositionsRate().peak;
|
||||||
|
snap.nodeSpeed = NodesRate().smoothed;
|
||||||
|
return snap;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::string FormatSpeed(double perSecond) {
|
||||||
|
char buf[64];
|
||||||
|
if (perSecond >= 1e9) std::snprintf(buf, sizeof(buf), "%.2fB/s", perSecond / 1e9);
|
||||||
|
else if (perSecond >= 1e6) std::snprintf(buf, sizeof(buf), "%.2fM/s", perSecond / 1e6);
|
||||||
|
else if (perSecond >= 1e3) std::snprintf(buf, sizeof(buf), "%.1fK/s", perSecond / 1e3);
|
||||||
|
else std::snprintf(buf, sizeof(buf), "%.0f/s", perSecond);
|
||||||
|
return buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
void PrintPlainLine(const Snapshot& snap, int targetPositions, int threads) {
|
||||||
|
const double progress = targetPositions > 0
|
||||||
|
? 100.0 * snap.positions / targetPositions : 0.0;
|
||||||
|
const double remaining = snap.posSpeed > 0
|
||||||
|
? (targetPositions - snap.positions) / snap.posSpeed : 0.0;
|
||||||
|
|
||||||
|
std::printf("[datagen] %lld/%d (%.1f%%) %s nodes %s elapsed %s eta %s games %lld files %lld threads %d\n",
|
||||||
|
snap.positions, targetPositions, progress,
|
||||||
|
FormatSpeed(snap.posSpeed).c_str(), FormatCount(snap.nodes).c_str(),
|
||||||
|
FormatDuration(snap.elapsed).c_str(), FormatDuration(remaining).c_str(),
|
||||||
|
snap.games, snap.files, threads);
|
||||||
|
std::fflush(stdout);
|
||||||
|
}
|
||||||
|
|
||||||
|
std::vector<std::string> BuildFrame(const Snapshot& snap, int targetPositions, int threads,
|
||||||
|
bool finished) {
|
||||||
|
const Glyphs g = PickGlyphs();
|
||||||
|
const auto levels = SparkLevels();
|
||||||
|
|
||||||
|
const int width = std::clamp(DetectWidth(), kMinWidth, kMaxWidth);
|
||||||
|
const int inner = width - 2;
|
||||||
|
|
||||||
|
const std::string accent = Fg(120, 190, 255);
|
||||||
|
const std::string border = Fg(70, 80, 100);
|
||||||
|
const std::string label = Fg(130, 140, 160);
|
||||||
|
const std::string value = Fg(235, 240, 250);
|
||||||
|
const std::string heading = Sgr("1") + Fg(150, 200, 255);
|
||||||
|
const std::string good = Fg(120, 235, 160);
|
||||||
|
const std::string warn = Fg(245, 200, 110);
|
||||||
|
|
||||||
|
const double progress = targetPositions > 0
|
||||||
|
? std::clamp(static_cast<double>(snap.positions) / targetPositions, 0.0, 1.0)
|
||||||
|
: 0.0;
|
||||||
|
|
||||||
|
const double remaining = snap.posSpeed > 0
|
||||||
|
? std::max(0.0, (targetPositions - snap.positions) / snap.posSpeed) : 0.0;
|
||||||
|
|
||||||
|
const double avgGame = snap.games > 0
|
||||||
|
? static_cast<double>(snap.positions) / snap.games : 0.0;
|
||||||
|
|
||||||
|
const long long attempted = snap.games + snap.rejected;
|
||||||
|
const double acceptRate = attempted > 0
|
||||||
|
? 100.0 * snap.games / attempted : 0.0;
|
||||||
|
|
||||||
|
std::vector<std::string> out;
|
||||||
|
out.push_back(Rule(g.tl, g.tr, g, inner, border));
|
||||||
|
|
||||||
|
out.push_back(HeaderRow(g, inner, border, finished ? "STOPPED" : "GENERATING",
|
||||||
|
finished ? warn : good));
|
||||||
|
|
||||||
|
out.push_back(Rule(g.v, g.v, g, inner, border));
|
||||||
|
|
||||||
|
// Headline counters.
|
||||||
|
{
|
||||||
|
char pct[32];
|
||||||
|
std::snprintf(pct, sizeof(pct), "%.1f%%", progress * 100.0);
|
||||||
|
|
||||||
|
const std::string left = " " + Sgr("1") + Fg(225, 235, 250) + FormatCount(snap.positions)
|
||||||
|
+ Fg(110, 120, 140) + " / " + FormatCount(targetPositions)
|
||||||
|
+ Fg(110, 120, 140) + " positions";
|
||||||
|
|
||||||
|
const std::string right = Sgr("1") + GradientAt(progress) + pct + Reset();
|
||||||
|
|
||||||
|
out.push_back(SplitRow(left, right + " ", g, inner, border));
|
||||||
|
|
||||||
|
const int barWidth = inner - 4;
|
||||||
|
const int filled = static_cast<int>(std::lround(progress * barWidth));
|
||||||
|
|
||||||
|
std::string bar;
|
||||||
|
for (int i = 0; i < barWidth; ++i) {
|
||||||
|
if (i < filled) bar += GradientAt(barWidth > 1 ? static_cast<double>(i) / (barWidth - 1) : 0.0) + g.full;
|
||||||
|
else bar += Fg(45, 50, 62) + g.empty;
|
||||||
|
}
|
||||||
|
bar += Reset();
|
||||||
|
|
||||||
|
out.push_back(Row(" " + bar, g, inner, border));
|
||||||
|
}
|
||||||
|
|
||||||
|
out.push_back(Row("", g, inner, border));
|
||||||
|
out.push_back(Rule(g.v, g.v, g, inner, border));
|
||||||
|
|
||||||
|
// Two-column statistics.
|
||||||
|
const int half = (inner - 3) / 2;
|
||||||
|
const int rightStart = half + 3;
|
||||||
|
const int rightWidth = inner - rightStart - 2;
|
||||||
|
|
||||||
|
auto statRow = [&](const char* lk, const std::string& lv, const char* rk, const std::string& rv) {
|
||||||
|
const std::string l = DotLeaders(lk, lv, half, label, value, g);
|
||||||
|
const std::string r = DotLeaders(rk, rv, rightWidth, label, value, g);
|
||||||
|
out.push_back(Row(" " + l + " " + r, g, inner, border));
|
||||||
|
};
|
||||||
|
|
||||||
|
out.push_back(Row(" " + heading + "THROUGHPUT" + Reset() + " "
|
||||||
|
+ heading + "SESSION" + Reset(), g, inner, border));
|
||||||
|
out.push_back(Row("", g, inner, border));
|
||||||
|
|
||||||
|
statRow("speed", FormatSpeed(snap.posSpeed), "elapsed", FormatDuration(snap.elapsed));
|
||||||
|
statRow("peak", FormatSpeed(snap.posPeak), "remaining", FormatDuration(remaining));
|
||||||
|
statRow("nodes", FormatCount(snap.nodes), "threads", std::to_string(threads));
|
||||||
|
statRow("node speed", FormatSpeed(snap.nodeSpeed), "progress",
|
||||||
|
[&] { char b[32]; std::snprintf(b, sizeof(b), "%.1f%%", progress * 100.0); return std::string(b); }());
|
||||||
|
|
||||||
|
out.push_back(Row("", g, inner, border));
|
||||||
|
statRow("games", FormatThousands(snap.games), "files", FormatThousands(snap.files));
|
||||||
|
statRow("rejected", FormatThousands(snap.rejected), "avg game",
|
||||||
|
[&] { char b[32]; std::snprintf(b, sizeof(b), "%.1f pos", avgGame); return std::string(b); }());
|
||||||
|
statRow("accept", [&] { char b[32]; std::snprintf(b, sizeof(b), "%.1f%%", acceptRate); return std::string(b); }(),
|
||||||
|
"nodes/pos",
|
||||||
|
[&] { char b[32]; std::snprintf(b, sizeof(b), "%.0f",
|
||||||
|
snap.positions > 0 ? static_cast<double>(snap.nodes) / snap.positions : 0.0); return std::string(b); }());
|
||||||
|
|
||||||
|
// Throughput history.
|
||||||
|
const int sparkWidth = inner - 4;
|
||||||
|
out.push_back(Row("", g, inner, border));
|
||||||
|
out.push_back(Row(" " + label + "throughput history" + Reset(), g, inner, border));
|
||||||
|
out.push_back(Row(" " + BuildSparkline(PositionsRate().samples, sparkWidth, levels, accent),
|
||||||
|
g, inner, border));
|
||||||
|
|
||||||
|
out.push_back(Rule(g.v, g.v, g, inner, border));
|
||||||
|
|
||||||
|
out.push_back(Row(" " + label
|
||||||
|
+ (finished ? "run finished " + std::string(g.dot) + " data written to data/*.binpack"
|
||||||
|
: "Ctrl+C to stop safely " + std::string(g.dot) + " data is flushed on exit")
|
||||||
|
+ Reset(),
|
||||||
|
g, inner, border));
|
||||||
|
|
||||||
|
out.push_back(Rule(g.bl, g.br, g, inner, border));
|
||||||
|
return out;
|
||||||
|
}
|
||||||
|
|
||||||
|
void DrawFrame(const std::vector<std::string>& frame) {
|
||||||
|
std::string buffer;
|
||||||
|
buffer.reserve(frame.size() * 96);
|
||||||
|
buffer += "\033[H";
|
||||||
|
|
||||||
|
for (const std::string& line : frame) {
|
||||||
|
buffer += line;
|
||||||
|
buffer += '\n';
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer += "\033[J";
|
||||||
|
std::fwrite(buffer.data(), 1, buffer.size(), stdout);
|
||||||
|
std::fflush(stdout);
|
||||||
|
}
|
||||||
|
|
||||||
|
void ClearFrame() {
|
||||||
|
if (!Interactive()) return;
|
||||||
|
std::fputs("\033[H\033[J", stdout);
|
||||||
|
std::fflush(stdout);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
void PrintProgress(const DatagenStats& stats, int targetPositions, Stopwatch &stopwatch, int threads) {
|
||||||
|
const Snapshot snap = TakeSnapshot(stats, stopwatch);
|
||||||
|
|
||||||
|
if (!Interactive()) {
|
||||||
|
PrintPlainLine(snap, targetPositions, threads);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
DrawFrame(BuildFrame(snap, targetPositions, threads, false));
|
||||||
|
}
|
||||||
|
|
||||||
|
void PrintSummary(const DatagenStats& stats, int targetPositions, Stopwatch &stopwatch, int threads) {
|
||||||
|
const Snapshot snap = TakeSnapshot(stats, stopwatch);
|
||||||
|
|
||||||
|
if (!Interactive()) {
|
||||||
|
PrintPlainLine(snap, targetPositions, threads);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ClearFrame();
|
||||||
|
DrawFrame(BuildFrame(snap, targetPositions, threads, true));
|
||||||
|
}
|
||||||
|
|
||||||
|
void PrintUsage() {
|
||||||
|
const Glyphs g = PickGlyphs();
|
||||||
|
|
||||||
|
// Help text is denser than the dashboard, so allow a slightly wider frame.
|
||||||
|
const int width = std::clamp(DetectWidth(), kMinWidth, 100);
|
||||||
|
const int inner = width - 2;
|
||||||
|
|
||||||
|
const std::string accent = Fg(120, 190, 255);
|
||||||
|
const std::string border = Fg(70, 80, 100);
|
||||||
|
const std::string label = Fg(130, 140, 160);
|
||||||
|
const std::string value = Fg(235, 240, 250);
|
||||||
|
const std::string heading = Sgr("1") + Fg(150, 200, 255);
|
||||||
|
|
||||||
|
std::vector<std::string> out;
|
||||||
|
out.push_back(Rule(g.tl, g.tr, g, inner, border));
|
||||||
|
out.push_back(HeaderRow(g, inner, border, "HELP", accent));
|
||||||
|
out.push_back(Rule(g.v, g.v, g, inner, border));
|
||||||
|
|
||||||
|
auto blank = [&]() { out.push_back(Row("", g, inner, border)); };
|
||||||
|
auto section = [&](const char* name) {
|
||||||
|
blank();
|
||||||
|
out.push_back(Row(" " + heading + name + Reset(), g, inner, border));
|
||||||
|
};
|
||||||
|
auto line = [&](const std::string& content) {
|
||||||
|
out.push_back(Row(" " + content, g, inner, border));
|
||||||
|
};
|
||||||
|
// A two-column row: fixed-width term on the left, description on the right.
|
||||||
|
auto term = [&](const std::string& name, const std::string& desc, int nameWidth = 11) {
|
||||||
|
out.push_back(Row(" " + Sgr("1") + accent + PadRight(name + Reset(), nameWidth) + desc,
|
||||||
|
g, inner, border));
|
||||||
|
};
|
||||||
|
auto note = [&](const std::string& text) {
|
||||||
|
line(label + g.dot + " " + text + Reset());
|
||||||
|
};
|
||||||
|
auto usage = [&](const std::string& args, const std::string& comment) {
|
||||||
|
const std::string padded = PadRight(value + args + Reset(), 28);
|
||||||
|
line(comment.empty() ? padded : padded + label + comment + Reset());
|
||||||
|
};
|
||||||
|
|
||||||
|
section("SYNTAX");
|
||||||
|
usage("Eleanor datagen [positions] [threads] [username]", "");
|
||||||
|
usage("Eleanor datagen --help", "");
|
||||||
|
|
||||||
|
section("ARGUMENTS");
|
||||||
|
term("positions", "Target size in thousands, multiplied by 1000.", 12);
|
||||||
|
term("", label + "Default 1 = 1,000 positions.");
|
||||||
|
term("threads", "Number of worker threads.", 12);
|
||||||
|
term("", label + "No default, minimum 2.");
|
||||||
|
term("username", "Enables online mode: registers a session", 12);
|
||||||
|
term("", "on the coordination server and uploads the data.");
|
||||||
|
|
||||||
|
section("EXAMPLES");
|
||||||
|
usage("Eleanor datagen 1000 22", "1,000,000 positions on 22 threads");
|
||||||
|
usage("Eleanor datagen 10 8", "10,000 positions on 8 threads");
|
||||||
|
usage("Eleanor datagen 1000 22 me", "1,000,000 positions, online mode");
|
||||||
|
|
||||||
|
section("NOTES");
|
||||||
|
note("Data is written to data/datagen_<timestamp>.binpack");
|
||||||
|
note("Press Ctrl+C to stop safely; partial data is flushed and merged.");
|
||||||
|
note("Each game starts from the initial position after 8-9 random plies.");
|
||||||
|
note("Openings scored beyond +/-200cp are discarded for evenness.");
|
||||||
|
note("A threads value of N starts N-1 generators, minimum 2.");
|
||||||
|
|
||||||
|
blank();
|
||||||
|
out.push_back(Rule(g.bl, g.br, g, inner, border));
|
||||||
|
|
||||||
|
for (const std::string& l : out) {
|
||||||
|
std::fputs((l + "\n").c_str(), stdout);
|
||||||
|
}
|
||||||
|
std::fflush(stdout);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace DATAGEN
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
#pragma once
|
||||||
|
#include "datagen.h"
|
||||||
|
#include "stopwatch.h"
|
||||||
|
|
||||||
|
namespace DATAGEN {
|
||||||
|
|
||||||
|
void PrintProgress(const DatagenStats& stats, int targetPositions, Stopwatch &stopwatch, int threads);
|
||||||
|
void PrintSummary(const DatagenStats& stats, int targetPositions, Stopwatch &stopwatch, int threads);
|
||||||
|
void PrintUsage();
|
||||||
|
|
||||||
|
} // namespace DATAGEN
|
||||||
+306
-28
@@ -5,9 +5,14 @@
|
|||||||
#include "benchmark.h"
|
#include "benchmark.h"
|
||||||
#include "search.h"
|
#include "search.h"
|
||||||
#include "datagen.h"
|
#include "datagen.h"
|
||||||
|
#include "datagenui.h"
|
||||||
#include "nnue.h"
|
#include "nnue.h"
|
||||||
#include "tests.h"
|
#include "tests.h"
|
||||||
|
|
||||||
|
#include <iostream>
|
||||||
|
#include <string>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
#ifndef EVALFILE
|
#ifndef EVALFILE
|
||||||
#define EVALFILE "./nnue.bin"
|
#define EVALFILE "./nnue.bin"
|
||||||
#endif
|
#endif
|
||||||
@@ -29,6 +34,77 @@
|
|||||||
INCBIN(EVAL, EVALFILE);
|
INCBIN(EVAL, EVALFILE);
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
// Strict integer parsing: returns 0 when the text is not a positive whole number,
|
||||||
|
// so bad CLI input reports a usage error instead of throwing std::invalid_argument.
|
||||||
|
static int ParsePositiveInt(const char* text) {
|
||||||
|
if (text == nullptr || *text == '\0') return 0;
|
||||||
|
|
||||||
|
for (const char* c = text; *c != '\0'; ++c) {
|
||||||
|
if (*c < '0' || *c > '9') return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const long long value = std::stoll(text);
|
||||||
|
if (value <= 0 || value > 2147483647LL) return 0;
|
||||||
|
return static_cast<int>(value);
|
||||||
|
} catch (...) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void ArgError(const char* value, const char* name) {
|
||||||
|
std::cerr << "error: invalid " << name << " value '" << value
|
||||||
|
<< "'. Expected a positive whole number.\n"
|
||||||
|
<< "\nRun 'Eleanor datagen --help' for usage.\n";
|
||||||
|
}
|
||||||
|
|
||||||
|
static void PrintUsage() {
|
||||||
|
std::cout << "Eleanor " << EleanorVersion << " - chess engine" << std::endl;
|
||||||
|
std::cout << std::endl;
|
||||||
|
std::cout << "Usage:" << std::endl;
|
||||||
|
std::cout << " Eleanor" << std::endl;
|
||||||
|
std::cout << " Eleanor bench" << std::endl;
|
||||||
|
std::cout << " Eleanor datagen [positions] [threads] [username]" << std::endl;
|
||||||
|
std::cout << " Eleanor datagen [options]" << std::endl;
|
||||||
|
std::cout << " Eleanor --help" << std::endl;
|
||||||
|
std::cout << " Eleanor --version" << std::endl;
|
||||||
|
std::cout << std::endl;
|
||||||
|
std::cout << "Commands:" << std::endl;
|
||||||
|
std::cout << " bench Run benchmark" << std::endl;
|
||||||
|
std::cout << " datagen Generate training data" << std::endl;
|
||||||
|
std::cout << " help Show this help" << std::endl;
|
||||||
|
std::cout << " version Show version" << std::endl;
|
||||||
|
std::cout << std::endl;
|
||||||
|
std::cout << "Options:" << std::endl;
|
||||||
|
std::cout << " -h, --help Show this help" << std::endl;
|
||||||
|
std::cout << " -v, --version Show version" << std::endl;
|
||||||
|
std::cout << " --bench Same as bench" << std::endl;
|
||||||
|
std::cout << " --datagen Same as datagen" << std::endl;
|
||||||
|
std::cout << " -p, --positions N Target size in thousands for datagen" << std::endl;
|
||||||
|
std::cout << " -t, --threads N Threads for datagen or UCI mode" << std::endl;
|
||||||
|
std::cout << " -u, --username NAME Online mode username for datagen" << std::endl;
|
||||||
|
std::cout << " --hash N Hash size in MB for UCI mode" << std::endl;
|
||||||
|
std::cout << " --evalfile PATH NNUE file to load for UCI mode" << std::endl;
|
||||||
|
std::cout << std::endl;
|
||||||
|
std::cout << "Datagen examples:" << std::endl;
|
||||||
|
std::cout << " Eleanor datagen 1000 22" << std::endl;
|
||||||
|
std::cout << " Eleanor datagen --positions 1000 --threads 22" << std::endl;
|
||||||
|
std::cout << " Eleanor datagen 1000 22 myuser" << std::endl;
|
||||||
|
std::cout << std::endl;
|
||||||
|
std::cout << "UCI go:" << std::endl;
|
||||||
|
std::cout << " go depth N" << std::endl;
|
||||||
|
std::cout << " go mate N" << std::endl;
|
||||||
|
std::cout << " go nodes N" << std::endl;
|
||||||
|
std::cout << " go movetime N" << std::endl;
|
||||||
|
std::cout << " go infinite" << std::endl;
|
||||||
|
std::cout << " go searchmoves MOVE ..." << std::endl;
|
||||||
|
std::cout << " go wtime N btime N winc N binc N movestogo N" << std::endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void PrintVersion() {
|
||||||
|
std::cout << "Eleanor " << EleanorVersion << std::endl;
|
||||||
|
}
|
||||||
|
|
||||||
int main(int argc, char* argv[]) {
|
int main(int argc, char* argv[]) {
|
||||||
auto loadDefaultNet = [&]([[maybe_unused]] bool warnMSVC = false) {
|
auto loadDefaultNet = [&]([[maybe_unused]] bool warnMSVC = false) {
|
||||||
#if defined(_MSC_VER) && !defined(__clang__)
|
#if defined(_MSC_VER) && !defined(__clang__)
|
||||||
@@ -39,36 +115,238 @@ int main(int argc, char* argv[]) {
|
|||||||
NNUE::net = *reinterpret_cast<const NNUE::Network*>(gEVALData);
|
NNUE::net = *reinterpret_cast<const NNUE::Network*>(gEVALData);
|
||||||
#endif
|
#endif
|
||||||
};
|
};
|
||||||
|
|
||||||
loadDefaultNet(true);
|
loadDefaultNet(true);
|
||||||
|
MOVEGEN::initLeaperAttacks();
|
||||||
|
MOVEGEN::initSliderAttacks();
|
||||||
|
|
||||||
MOVEGEN::initLeaperAttacks();
|
|
||||||
MOVEGEN::initSliderAttacks();
|
|
||||||
UTILS::InitZobrist();
|
UTILS::InitZobrist();
|
||||||
SEARCH::InitLMRTable();
|
#ifdef TUNING
|
||||||
|
SEARCH::RefreshTunableCaches();
|
||||||
Board board;
|
#else
|
||||||
|
SEARCH::InitLMRTable();
|
||||||
if (argc > 1) {
|
#endif
|
||||||
if (std::string(argv[1]) == "bench") {
|
Board board;
|
||||||
RunBenchmark();
|
if (argc <= 1) {
|
||||||
} else if (std::string(argv[1]) == "datagen") {
|
|
||||||
int positions = 1;
|
|
||||||
int threads = 1;
|
|
||||||
if (argc > 2) {
|
|
||||||
positions = std::stoi(argv[2]) * 1000;
|
|
||||||
|
|
||||||
if (argc > 3) {
|
|
||||||
threads = std::stoi(argv[3]);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
DATAGEN::Run(positions, threads);
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
UCILoop(board);
|
UCILoop(board);
|
||||||
|
return 0;
|
||||||
}
|
}
|
||||||
|
std::string first = argv[1];
|
||||||
return 0;
|
if (first == "--help" || first == "-h" || first == "help") {
|
||||||
|
PrintUsage();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (first == "--version" || first == "-v" || first == "version") {
|
||||||
|
PrintVersion();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (first == "bench" || first == "--bench") {
|
||||||
|
if (argc > 2) {
|
||||||
|
std::string second = argv[2];
|
||||||
|
if (second == "--help" || second == "-h" || second == "help") {
|
||||||
|
PrintUsage();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
RunBenchmark();
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (first == "datagen" || first == "--datagen") {
|
||||||
|
int positions = 0;
|
||||||
|
int datagenThreads = 1;
|
||||||
|
std::string username = "";
|
||||||
|
bool hasPositions = false;
|
||||||
|
bool hasThreads = false;
|
||||||
|
std::vector<std::string> positional;
|
||||||
|
for (int i = 2; i < argc; i++) {
|
||||||
|
std::string arg = argv[i];
|
||||||
|
if (arg == "--help" || arg == "-h" || arg == "help") {
|
||||||
|
DATAGEN::PrintUsage();
|
||||||
|
return 0;
|
||||||
|
} else if (arg == "--positions" || arg == "-p") {
|
||||||
|
if (i + 1 >= argc) {
|
||||||
|
std::cerr << "error: missing value for '" << arg << "'." << std::endl;
|
||||||
|
std::cerr << std::endl;
|
||||||
|
std::cerr << "Run 'Eleanor datagen --help' for usage." << std::endl;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
positions = ParsePositiveInt(argv[++i]);
|
||||||
|
if (positions == 0) {
|
||||||
|
ArgError(argv[i], "positions");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
positions *= 1000;
|
||||||
|
hasPositions = true;
|
||||||
|
} else if (arg.rfind("--positions=", 0) == 0) {
|
||||||
|
positions = ParsePositiveInt(arg.substr(12).c_str());
|
||||||
|
if (positions == 0) {
|
||||||
|
ArgError(arg.substr(12).c_str(), "positions");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
positions *= 1000;
|
||||||
|
hasPositions = true;
|
||||||
|
} else if (arg == "--threads" || arg == "-t") {
|
||||||
|
if (i + 1 >= argc) {
|
||||||
|
std::cerr << "error: missing value for '" << arg << "'." << std::endl;
|
||||||
|
std::cerr << std::endl;
|
||||||
|
std::cerr << "Run 'Eleanor datagen --help' for usage." << std::endl;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
datagenThreads = ParsePositiveInt(argv[++i]);
|
||||||
|
if (datagenThreads == 0) {
|
||||||
|
ArgError(argv[i], "threads");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
hasThreads = true;
|
||||||
|
} else if (arg.rfind("--threads=", 0) == 0) {
|
||||||
|
datagenThreads = ParsePositiveInt(arg.substr(10).c_str());
|
||||||
|
if (datagenThreads == 0) {
|
||||||
|
ArgError(arg.substr(10).c_str(), "threads");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
hasThreads = true;
|
||||||
|
} else if (arg == "--username" || arg == "-u") {
|
||||||
|
if (i + 1 >= argc) {
|
||||||
|
std::cerr << "error: missing value for '" << arg << "'." << std::endl;
|
||||||
|
std::cerr << std::endl;
|
||||||
|
std::cerr << "Run 'Eleanor datagen --help' for usage." << std::endl;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
username = argv[++i];
|
||||||
|
} else if (arg.rfind("--username=", 0) == 0) {
|
||||||
|
username = arg.substr(11);
|
||||||
|
} else if (!arg.empty() && arg[0] == '-') {
|
||||||
|
std::cerr << "error: unknown option '" << arg << "'." << std::endl;
|
||||||
|
std::cerr << std::endl;
|
||||||
|
std::cerr << "Run 'Eleanor datagen --help' for usage." << std::endl;
|
||||||
|
return 1;
|
||||||
|
} else {
|
||||||
|
positional.push_back(arg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
size_t posIndex = 0;
|
||||||
|
if (!hasPositions && posIndex < positional.size()) {
|
||||||
|
positions = ParsePositiveInt(positional[posIndex].c_str());
|
||||||
|
if (positions == 0) {
|
||||||
|
ArgError(positional[posIndex].c_str(), "positions");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
positions *= 1000;
|
||||||
|
hasPositions = true;
|
||||||
|
posIndex++;
|
||||||
|
}
|
||||||
|
if (!hasThreads && posIndex < positional.size()) {
|
||||||
|
datagenThreads = ParsePositiveInt(positional[posIndex].c_str());
|
||||||
|
if (datagenThreads == 0) {
|
||||||
|
ArgError(positional[posIndex].c_str(), "threads");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
hasThreads = true;
|
||||||
|
posIndex++;
|
||||||
|
}
|
||||||
|
if (username.empty() && posIndex < positional.size()) {
|
||||||
|
username = positional[posIndex];
|
||||||
|
posIndex++;
|
||||||
|
}
|
||||||
|
if (posIndex < positional.size()) {
|
||||||
|
std::cerr << "error: unexpected argument '" << positional[posIndex] << "'." << std::endl;
|
||||||
|
std::cerr << std::endl;
|
||||||
|
std::cerr << "Run 'Eleanor datagen --help' for usage." << std::endl;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!hasPositions)
|
||||||
|
positions = 1000;
|
||||||
|
if (!hasThreads) {
|
||||||
|
std::cerr << "error: threads must be at least 2." << std::endl;
|
||||||
|
std::cerr << std::endl;
|
||||||
|
std::cerr << "Run 'Eleanor datagen --help' for usage." << std::endl;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (datagenThreads < 2) {
|
||||||
|
std::cerr << "error: threads must be at least 2 (got " << datagenThreads << "). The main thread only renders the progress screen, so " << datagenThreads << " leaves no worker to generate." << std::endl;
|
||||||
|
std::cerr << std::endl;
|
||||||
|
std::cerr << "Run 'Eleanor datagen --help' for usage." << std::endl;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
if (!username.empty()) {
|
||||||
|
DATAGEN::RunOnline(username, positions, datagenThreads);
|
||||||
|
} else {
|
||||||
|
DATAGEN::Run(positions, datagenThreads);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
if (!first.empty() && first[0] == '-') {
|
||||||
|
for (int i = 1; i < argc; i++) {
|
||||||
|
std::string arg = argv[i];
|
||||||
|
if (arg == "--help" || arg == "-h" || arg == "help") {
|
||||||
|
PrintUsage();
|
||||||
|
return 0;
|
||||||
|
} else if (arg == "--version" || arg == "-v" || arg == "version") {
|
||||||
|
PrintVersion();
|
||||||
|
return 0;
|
||||||
|
} else if (arg == "--threads" || arg == "-t") {
|
||||||
|
if (i + 1 >= argc) {
|
||||||
|
std::cerr << "error: missing value for '" << arg << "'." << std::endl;
|
||||||
|
std::cerr << std::endl;
|
||||||
|
std::cerr << "Run 'Eleanor --help' for usage." << std::endl;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
int value = ParsePositiveInt(argv[++i]);
|
||||||
|
if (value < 1 || value > 512) {
|
||||||
|
ArgError(argv[i], "threads");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
threads = value;
|
||||||
|
} else if (arg.rfind("--threads=", 0) == 0) {
|
||||||
|
int value = ParsePositiveInt(arg.substr(10).c_str());
|
||||||
|
if (value < 1 || value > 512) {
|
||||||
|
ArgError(arg.substr(10).c_str(), "threads");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
threads = value;
|
||||||
|
} else if (arg == "--hash") {
|
||||||
|
if (i + 1 >= argc) {
|
||||||
|
std::cerr << "error: missing value for '" << arg << "'." << std::endl;
|
||||||
|
std::cerr << std::endl;
|
||||||
|
std::cerr << "Run 'Eleanor --help' for usage." << std::endl;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
int value = ParsePositiveInt(argv[++i]);
|
||||||
|
if (value < 1 || value > 1024) {
|
||||||
|
ArgError(argv[i], "hash");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
U64 hashSize = (U64(value) * 1000000ULL) / sizeof(TTBucket);
|
||||||
|
SharedTT.Resize(hashSize);
|
||||||
|
} else if (arg.rfind("--hash=", 0) == 0) {
|
||||||
|
int value = ParsePositiveInt(arg.substr(7).c_str());
|
||||||
|
if (value < 1 || value > 1024) {
|
||||||
|
ArgError(arg.substr(7).c_str(), "hash");
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
U64 hashSize = (U64(value) * 1000000ULL) / sizeof(TTBucket);
|
||||||
|
SharedTT.Resize(hashSize);
|
||||||
|
} else if (arg == "--evalfile") {
|
||||||
|
if (i + 1 >= argc) {
|
||||||
|
std::cerr << "error: missing value for '" << arg << "'." << std::endl;
|
||||||
|
std::cerr << std::endl;
|
||||||
|
std::cerr << "Run 'Eleanor --help' for usage." << std::endl;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
NNUE::net.Load(argv[++i]);
|
||||||
|
} else if (arg.rfind("--evalfile=", 0) == 0) {
|
||||||
|
NNUE::net.Load(arg.substr(11));
|
||||||
|
} else {
|
||||||
|
std::cerr << "error: unknown option '" << arg << "'." << std::endl;
|
||||||
|
std::cerr << std::endl;
|
||||||
|
std::cerr << "Run 'Eleanor --help' for usage." << std::endl;
|
||||||
|
return 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
UCILoop(board);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
std::cerr << "error: unknown command '" << first << "'." << std::endl;
|
||||||
|
std::cerr << std::endl;
|
||||||
|
std::cerr << "Run 'Eleanor --help' for usage." << std::endl;
|
||||||
|
return 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,6 +64,10 @@ public:
|
|||||||
return (GetFlags() >= knightPromotion);
|
return (GetFlags() >= knightPromotion);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
bool IsCastle() {
|
||||||
|
return (GetFlags() == kingCastle || GetFlags() == queenCastle);
|
||||||
|
}
|
||||||
|
|
||||||
void PrintMove() {
|
void PrintMove() {
|
||||||
std::cout << squareCoords[MoveFrom()] << squareCoords[MoveTo()];
|
std::cout << squareCoords[MoveFrom()] << squareCoords[MoveTo()];
|
||||||
|
|
||||||
@@ -80,6 +84,25 @@ public:
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::string GetMoveString() {
|
||||||
|
std::string result = squareCoords[MoveFrom()];
|
||||||
|
result += squareCoords[MoveTo()];
|
||||||
|
|
||||||
|
int flags = GetFlags();
|
||||||
|
|
||||||
|
if (flags == knightPromotion || flags == knightPromoCapture) {
|
||||||
|
result += 'n';
|
||||||
|
} else if (flags == bishopPromotion || flags == bishopPromoCapture) {
|
||||||
|
result += 'b';
|
||||||
|
} else if (flags == rookPromotion || flags == rookPromoCapture) {
|
||||||
|
result += 'r';
|
||||||
|
} else if (flags == queenPromotion || flags == queenPromoCapture) {
|
||||||
|
result += 'q';
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
uint16_t ConvertToViriMoveFormat() {
|
uint16_t ConvertToViriMoveFormat() {
|
||||||
uint16_t viriMove = 0;
|
uint16_t viriMove = 0;
|
||||||
int flags = GetFlags();
|
int flags = GetFlags();
|
||||||
@@ -127,6 +150,14 @@ public:
|
|||||||
return viriMove;
|
return viriMove;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
int GetPromoPiece() {
|
||||||
|
if (IsCapture()) {
|
||||||
|
return GetFlags() - 9;
|
||||||
|
} else {
|
||||||
|
return GetFlags() - 5;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
operator uint16_t() {
|
operator uint16_t() {
|
||||||
return m_move;
|
return m_move;
|
||||||
}
|
}
|
||||||
|
|||||||
+4
-3
@@ -4,8 +4,9 @@
|
|||||||
#include "board.h"
|
#include "board.h"
|
||||||
|
|
||||||
enum MovegenMode {
|
enum MovegenMode {
|
||||||
All,
|
Quiet,
|
||||||
Noisy
|
Noisy,
|
||||||
|
All
|
||||||
};
|
};
|
||||||
|
|
||||||
namespace MOVEGEN {
|
namespace MOVEGEN {
|
||||||
@@ -37,7 +38,7 @@ template <MovegenMode mode>
|
|||||||
void GenKingMoves(Board &board);
|
void GenKingMoves(Board &board);
|
||||||
|
|
||||||
template <MovegenMode mode>
|
template <MovegenMode mode>
|
||||||
void GenerateMoves(Board &board);
|
void GenerateMoves(Board &board, bool clear, bool recalcThreats = true);
|
||||||
|
|
||||||
void GenThreatMaps(Board &board);
|
void GenThreatMaps(Board &board);
|
||||||
|
|
||||||
|
|||||||
+82
-142
@@ -11,8 +11,8 @@ void GenPawnMoves(Board &board) {
|
|||||||
|
|
||||||
Bitboard lastRank = board.sideToMove ? ranks[r_1] : ranks[r_8];
|
Bitboard lastRank = board.sideToMove ? ranks[r_1] : ranks[r_8];
|
||||||
|
|
||||||
if constexpr (mode == Noisy) {
|
if constexpr (mode == Noisy || mode == All) {
|
||||||
pushes &= lastRank;
|
Bitboard noisyPushes = pushes & lastRank;
|
||||||
|
|
||||||
if (board.enPassantTarget != noEPTarget) {
|
if (board.enPassantTarget != noEPTarget) {
|
||||||
if (attacks.IsSet(board.enPassantTarget)) {
|
if (attacks.IsSet(board.enPassantTarget)) {
|
||||||
@@ -35,8 +35,8 @@ void GenPawnMoves(Board &board) {
|
|||||||
captures.PopBit(targetSquare);
|
captures.PopBit(targetSquare);
|
||||||
}
|
}
|
||||||
|
|
||||||
while (pushes) {
|
while (noisyPushes) {
|
||||||
int pushSquare = pushes.getLS1BIndex();
|
int pushSquare = noisyPushes.getLS1BIndex();
|
||||||
|
|
||||||
// Only promotions because NOISY
|
// Only promotions because NOISY
|
||||||
board.AddMove(Move(square, pushSquare, knightPromotion));
|
board.AddMove(Move(square, pushSquare, knightPromotion));
|
||||||
@@ -44,29 +44,17 @@ void GenPawnMoves(Board &board) {
|
|||||||
board.AddMove(Move(square, pushSquare, rookPromotion));
|
board.AddMove(Move(square, pushSquare, rookPromotion));
|
||||||
board.AddMove(Move(square, pushSquare, queenPromotion));
|
board.AddMove(Move(square, pushSquare, queenPromotion));
|
||||||
|
|
||||||
pushes.PopBit(pushSquare);
|
noisyPushes.PopBit(pushSquare);
|
||||||
}
|
}
|
||||||
|
|
||||||
pawns.PopBit(square);
|
pawns.PopBit(square);
|
||||||
continue;
|
}
|
||||||
} else {
|
|
||||||
// Checking for en passant
|
|
||||||
if (board.enPassantTarget != noEPTarget) {
|
|
||||||
if (attacks.IsSet(board.enPassantTarget)) {
|
|
||||||
board.AddMove(Move(square, board.enPassantTarget, epCapture));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
if constexpr (mode == Quiet || mode == All) {
|
||||||
while (pushes) {
|
while (pushes) {
|
||||||
int pushSquare = pushes.getLS1BIndex();
|
int pushSquare = pushes.getLS1BIndex();
|
||||||
|
|
||||||
// Checking for promotion
|
if (!lastRank.IsSet(pushSquare)) {
|
||||||
if (lastRank.IsSet(pushSquare)) {
|
|
||||||
board.AddMove(Move(square, pushSquare, knightPromotion));
|
|
||||||
board.AddMove(Move(square, pushSquare, bishopPromotion));
|
|
||||||
board.AddMove(Move(square, pushSquare, rookPromotion));
|
|
||||||
board.AddMove(Move(square, pushSquare, queenPromotion));
|
|
||||||
} else {
|
|
||||||
if (std::abs(square - pushSquare) == 16) {
|
if (std::abs(square - pushSquare) == 16) {
|
||||||
board.AddMove(Move(square, pushSquare, doublePawnPush));
|
board.AddMove(Move(square, pushSquare, doublePawnPush));
|
||||||
} else {
|
} else {
|
||||||
@@ -76,22 +64,6 @@ void GenPawnMoves(Board &board) {
|
|||||||
|
|
||||||
pushes.PopBit(pushSquare);
|
pushes.PopBit(pushSquare);
|
||||||
}
|
}
|
||||||
|
|
||||||
while (captures) {
|
|
||||||
int targetSquare = captures.getLS1BIndex();
|
|
||||||
|
|
||||||
// Checking for promotion
|
|
||||||
if (lastRank.IsSet(targetSquare)) {
|
|
||||||
board.AddMove(Move(square, targetSquare, knightPromoCapture));
|
|
||||||
board.AddMove(Move(square, targetSquare, bishopPromoCapture));
|
|
||||||
board.AddMove(Move(square, targetSquare, rookPromoCapture));
|
|
||||||
board.AddMove(Move(square, targetSquare, queenPromoCapture));
|
|
||||||
} else {
|
|
||||||
board.AddMove(Move(square, targetSquare, capture));
|
|
||||||
}
|
|
||||||
|
|
||||||
captures.PopBit(targetSquare);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pawns.PopBit(square);
|
pawns.PopBit(square);
|
||||||
@@ -108,7 +80,7 @@ void GenKnightMoves(Board &board) {
|
|||||||
Bitboard captures = moves & board.colors[!board.sideToMove];
|
Bitboard captures = moves & board.colors[!board.sideToMove];
|
||||||
moves &= ~captures;
|
moves &= ~captures;
|
||||||
|
|
||||||
if constexpr (mode == Noisy) {
|
if constexpr (mode == Noisy || mode == All) {
|
||||||
while (captures) {
|
while (captures) {
|
||||||
int targetSquare = captures.getLS1BIndex();
|
int targetSquare = captures.getLS1BIndex();
|
||||||
|
|
||||||
@@ -118,25 +90,18 @@ void GenKnightMoves(Board &board) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
knights.PopBit(square);
|
knights.PopBit(square);
|
||||||
continue;
|
|
||||||
} else {
|
|
||||||
while (moves) {
|
|
||||||
int targetSquare = moves.getLS1BIndex();
|
|
||||||
|
|
||||||
board.AddMove(Move(square, targetSquare, quiet));
|
|
||||||
|
|
||||||
moves.PopBit(targetSquare);
|
|
||||||
}
|
|
||||||
|
|
||||||
while (captures) {
|
|
||||||
int targetSquare = captures.getLS1BIndex();
|
|
||||||
|
|
||||||
board.AddMove(Move(square, targetSquare, capture));
|
|
||||||
|
|
||||||
captures.PopBit(targetSquare);
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if constexpr (mode == Quiet || mode == All) {
|
||||||
|
while (moves) {
|
||||||
|
int targetSquare = moves.getLS1BIndex();
|
||||||
|
|
||||||
|
board.AddMove(Move(square, targetSquare, quiet));
|
||||||
|
|
||||||
|
moves.PopBit(targetSquare);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
knights.PopBit(square);
|
knights.PopBit(square);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -151,7 +116,7 @@ void GenRookMoves(Board &board) {
|
|||||||
Bitboard captures = moves & board.colors[!board.sideToMove];
|
Bitboard captures = moves & board.colors[!board.sideToMove];
|
||||||
moves &= ~captures;
|
moves &= ~captures;
|
||||||
|
|
||||||
if constexpr (mode == Noisy) {
|
if constexpr (mode == Noisy || mode == All) {
|
||||||
while (captures) {
|
while (captures) {
|
||||||
int targetSquare = captures.getLS1BIndex();
|
int targetSquare = captures.getLS1BIndex();
|
||||||
|
|
||||||
@@ -161,24 +126,17 @@ void GenRookMoves(Board &board) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
rooks.PopBit(square);
|
rooks.PopBit(square);
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
while (moves) {
|
if constexpr (mode == Quiet || mode == All) {
|
||||||
int targetSquare = moves.getLS1BIndex();
|
while (moves) {
|
||||||
|
int targetSquare = moves.getLS1BIndex();
|
||||||
|
|
||||||
board.AddMove(Move(square, targetSquare, quiet));
|
board.AddMove(Move(square, targetSquare, quiet));
|
||||||
|
|
||||||
moves.PopBit(targetSquare);
|
moves.PopBit(targetSquare);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
while (captures) {
|
|
||||||
int targetSquare = captures.getLS1BIndex();
|
|
||||||
|
|
||||||
board.AddMove(Move(square, targetSquare, capture));
|
|
||||||
|
|
||||||
captures.PopBit(targetSquare);
|
|
||||||
}
|
|
||||||
|
|
||||||
rooks.PopBit(square);
|
rooks.PopBit(square);
|
||||||
}
|
}
|
||||||
@@ -194,7 +152,7 @@ void GenBishopMoves(Board &board) {
|
|||||||
Bitboard captures = moves & board.colors[!board.sideToMove];
|
Bitboard captures = moves & board.colors[!board.sideToMove];
|
||||||
moves &= ~captures;
|
moves &= ~captures;
|
||||||
|
|
||||||
if constexpr (mode == Noisy) {
|
if constexpr (mode == Noisy || mode == All) {
|
||||||
while (captures) {
|
while (captures) {
|
||||||
int targetSquare = captures.getLS1BIndex();
|
int targetSquare = captures.getLS1BIndex();
|
||||||
|
|
||||||
@@ -204,24 +162,17 @@ void GenBishopMoves(Board &board) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bishops.PopBit(square);
|
bishops.PopBit(square);
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
while (moves) {
|
if constexpr (mode == Quiet || mode == All) {
|
||||||
int targetSquare = moves.getLS1BIndex();
|
while (moves) {
|
||||||
|
int targetSquare = moves.getLS1BIndex();
|
||||||
|
|
||||||
board.AddMove(Move(square, targetSquare, quiet));
|
board.AddMove(Move(square, targetSquare, quiet));
|
||||||
|
|
||||||
moves.PopBit(targetSquare);
|
moves.PopBit(targetSquare);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
while (captures) {
|
|
||||||
int targetSquare = captures.getLS1BIndex();
|
|
||||||
|
|
||||||
board.AddMove(Move(square, targetSquare, capture));
|
|
||||||
|
|
||||||
captures.PopBit(targetSquare);
|
|
||||||
}
|
|
||||||
|
|
||||||
bishops.PopBit(square);
|
bishops.PopBit(square);
|
||||||
}
|
}
|
||||||
@@ -237,7 +188,7 @@ void GenQueenMoves(Board &board) {
|
|||||||
Bitboard captures = moves & board.colors[!board.sideToMove];
|
Bitboard captures = moves & board.colors[!board.sideToMove];
|
||||||
moves &= ~captures;
|
moves &= ~captures;
|
||||||
|
|
||||||
if constexpr (mode == Noisy) {
|
if constexpr (mode == Noisy || mode == All) {
|
||||||
while (captures) {
|
while (captures) {
|
||||||
int targetSquare = captures.getLS1BIndex();
|
int targetSquare = captures.getLS1BIndex();
|
||||||
|
|
||||||
@@ -247,24 +198,17 @@ void GenQueenMoves(Board &board) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
queens.PopBit(square);
|
queens.PopBit(square);
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
while (moves) {
|
if constexpr (mode == Quiet || mode == All) {
|
||||||
int targetSquare = moves.getLS1BIndex();
|
while (moves) {
|
||||||
|
int targetSquare = moves.getLS1BIndex();
|
||||||
|
|
||||||
board.AddMove(Move(square, targetSquare, quiet));
|
board.AddMove(Move(square, targetSquare, quiet));
|
||||||
|
|
||||||
moves.PopBit(targetSquare);
|
moves.PopBit(targetSquare);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
while (captures) {
|
|
||||||
int targetSquare = captures.getLS1BIndex();
|
|
||||||
|
|
||||||
board.AddMove(Move(square, targetSquare, capture));
|
|
||||||
|
|
||||||
captures.PopBit(targetSquare);
|
|
||||||
}
|
|
||||||
|
|
||||||
queens.PopBit(square);
|
queens.PopBit(square);
|
||||||
}
|
}
|
||||||
@@ -277,7 +221,7 @@ void GenKingMoves(Board &board) {
|
|||||||
Bitboard captures = moves & board.colors[!board.sideToMove];
|
Bitboard captures = moves & board.colors[!board.sideToMove];
|
||||||
moves &= ~board.colors[!board.sideToMove];
|
moves &= ~board.colors[!board.sideToMove];
|
||||||
|
|
||||||
if constexpr (mode == Noisy) {
|
if constexpr (mode == Noisy || mode == All) {
|
||||||
while (captures) {
|
while (captures) {
|
||||||
int square = captures.getLS1BIndex();
|
int square = captures.getLS1BIndex();
|
||||||
|
|
||||||
@@ -286,58 +230,54 @@ void GenKingMoves(Board &board) {
|
|||||||
|
|
||||||
captures.PopBit(square);
|
captures.PopBit(square);
|
||||||
}
|
}
|
||||||
return;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
while (moves) {
|
if constexpr (mode == Quiet || mode == All) {
|
||||||
int square = moves.getLS1BIndex();
|
while (moves) {
|
||||||
|
int square = moves.getLS1BIndex();
|
||||||
|
|
||||||
board.AddMove(Move(kingSquare, square, quiet));
|
board.AddMove(Move(kingSquare, square, quiet));
|
||||||
|
|
||||||
moves.PopBit(square);
|
|
||||||
}
|
|
||||||
|
|
||||||
while (captures) {
|
|
||||||
int square = captures.getLS1BIndex();
|
|
||||||
|
|
||||||
Move move(kingSquare, square, capture);
|
|
||||||
board.AddMove(move);
|
|
||||||
|
|
||||||
captures.PopBit(square);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Generating castles
|
|
||||||
int kingRight = board.sideToMove ? blackKingRight : whiteKingRight;
|
|
||||||
int queenRight = board.sideToMove ? blackQueenRight : whiteQueenRight;
|
|
||||||
|
|
||||||
if (board.castlingRights & queenRight) {
|
|
||||||
U64 QueenSide = board.sideToMove ? 0x1f00000000000000 : 0x1f;
|
|
||||||
U64 mask = board.sideToMove ? 0x1c00000000000000 : 0x1c;
|
|
||||||
int targetSquare = board.sideToMove ? c8 : c1;
|
|
||||||
if ((Bitboard(QueenSide) & board.occupied).PopCount() == 2
|
|
||||||
&& !(mask & board.colorThreats[!board.sideToMove])) {
|
|
||||||
board.AddMove(Move(kingSquare, targetSquare, queenCastle));
|
|
||||||
|
|
||||||
|
moves.PopBit(square);
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
if (board.castlingRights & kingRight) {
|
// Generating castles
|
||||||
U64 KingSide = board.sideToMove ? 0xf000000000000000 : 0xf0;
|
int kingRight = board.sideToMove ? blackKingRight : whiteKingRight;
|
||||||
U64 mask = board.sideToMove ? 0x7000000000000000 : 0x70;
|
int queenRight = board.sideToMove ? blackQueenRight : whiteQueenRight;
|
||||||
int targetSquare = board.sideToMove ? g8 : g1;
|
|
||||||
if ((Bitboard(KingSide) & board.occupied).PopCount() == 2
|
if (board.castlingRights & queenRight) {
|
||||||
&& !(mask & board.colorThreats[!board.sideToMove])) {
|
U64 QueenSide = board.sideToMove ? 0x1f00000000000000 : 0x1f;
|
||||||
board.AddMove(Move(kingSquare, targetSquare, kingCastle));
|
U64 mask = board.sideToMove ? 0x1c00000000000000 : 0x1c;
|
||||||
|
int targetSquare = board.sideToMove ? c8 : c1;
|
||||||
|
if ((Bitboard(QueenSide) & board.occupied).PopCount() == 2
|
||||||
|
&& !(mask & board.colorThreats[!board.sideToMove])) {
|
||||||
|
board.AddMove(Move(kingSquare, targetSquare, queenCastle));
|
||||||
|
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (board.castlingRights & kingRight) {
|
||||||
|
U64 KingSide = board.sideToMove ? 0xf000000000000000 : 0xf0;
|
||||||
|
U64 mask = board.sideToMove ? 0x7000000000000000 : 0x70;
|
||||||
|
int targetSquare = board.sideToMove ? g8 : g1;
|
||||||
|
if ((Bitboard(KingSide) & board.occupied).PopCount() == 2
|
||||||
|
&& !(mask & board.colorThreats[!board.sideToMove])) {
|
||||||
|
board.AddMove(Move(kingSquare, targetSquare, kingCastle));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
template <MovegenMode mode>
|
template <MovegenMode mode>
|
||||||
void GenerateMoves(Board &board) {
|
void GenerateMoves(Board &board, bool clear, bool recalcThreats) {
|
||||||
board.ResetMoves();
|
if (clear) {
|
||||||
board.pieceThreats = std::array<Bitboard, 6>();
|
board.ResetMoves();
|
||||||
board.colorThreats = std::array<Bitboard, 2>();
|
}
|
||||||
GenThreatMaps(board);
|
|
||||||
|
if (recalcThreats) {
|
||||||
|
GenThreatMaps(board);
|
||||||
|
}
|
||||||
|
|
||||||
GenPawnMoves<mode>(board);
|
GenPawnMoves<mode>(board);
|
||||||
GenKnightMoves<mode>(board);
|
GenKnightMoves<mode>(board);
|
||||||
|
|||||||
@@ -0,0 +1,209 @@
|
|||||||
|
#include "movepicker.h"
|
||||||
|
#include "search.h"
|
||||||
|
#include "tunables.h"
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace SEARCH {
|
||||||
|
|
||||||
|
template <MovegenMode mode>
|
||||||
|
MovePicker<mode>::MovePicker(Board &b, SearchContext *c, int p, Move tt)
|
||||||
|
: board(b), ctx(c), ply(p), ttMove(tt), killerMove(), stage(PickStage::TTMove) {
|
||||||
|
|
||||||
|
if (!ttMove || !board.IsPseudoLegal(ttMove)) {
|
||||||
|
ttMove = Move();
|
||||||
|
}
|
||||||
|
|
||||||
|
if constexpr (mode == Noisy) {
|
||||||
|
if (ttMove && !(ttMove.IsCapture() || ttMove.IsPromo())) {
|
||||||
|
ttMove = Move();
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
Move killer = ctx->killerMoves[ply];
|
||||||
|
|
||||||
|
if (killer && killer != ttMove && !killer.IsCapture() && !killer.IsPromo()
|
||||||
|
&& board.IsPseudoLegal(killer)) {
|
||||||
|
killerMove = killer;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template <MovegenMode mode>
|
||||||
|
int MovePicker<mode>::ScoreNoisyMove(Move move) {
|
||||||
|
int score = MoveEstimatedValue(board, move) * noisyScoreScale;
|
||||||
|
|
||||||
|
if (move.IsCapture()) {
|
||||||
|
int attackerType = board.GetPieceType(move.MoveFrom());
|
||||||
|
int targetType = (move.GetFlags() == epCapture) ? Pawn : board.GetPieceType(move.MoveTo());
|
||||||
|
|
||||||
|
score += ctx->capthist[board.sideToMove][attackerType][targetType][move.MoveTo()];
|
||||||
|
}
|
||||||
|
|
||||||
|
return score;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <MovegenMode mode>
|
||||||
|
int MovePicker<mode>::ScoreQuietMove(Move move) {
|
||||||
|
bool sourceThreatened = board.IsSquareThreatened(board.sideToMove, move.MoveFrom());
|
||||||
|
bool targetThreatened = board.IsSquareThreatened(board.sideToMove, move.MoveTo());
|
||||||
|
|
||||||
|
int score = ctx->history[board.sideToMove][move.MoveFrom()][move.MoveTo()][sourceThreatened][targetThreatened];
|
||||||
|
|
||||||
|
if (ply > 0) score += ctx->conthist.GetNPly(board, move, ctx, ply, 1);
|
||||||
|
if (ply > 1) score += ctx->conthist.GetNPly(board, move, ctx, ply, 2);
|
||||||
|
|
||||||
|
return score;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <MovegenMode mode>
|
||||||
|
void MovePicker<mode>::ScoreNoisyRange() {
|
||||||
|
noisyStart = 0;
|
||||||
|
|
||||||
|
MOVEGEN::GenerateMoves<Noisy>(board, true, false);
|
||||||
|
|
||||||
|
int rawEnd = board.currentMoveIndex;
|
||||||
|
int write = noisyStart;
|
||||||
|
|
||||||
|
for (int read = noisyStart; read < rawEnd; read++) {
|
||||||
|
Move m = board.moveList[read];
|
||||||
|
if (m == ttMove || m == killerMove) continue;
|
||||||
|
|
||||||
|
board.moveList[write] = m;
|
||||||
|
scores[write] = ScoreNoisyMove(m);
|
||||||
|
write++;
|
||||||
|
}
|
||||||
|
|
||||||
|
noisyEnd = write;
|
||||||
|
board.currentMoveIndex = noisyEnd;
|
||||||
|
|
||||||
|
int goodWrite = noisyStart;
|
||||||
|
|
||||||
|
for (int i = noisyStart; i < noisyEnd; i++) {
|
||||||
|
Move m = board.moveList[i];
|
||||||
|
|
||||||
|
if (SEE(board, m, seeOrderingThreshold)) {
|
||||||
|
if (i != goodWrite) {
|
||||||
|
std::swap(board.moveList[i], board.moveList[goodWrite]);
|
||||||
|
std::swap(scores[i], scores[goodWrite]);
|
||||||
|
}
|
||||||
|
goodWrite++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
goodNoisyEnd = goodWrite;
|
||||||
|
noisyCursor = noisyStart;
|
||||||
|
badNoisyCursor = goodNoisyEnd;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <MovegenMode mode>
|
||||||
|
void MovePicker<mode>::ScoreQuietRange() {
|
||||||
|
quietStart = noisyEnd;
|
||||||
|
|
||||||
|
MOVEGEN::GenerateMoves<Quiet>(board, false, false);
|
||||||
|
|
||||||
|
int rawEnd = board.currentMoveIndex;
|
||||||
|
int write = quietStart;
|
||||||
|
|
||||||
|
for (int read = quietStart; read < rawEnd; read++) {
|
||||||
|
Move m = board.moveList[read];
|
||||||
|
if (m == ttMove || m == killerMove) continue;
|
||||||
|
|
||||||
|
board.moveList[write] = m;
|
||||||
|
scores[write] = ScoreQuietMove(m);
|
||||||
|
write++;
|
||||||
|
}
|
||||||
|
|
||||||
|
quietEnd = write;
|
||||||
|
board.currentMoveIndex = quietEnd;
|
||||||
|
quietCursor = quietStart;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <MovegenMode mode>
|
||||||
|
Move MovePicker<mode>::PopBest(int &cursor, int end) {
|
||||||
|
if (cursor >= end) return Move();
|
||||||
|
|
||||||
|
int bestIdx = cursor;
|
||||||
|
|
||||||
|
for (int i = cursor + 1; i < end; i++) {
|
||||||
|
if (scores[i] > scores[bestIdx]) bestIdx = i;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (bestIdx != cursor) {
|
||||||
|
std::swap(board.moveList[bestIdx], board.moveList[cursor]);
|
||||||
|
std::swap(scores[bestIdx], scores[cursor]);
|
||||||
|
}
|
||||||
|
|
||||||
|
Move best = board.moveList[cursor];
|
||||||
|
cursor++;
|
||||||
|
|
||||||
|
return best;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <MovegenMode mode>
|
||||||
|
Move MovePicker<mode>::Next() {
|
||||||
|
while (true) {
|
||||||
|
switch (stage) {
|
||||||
|
case PickStage::TTMove: {
|
||||||
|
stage = PickStage::GenNoisy;
|
||||||
|
if (ttMove) return ttMove;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
case PickStage::GenNoisy: {
|
||||||
|
ScoreNoisyRange();
|
||||||
|
stage = PickStage::GoodNoisy;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
case PickStage::GoodNoisy: {
|
||||||
|
Move m = PopBest(noisyCursor, goodNoisyEnd);
|
||||||
|
if (m) return m;
|
||||||
|
|
||||||
|
if constexpr (mode == Noisy) {
|
||||||
|
stage = PickStage::BadNoisy;
|
||||||
|
} else {
|
||||||
|
stage = PickStage::Killer;
|
||||||
|
}
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
case PickStage::Killer: {
|
||||||
|
stage = PickStage::GenQuiet;
|
||||||
|
if (killerMove) return killerMove;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
case PickStage::GenQuiet: {
|
||||||
|
ScoreQuietRange();
|
||||||
|
stage = PickStage::Quiet;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
case PickStage::Quiet: {
|
||||||
|
Move m = PopBest(quietCursor, quietEnd);
|
||||||
|
if (m) return m;
|
||||||
|
|
||||||
|
stage = PickStage::BadNoisy;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
case PickStage::BadNoisy: {
|
||||||
|
Move m = PopBest(badNoisyCursor, noisyEnd);
|
||||||
|
if (m) return m;
|
||||||
|
|
||||||
|
stage = PickStage::Finished;
|
||||||
|
return Move();
|
||||||
|
}
|
||||||
|
|
||||||
|
case PickStage::Finished:
|
||||||
|
return Move();
|
||||||
|
|
||||||
|
default:
|
||||||
|
return Move();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
template class MovePicker<Noisy>;
|
||||||
|
template class MovePicker<All>;
|
||||||
|
|
||||||
|
}
|
||||||
@@ -0,0 +1,61 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <array>
|
||||||
|
#include "board.h"
|
||||||
|
#include "movegen.h"
|
||||||
|
|
||||||
|
namespace SEARCH {
|
||||||
|
|
||||||
|
class SearchContext;
|
||||||
|
|
||||||
|
enum class PickStage {
|
||||||
|
TTMove,
|
||||||
|
GenNoisy,
|
||||||
|
GoodNoisy,
|
||||||
|
Killer,
|
||||||
|
GenQuiet,
|
||||||
|
Quiet,
|
||||||
|
BadNoisy,
|
||||||
|
Finished
|
||||||
|
};
|
||||||
|
|
||||||
|
template <MovegenMode mode>
|
||||||
|
class MovePicker {
|
||||||
|
public:
|
||||||
|
MovePicker(Board &board, SearchContext *ctx, int ply, Move ttMove);
|
||||||
|
|
||||||
|
Move Next();
|
||||||
|
|
||||||
|
private:
|
||||||
|
Board &board;
|
||||||
|
SearchContext *ctx;
|
||||||
|
int ply;
|
||||||
|
|
||||||
|
Move ttMove;
|
||||||
|
Move killerMove;
|
||||||
|
|
||||||
|
PickStage stage;
|
||||||
|
|
||||||
|
int noisyStart = 0;
|
||||||
|
int noisyEnd = 0;
|
||||||
|
int goodNoisyEnd = 0;
|
||||||
|
|
||||||
|
int quietStart = 0;
|
||||||
|
int quietEnd = 0;
|
||||||
|
|
||||||
|
int noisyCursor = 0;
|
||||||
|
int badNoisyCursor = 0;
|
||||||
|
int quietCursor = 0;
|
||||||
|
|
||||||
|
std::array<int, MAX_MOVES> scores{};
|
||||||
|
|
||||||
|
void ScoreNoisyRange();
|
||||||
|
|
||||||
|
void ScoreQuietRange();
|
||||||
|
|
||||||
|
int ScoreNoisyMove(Move move);
|
||||||
|
int ScoreQuietMove(Move move);
|
||||||
|
|
||||||
|
Move PopBest(int &cursor, int end);
|
||||||
|
};
|
||||||
|
|
||||||
|
}
|
||||||
+23
-17
@@ -15,24 +15,22 @@ void Network::Load(const std::string& path) {
|
|||||||
std::cerr << "Failed to open file " + path << std::endl;
|
std::cerr << "Failed to open file " + path << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
// HL weights
|
|
||||||
for (size_t i = 0; i < accumulator_weights.size(); i++) {
|
for (size_t i = 0; i < accumulator_weights.size(); i++) {
|
||||||
file.read(reinterpret_cast<char*>(&accumulator_weights[i]), sizeof(int16_t));
|
for (size_t j = 0; j < accumulator_weights[i].size(); j++) {
|
||||||
|
file.read(reinterpret_cast<char*>(&accumulator_weights[i][j]), sizeof(int16_t));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// HL biases
|
|
||||||
for (size_t i = 0; i < accumulator_biases.size(); i++) {
|
for (size_t i = 0; i < accumulator_biases.size(); i++) {
|
||||||
file.read(reinterpret_cast<char*>(&accumulator_biases[i]), sizeof(int16_t));
|
file.read(reinterpret_cast<char*>(&accumulator_biases[i]), sizeof(int16_t));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Output weights
|
|
||||||
for (size_t i = 0; i < output_weights.size(); i++) {
|
for (size_t i = 0; i < output_weights.size(); i++) {
|
||||||
for (size_t j = 0; j < output_weights[i].size(); j++) {
|
for (size_t j = 0; j < output_weights[i].size(); j++) {
|
||||||
file.read(reinterpret_cast<char*>(&output_weights[i][j]), sizeof(int16_t));
|
file.read(reinterpret_cast<char*>(&output_weights[i][j]), sizeof(int16_t));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Output biases
|
|
||||||
for (size_t i = 0; i < output_bias.size(); i++) {
|
for (size_t i = 0; i < output_bias.size(); i++) {
|
||||||
file.read(reinterpret_cast<char*>(&output_bias[i]), sizeof(int16_t));
|
file.read(reinterpret_cast<char*>(&output_bias[i]), sizeof(int16_t));
|
||||||
}
|
}
|
||||||
@@ -133,12 +131,12 @@ using nativeVector = void*;
|
|||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
|
||||||
static int32_t VectorizedSCReLU(const Board& board, const Network& net, size_t outputBucket) {
|
static int32_t VectorizedSCReLU(const Board& board, const ACC::AccumulatorPair& acc, const Network& net, size_t outputBucket) {
|
||||||
const size_t VECTOR_SIZE = sizeof(nativeVector) / sizeof(int16_t);
|
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");
|
static_assert(HL_SIZE % VECTOR_SIZE == 0, "HL size must be divisible by the native register size of your CPU for vectorization to work");
|
||||||
|
|
||||||
const ACC::Accumulator& stmAcc = board.sideToMove == White ? board.accPair.white : board.accPair.black;
|
const ACC::Accumulator& stmAcc = board.sideToMove == White ? acc.white : acc.black;
|
||||||
const ACC::Accumulator& nstmAcc = !board.sideToMove == White ? board.accPair.white : board.accPair.black;
|
const ACC::Accumulator& nstmAcc = !board.sideToMove == White ? acc.white : acc.black;
|
||||||
|
|
||||||
const nativeVector VEC_QA = set1_epi16(QA);
|
const nativeVector VEC_QA = set1_epi16(QA);
|
||||||
const nativeVector VEC_ZERO = set1_epi16(0);
|
const nativeVector VEC_ZERO = set1_epi16(0);
|
||||||
@@ -146,19 +144,15 @@ static int32_t VectorizedSCReLU(const Board& board, const Network& net, size_t o
|
|||||||
nativeVector accumulator{};
|
nativeVector accumulator{};
|
||||||
|
|
||||||
for (int i = 0; i < HL_SIZE; i += VECTOR_SIZE) {
|
for (int i = 0; i < HL_SIZE; i += VECTOR_SIZE) {
|
||||||
// Load accumulators
|
|
||||||
const nativeVector stmAccumValues = load_epi16(reinterpret_cast<const nativeVector*>(&stmAcc[i]));
|
const nativeVector stmAccumValues = load_epi16(reinterpret_cast<const nativeVector*>(&stmAcc[i]));
|
||||||
const nativeVector nstmAccumValues = load_epi16(reinterpret_cast<const nativeVector*>(&nstmAcc[i]));
|
const nativeVector nstmAccumValues = load_epi16(reinterpret_cast<const nativeVector*>(&nstmAcc[i]));
|
||||||
|
|
||||||
// Clamp values
|
|
||||||
const nativeVector stmClamped = min_epi16(VEC_QA, max_epi16(stmAccumValues, VEC_ZERO));
|
const nativeVector stmClamped = min_epi16(VEC_QA, max_epi16(stmAccumValues, VEC_ZERO));
|
||||||
const nativeVector nstmClamped = min_epi16(VEC_QA, max_epi16(nstmAccumValues, VEC_ZERO));
|
const nativeVector nstmClamped = min_epi16(VEC_QA, max_epi16(nstmAccumValues, VEC_ZERO));
|
||||||
|
|
||||||
// Load weights
|
|
||||||
const nativeVector stmWeights = load_epi16(reinterpret_cast<const nativeVector*>(&net.output_weights[outputBucket][i]));
|
const nativeVector stmWeights = load_epi16(reinterpret_cast<const nativeVector*>(&net.output_weights[outputBucket][i]));
|
||||||
const nativeVector nstmWeights = load_epi16(reinterpret_cast<const nativeVector*>(&net.output_weights[outputBucket][i + HL_SIZE]));
|
const nativeVector nstmWeights = load_epi16(reinterpret_cast<const nativeVector*>(&net.output_weights[outputBucket][i + HL_SIZE]));
|
||||||
|
|
||||||
// SCReLU activation
|
|
||||||
const nativeVector stmActivated = madd_epi16(stmClamped, mullo_epi16(stmClamped, stmWeights));
|
const nativeVector stmActivated = madd_epi16(stmClamped, mullo_epi16(stmClamped, stmWeights));
|
||||||
const nativeVector nstmActivated = madd_epi16(nstmClamped, mullo_epi16(nstmClamped, nstmWeights));
|
const nativeVector nstmActivated = madd_epi16(nstmClamped, mullo_epi16(nstmClamped, nstmWeights));
|
||||||
|
|
||||||
@@ -169,13 +163,13 @@ static int32_t VectorizedSCReLU(const Board& board, const Network& net, size_t o
|
|||||||
return reduce_epi32(accumulator);
|
return reduce_epi32(accumulator);
|
||||||
}
|
}
|
||||||
|
|
||||||
int Forward(const Board& board, const Network& net) {
|
static int Forward(const Board& board, const ACC::AccumulatorPair& acc, const Network& net) {
|
||||||
const size_t divisor = 32 / OUTPUT_BUCKETS;
|
const size_t divisor = 32 / OUTPUT_BUCKETS;
|
||||||
const size_t outputBucket = (board.occupied.PopCount() - 2) / divisor;
|
const size_t outputBucket = (board.occupied.PopCount() - 2) / divisor;
|
||||||
|
|
||||||
int64_t eval = 0;
|
int64_t eval = 0;
|
||||||
|
|
||||||
eval = VectorizedSCReLU(board, net, outputBucket);
|
eval = VectorizedSCReLU(board, acc, net, outputBucket);
|
||||||
|
|
||||||
eval /= QA;
|
eval /= QA;
|
||||||
|
|
||||||
@@ -185,9 +179,21 @@ int Forward(const Board& board, const Network& net) {
|
|||||||
return (eval * SCALE) / (QA * QB);
|
return (eval * SCALE) / (QA * QB);
|
||||||
}
|
}
|
||||||
|
|
||||||
int16_t Network::Evaluate(const Board& board) {
|
int16_t Network::Evaluate(const Board& board, const ACC::AccumulatorPair& acc, bool datagen) {
|
||||||
return std::clamp(Forward(board, *this), (-SEARCH::MATE_SCORE + SEARCH::MAX_PLY),
|
const int materialScale = datagen ? 4096 : 2048
|
||||||
(SEARCH::MATE_SCORE - SEARCH::MAX_PLY));
|
+ 90 * board.pieces[Knight].PopCount()
|
||||||
|
+ 90 * board.pieces[Bishop].PopCount()
|
||||||
|
+ 180 * board.pieces[Rook].PopCount()
|
||||||
|
+ 360 * board.pieces[Queen].PopCount();
|
||||||
|
|
||||||
|
return std::clamp(Forward(board, acc, *this) * materialScale / 4096, (-SEARCH::MATE_SCORE + SEARCH::MAX_DEPTH),
|
||||||
|
(SEARCH::MATE_SCORE - SEARCH::MAX_DEPTH));
|
||||||
|
}
|
||||||
|
|
||||||
|
int16_t Network::Evaluate(const Board& board, bool datagen) {
|
||||||
|
ACC::AccumulatorPair acc;
|
||||||
|
board.RefreshAccumulator(acc);
|
||||||
|
return Evaluate(board, acc, datagen);
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
+34
-5
@@ -3,10 +3,12 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
#include <array>
|
#include <array>
|
||||||
|
|
||||||
#include "../external/fmt/fmt/format.h"
|
|
||||||
|
|
||||||
class Board;
|
class Board;
|
||||||
|
|
||||||
|
namespace ACC {
|
||||||
|
struct AccumulatorPair;
|
||||||
|
}
|
||||||
|
|
||||||
#ifdef __AVX512F__
|
#ifdef __AVX512F__
|
||||||
constexpr size_t ALIGNMENT = 64;
|
constexpr size_t ALIGNMENT = 64;
|
||||||
#else
|
#else
|
||||||
@@ -16,22 +18,49 @@ constexpr size_t ALIGNMENT = 32;
|
|||||||
namespace NNUE {
|
namespace NNUE {
|
||||||
|
|
||||||
constexpr size_t INPUT_SIZE = 768;
|
constexpr size_t INPUT_SIZE = 768;
|
||||||
constexpr size_t HL_SIZE = 1024;
|
constexpr size_t HL_SIZE = 1536;
|
||||||
|
constexpr size_t INPUT_BUCKETS = 8;
|
||||||
constexpr size_t OUTPUT_BUCKETS = 8;
|
constexpr size_t OUTPUT_BUCKETS = 8;
|
||||||
|
|
||||||
constexpr int16_t SCALE = 400;
|
constexpr int16_t SCALE = 400;
|
||||||
constexpr int16_t QA = 255;
|
constexpr int16_t QA = 255;
|
||||||
constexpr int16_t QB = 64;
|
constexpr int16_t QB = 64;
|
||||||
|
|
||||||
|
constexpr int kingBuckets[2][64] = {
|
||||||
|
{
|
||||||
|
0, 1, 2, 3, 3, 2, 1, 0,
|
||||||
|
4, 4, 5, 5, 5, 5, 4, 4,
|
||||||
|
6, 6, 6, 6, 6, 6, 6, 6,
|
||||||
|
6, 6, 6, 6, 6, 6, 6, 6,
|
||||||
|
6, 6, 6, 6, 6, 6, 6, 6,
|
||||||
|
7, 7, 7, 7, 7, 7, 7, 7,
|
||||||
|
7, 7, 7, 7, 7, 7, 7, 7,
|
||||||
|
7, 7, 7, 7, 7, 7, 7, 7
|
||||||
|
},
|
||||||
|
|
||||||
|
{
|
||||||
|
7, 7, 7, 7, 7, 7, 7, 7,
|
||||||
|
7, 7, 7, 7, 7, 7, 7, 7,
|
||||||
|
7, 7, 7, 7, 7, 7, 7, 7,
|
||||||
|
6, 6, 6, 6, 6, 6, 6, 6,
|
||||||
|
6, 6, 6, 6, 6, 6, 6, 6,
|
||||||
|
6, 6, 6, 6, 6, 6, 6, 6,
|
||||||
|
4, 4, 5, 5, 5, 5, 4, 4,
|
||||||
|
0, 1, 2, 3, 3, 2, 1, 0,
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
struct Network {
|
struct Network {
|
||||||
alignas(ALIGNMENT) std::array<int16_t, HL_SIZE * INPUT_SIZE> accumulator_weights;
|
alignas(ALIGNMENT) std::array<std::array<int16_t, HL_SIZE * INPUT_SIZE>, INPUT_BUCKETS> accumulator_weights;
|
||||||
alignas(ALIGNMENT) std::array<int16_t, HL_SIZE> accumulator_biases;
|
alignas(ALIGNMENT) std::array<int16_t, HL_SIZE> accumulator_biases;
|
||||||
alignas(ALIGNMENT) std::array<std::array<int16_t, 2 * HL_SIZE>, OUTPUT_BUCKETS> output_weights;
|
alignas(ALIGNMENT) std::array<std::array<int16_t, 2 * HL_SIZE>, OUTPUT_BUCKETS> output_weights;
|
||||||
std::array<int16_t, OUTPUT_BUCKETS> output_bias;
|
std::array<int16_t, OUTPUT_BUCKETS> output_bias;
|
||||||
|
|
||||||
void Load(const std::string& path);
|
void Load(const std::string& path);
|
||||||
|
|
||||||
int16_t Evaluate(const Board& board);
|
int16_t Evaluate(const Board& board, const ACC::AccumulatorPair& acc, bool datagen = false);
|
||||||
|
|
||||||
|
int16_t Evaluate(const Board& board, bool datagen = false);
|
||||||
};
|
};
|
||||||
|
|
||||||
inline Network net;
|
inline Network net;
|
||||||
|
|||||||
+249
-26
@@ -1,42 +1,265 @@
|
|||||||
#include "perft.h"
|
#include "perft.h"
|
||||||
#include "stopwatch.h"
|
#include "stopwatch.h"
|
||||||
#include "movegen.h"
|
#include "movegen.h"
|
||||||
|
#include "termcolor.hpp"
|
||||||
|
#include <iostream>
|
||||||
|
#include <iomanip>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
static U64 HelperPerft(Board board, int depth) {
|
struct PerftCounts {
|
||||||
MOVEGEN::GenerateMoves<All>(board);
|
|
||||||
|
|
||||||
if (depth == 0) return 1ULL;
|
|
||||||
|
|
||||||
U64 nodes = 0;
|
U64 nodes = 0;
|
||||||
|
U64 captures = 0;
|
||||||
|
U64 ep = 0;
|
||||||
|
U64 castles = 0;
|
||||||
|
U64 promotions = 0;
|
||||||
|
U64 checks = 0;
|
||||||
|
U64 discovery = 0;
|
||||||
|
U64 doubles = 0;
|
||||||
|
U64 mates = 0;
|
||||||
|
|
||||||
for (int i = 0; i < board.currentMoveIndex; i++) {
|
PerftCounts& operator+=(const PerftCounts& other) {
|
||||||
Board copy = board;
|
nodes += other.nodes;
|
||||||
bool isLegal = copy.MakeMove(board.moveList[i]);
|
captures += other.captures;
|
||||||
if (!isLegal) continue;
|
ep += other.ep;
|
||||||
nodes += HelperPerft(copy, depth - 1);
|
castles += other.castles;
|
||||||
|
promotions += other.promotions;
|
||||||
|
checks += other.checks;
|
||||||
|
discovery += other.discovery;
|
||||||
|
doubles += other.doubles;
|
||||||
|
mates += other.mates;
|
||||||
|
return *this;
|
||||||
}
|
}
|
||||||
return nodes;
|
};
|
||||||
|
|
||||||
|
static bool IsDirectCheck(Board& pos, Move move) {
|
||||||
|
int mover = !pos.sideToMove;
|
||||||
|
int kingSq = (pos.pieces[King] & pos.colors[pos.sideToMove]).getLS1BIndex();
|
||||||
|
if (kingSq < 0 || kingSq >= 64)
|
||||||
|
return false;
|
||||||
|
int to = move.MoveTo();
|
||||||
|
int flags = move.GetFlags();
|
||||||
|
if (flags == kingCastle || flags == queenCastle) {
|
||||||
|
int rookFrom = mover ? (flags == kingCastle ? h8 : a8) : (flags == kingCastle ? h1 : a1);
|
||||||
|
int rookTo = flags == kingCastle ? rookFrom - 2 : rookFrom + 3;
|
||||||
|
Bitboard rookAtt = MOVEGEN::getRookAttack(rookTo, pos.occupied);
|
||||||
|
return rookAtt.IsSet(kingSq);
|
||||||
|
}
|
||||||
|
int endPiece = pos.GetPieceType(to);
|
||||||
|
if (endPiece == nullPieceType || endPiece == King)
|
||||||
|
return false;
|
||||||
|
Bitboard att = MOVEGEN::getPieceAttacks(to, endPiece, mover, pos.occupied);
|
||||||
|
return att.IsSet(kingSq);
|
||||||
|
}
|
||||||
|
|
||||||
|
static void CountLeaf(Board& pos, Move move, PerftCounts& out) {
|
||||||
|
out.nodes++;
|
||||||
|
int flags = move.GetFlags();
|
||||||
|
if (move.IsCapture())
|
||||||
|
out.captures++;
|
||||||
|
if (flags == epCapture)
|
||||||
|
out.ep++;
|
||||||
|
if (flags == kingCastle || flags == queenCastle)
|
||||||
|
out.castles++;
|
||||||
|
if (move.IsPromo())
|
||||||
|
out.promotions++;
|
||||||
|
if (pos.InCheck()) {
|
||||||
|
out.checks++;
|
||||||
|
if (pos.checkers.PopCount() == 2)
|
||||||
|
out.doubles++;
|
||||||
|
if (!IsDirectCheck(pos, move))
|
||||||
|
out.discovery++;
|
||||||
|
MOVEGEN::GenerateMoves<All>(pos, true);
|
||||||
|
bool hasLegal = false;
|
||||||
|
for (int i = 0; i < pos.currentMoveIndex; i++) {
|
||||||
|
Move m = pos.moveList[i];
|
||||||
|
if (pos.IsLegal(m)) {
|
||||||
|
hasLegal = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!hasLegal)
|
||||||
|
out.mates++;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void PerftRec(Board& board, int depth, PerftCounts& out) {
|
||||||
|
MOVEGEN::GenerateMoves<All>(board, true);
|
||||||
|
for (int i = 0; i < board.currentMoveIndex; i++) {
|
||||||
|
Move move = board.moveList[i];
|
||||||
|
if (!board.IsLegal(move))
|
||||||
|
continue;
|
||||||
|
Board copy = board;
|
||||||
|
copy.MakeMove(move);
|
||||||
|
if (depth == 1)
|
||||||
|
CountLeaf(copy, move, out);
|
||||||
|
else
|
||||||
|
PerftRec(copy, depth - 1, out);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void PrintPerftHeader() {
|
||||||
|
std::cout << termcolor::bold << termcolor::color<244>;
|
||||||
|
std::cout << std::setw(6) << std::left << "Move";
|
||||||
|
std::cout << std::setw(11) << std::right << "Nodes";
|
||||||
|
std::cout << std::setw(8) << std::right << "Capt";
|
||||||
|
std::cout << std::setw(7) << std::right << "E.P.";
|
||||||
|
std::cout << std::setw(7) << std::right << "Cast";
|
||||||
|
std::cout << std::setw(7) << std::right << "Promo";
|
||||||
|
std::cout << std::setw(8) << std::right << "Check";
|
||||||
|
std::cout << std::setw(7) << std::right << "Disc";
|
||||||
|
std::cout << std::setw(5) << std::right << "Dbl";
|
||||||
|
std::cout << std::setw(7) << std::right << "Mate";
|
||||||
|
std::cout << termcolor::reset << std::endl;
|
||||||
|
|
||||||
|
std::cout << termcolor::color<238>;
|
||||||
|
for (int i = 0; i < 73; i++)
|
||||||
|
std::cout << '-';
|
||||||
|
std::cout << termcolor::reset << std::endl;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void PrintPerftBase(int index) {
|
||||||
|
if (index % 2 == 0)
|
||||||
|
std::cout << termcolor::color<247>;
|
||||||
|
else
|
||||||
|
std::cout << termcolor::color<251>;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void PrintPerftLine(int index, const std::string& moveStr, const PerftCounts& c) {
|
||||||
|
PrintPerftBase(index);
|
||||||
|
|
||||||
|
std::cout << termcolor::bold << termcolor::bright_cyan;
|
||||||
|
std::cout << std::setw(6) << std::left << (moveStr + ":");
|
||||||
|
std::cout << termcolor::reset;
|
||||||
|
PrintPerftBase(index);
|
||||||
|
|
||||||
|
std::cout << termcolor::bold << termcolor::bright_white;
|
||||||
|
std::cout << std::setw(11) << std::right << c.nodes;
|
||||||
|
std::cout << termcolor::reset;
|
||||||
|
PrintPerftBase(index);
|
||||||
|
|
||||||
|
if (c.captures > 0)
|
||||||
|
std::cout << termcolor::bold << termcolor::yellow;
|
||||||
|
else
|
||||||
|
std::cout << termcolor::color<244>;
|
||||||
|
std::cout << std::setw(8) << std::right << c.captures;
|
||||||
|
std::cout << termcolor::reset;
|
||||||
|
PrintPerftBase(index);
|
||||||
|
|
||||||
|
if (c.ep > 0)
|
||||||
|
std::cout << termcolor::bold << termcolor::bright_yellow;
|
||||||
|
else
|
||||||
|
std::cout << termcolor::color<244>;
|
||||||
|
std::cout << std::setw(7) << std::right << c.ep;
|
||||||
|
std::cout << termcolor::reset;
|
||||||
|
PrintPerftBase(index);
|
||||||
|
|
||||||
|
if (c.castles > 0)
|
||||||
|
std::cout << termcolor::bold << termcolor::cyan;
|
||||||
|
else
|
||||||
|
std::cout << termcolor::color<244>;
|
||||||
|
std::cout << std::setw(7) << std::right << c.castles;
|
||||||
|
std::cout << termcolor::reset;
|
||||||
|
PrintPerftBase(index);
|
||||||
|
|
||||||
|
if (c.promotions > 0)
|
||||||
|
std::cout << termcolor::bold << termcolor::magenta;
|
||||||
|
else
|
||||||
|
std::cout << termcolor::color<244>;
|
||||||
|
std::cout << std::setw(7) << std::right << c.promotions;
|
||||||
|
std::cout << termcolor::reset;
|
||||||
|
PrintPerftBase(index);
|
||||||
|
|
||||||
|
if (c.checks > 0)
|
||||||
|
std::cout << termcolor::bold << termcolor::green;
|
||||||
|
else
|
||||||
|
std::cout << termcolor::color<244>;
|
||||||
|
std::cout << std::setw(8) << std::right << c.checks;
|
||||||
|
std::cout << termcolor::reset;
|
||||||
|
PrintPerftBase(index);
|
||||||
|
|
||||||
|
if (c.discovery > 0)
|
||||||
|
std::cout << termcolor::bold << termcolor::bright_magenta;
|
||||||
|
else
|
||||||
|
std::cout << termcolor::color<244>;
|
||||||
|
std::cout << std::setw(7) << std::right << c.discovery;
|
||||||
|
std::cout << termcolor::reset;
|
||||||
|
PrintPerftBase(index);
|
||||||
|
|
||||||
|
if (c.doubles > 0)
|
||||||
|
std::cout << termcolor::bold << termcolor::bright_red;
|
||||||
|
else
|
||||||
|
std::cout << termcolor::color<244>;
|
||||||
|
std::cout << std::setw(5) << std::right << c.doubles;
|
||||||
|
std::cout << termcolor::reset;
|
||||||
|
PrintPerftBase(index);
|
||||||
|
|
||||||
|
if (c.mates > 0)
|
||||||
|
std::cout << termcolor::bold << termcolor::red;
|
||||||
|
else
|
||||||
|
std::cout << termcolor::color<244>;
|
||||||
|
std::cout << std::setw(7) << std::right << c.mates;
|
||||||
|
std::cout << termcolor::reset << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
void Perft(Board &board, int depth) {
|
void Perft(Board &board, int depth) {
|
||||||
MOVEGEN::GenerateMoves<All>(board);
|
|
||||||
|
|
||||||
U64 totalNodes = 0;
|
|
||||||
|
|
||||||
Stopwatch sw;
|
Stopwatch sw;
|
||||||
for (int i = 0; i < board.currentMoveIndex; i++) {
|
|
||||||
Board copy = board;
|
|
||||||
bool isLegal = copy.MakeMove(board.moveList[i]);
|
|
||||||
if (!isLegal) continue;
|
|
||||||
U64 nodeCount = HelperPerft(copy, depth - 1);
|
|
||||||
totalNodes += nodeCount;
|
|
||||||
board.moveList[i].PrintMove();
|
|
||||||
|
|
||||||
std::cout << ": " << nodeCount << std::endl;
|
if (depth <= 0) {
|
||||||
|
std::cout << std::endl << "Depth: " << depth << std::endl;
|
||||||
|
std::cout << "Total nodes: 1" << std::endl;
|
||||||
|
std::cout << "Time took: " << sw.GetElapsedSec() << "s (";
|
||||||
|
std::cout << int(1 / sw.GetElapsedSec()) << " nodes/sec)" << std::endl;
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
MOVEGEN::GenerateMoves<All>(board, true);
|
||||||
|
|
||||||
|
PerftCounts total;
|
||||||
|
int moveCount = 0;
|
||||||
|
|
||||||
|
PrintPerftHeader();
|
||||||
|
|
||||||
|
for (int i = 0; i < board.currentMoveIndex; i++) {
|
||||||
|
Move move = board.moveList[i];
|
||||||
|
if (!board.IsLegal(move))
|
||||||
|
continue;
|
||||||
|
Board copy = board;
|
||||||
|
copy.MakeMove(move);
|
||||||
|
PerftCounts local;
|
||||||
|
if (depth == 1)
|
||||||
|
CountLeaf(copy, move, local);
|
||||||
|
else
|
||||||
|
PerftRec(copy, depth - 1, local);
|
||||||
|
total += local;
|
||||||
|
PrintPerftLine(moveCount, move.GetMoveString(), local);
|
||||||
|
moveCount++;
|
||||||
|
}
|
||||||
|
|
||||||
|
double elapsed = sw.GetElapsedSec();
|
||||||
|
|
||||||
|
std::cout << termcolor::color<238>;
|
||||||
|
for (int i = 0; i < 73; i++)
|
||||||
|
std::cout << '-';
|
||||||
|
std::cout << termcolor::reset << std::endl;
|
||||||
|
|
||||||
|
PrintPerftLine(moveCount, "Total", total);
|
||||||
|
|
||||||
|
std::cout << std::endl;
|
||||||
|
std::cout << termcolor::bold << termcolor::bright_white;
|
||||||
|
std::cout << "Depth: " << depth;
|
||||||
|
std::cout << " Moves: " << moveCount;
|
||||||
|
std::cout << " Nodes: " << total.nodes;
|
||||||
|
U64 nps = elapsed > 0 ? U64(double(total.nodes) / elapsed) : total.nodes;
|
||||||
|
std::cout << " Time: ";
|
||||||
|
if (elapsed >= 1.0)
|
||||||
|
std::cout << elapsed << "s";
|
||||||
|
else
|
||||||
|
std::cout << int(elapsed * 1000) << "ms";
|
||||||
|
std::cout << " Avg: " << nps << "/s";
|
||||||
|
std::cout << termcolor::reset << std::endl;
|
||||||
|
|
||||||
std::cout << std::endl << "Depth: " << depth << std::endl;
|
std::cout << std::endl << "Depth: " << depth << std::endl;
|
||||||
std::cout << "Total nodes: " << totalNodes << std::endl;
|
std::cout << "Total nodes: " << total.nodes << std::endl;
|
||||||
std::cout << "Time took: " << sw.GetElapsedSec() << "s (";
|
std::cout << "Time took: " << elapsed << "s (";
|
||||||
std::cout << int(totalNodes / sw.GetElapsedSec()) << " nodes/sec)" << std::endl;
|
std::cout << int(double(total.nodes) / elapsed) << " nodes/sec)" << std::endl;
|
||||||
}
|
}
|
||||||
+846
-356
File diff suppressed because it is too large.
Load diff
+154
-25
@@ -2,9 +2,13 @@
|
|||||||
#include "board.h"
|
#include "board.h"
|
||||||
#include "uci.h"
|
#include "uci.h"
|
||||||
#include <vector>
|
#include <vector>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
#include "move.h"
|
#include "move.h"
|
||||||
#include <algorithm>
|
#include <algorithm>
|
||||||
#include "stopwatch.h"
|
#include "stopwatch.h"
|
||||||
|
#include "tunables.h"
|
||||||
|
#include "termcolor.hpp"
|
||||||
#include "tt.h"
|
#include "tt.h"
|
||||||
|
|
||||||
#include "../external/multi_array.h"
|
#include "../external/multi_array.h"
|
||||||
@@ -19,25 +23,105 @@ enum searchMode {
|
|||||||
};
|
};
|
||||||
|
|
||||||
constexpr int MATE_SCORE = 32767;
|
constexpr int MATE_SCORE = 32767;
|
||||||
constexpr int MAX_DEPTH = 128;
|
constexpr int MAX_DEPTH = 256;
|
||||||
constexpr int MAX_PLY = 512;
|
|
||||||
constexpr int MAX_HISTORY = 16384;
|
constexpr int MAX_HISTORY = 16384;
|
||||||
|
constexpr int WIN_SCORE = 30000;
|
||||||
|
|
||||||
|
constexpr int CORRHIST_WEIGHT_SCALE = 256;
|
||||||
|
constexpr int CORRHIST_GRAIN = 256;
|
||||||
|
constexpr int CORRHIST_LIMIT = 1024;
|
||||||
|
constexpr int CORRHIST_SIZE = 16384;
|
||||||
|
constexpr int CORRHIST_MAX = 16384;
|
||||||
|
|
||||||
constexpr int32_t ScoreNone = -255000;
|
constexpr int32_t ScoreNone = -255000;
|
||||||
constexpr int inf = 100000;
|
constexpr int inf = 100000;
|
||||||
|
|
||||||
inline int lmrTable[MAX_DEPTH+1][MAX_MOVES];
|
inline int lmrTable[2][MAX_DEPTH+1][MAX_MOVES];
|
||||||
|
|
||||||
constexpr std::array<int, 6> SEEPieceValues = {
|
#ifdef TUNING
|
||||||
100, 300, 350, 500, 900, 0
|
inline std::array<int, 6> SEEPieceValues = {
|
||||||
|
seePawnValue, seeKnightValue, seeBishopValue, seeRookValue, seeQueenValue, 0
|
||||||
};
|
};
|
||||||
|
#else
|
||||||
|
constexpr std::array<int, 6> SEEPieceValues = {
|
||||||
|
seePawnValue, seeKnightValue, seeBishopValue, seeRookValue, seeQueenValue, 0
|
||||||
|
};
|
||||||
|
#endif
|
||||||
|
|
||||||
void InitLMRTable();
|
void InitLMRTable();
|
||||||
|
|
||||||
|
#ifdef TUNING
|
||||||
|
void InitSEEPieceValues();
|
||||||
|
void RefreshTunableCaches();
|
||||||
|
#endif
|
||||||
|
|
||||||
class SearchContext;
|
class SearchContext;
|
||||||
|
|
||||||
|
struct RootVote {
|
||||||
|
Move bestMove;
|
||||||
|
int score = 0;
|
||||||
|
int depth = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
SearchResults VoteRootMoves(const std::vector<RootVote>& votes);
|
||||||
|
|
||||||
|
class CaptHistory {
|
||||||
|
private:
|
||||||
|
MultiArray<int, 2, 6, 6, 64> historyMoves;
|
||||||
|
public:
|
||||||
|
void Update(bool stm, int moving, int capture, int to, int bonus) {
|
||||||
|
int clampedBonus = std::clamp(bonus, -MAX_HISTORY, MAX_HISTORY);
|
||||||
|
historyMoves[stm][moving][capture][to] +=
|
||||||
|
clampedBonus - historyMoves[stm][moving][capture][to] * std::abs(clampedBonus) / MAX_HISTORY;
|
||||||
|
}
|
||||||
|
|
||||||
|
void Clear() {
|
||||||
|
std::fill(&historyMoves[0][0][0][0], &historyMoves[0][0][0][0] + sizeof(historyMoves) / sizeof(int), 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
auto& operator[](int index) {
|
||||||
|
return historyMoves[index];
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
class CorrHist {
|
||||||
|
private:
|
||||||
|
struct Tables {
|
||||||
|
MultiArray<int, 2, CORRHIST_SIZE> pawnHist{};
|
||||||
|
MultiArray<int, 2, CORRHIST_SIZE> nonPawnHist{};
|
||||||
|
MultiArray<int, 2, CORRHIST_SIZE> majorHist{};
|
||||||
|
};
|
||||||
|
std::shared_ptr<Tables> t = std::make_shared<Tables>();
|
||||||
|
public:
|
||||||
|
void Update(Board& board, int depth, int diff, int* entry) {
|
||||||
|
const int scaledDiff = diff * CORRHIST_GRAIN;
|
||||||
|
const int newWeight = std::min(depth * depth + 2 * depth + 1, 128);
|
||||||
|
|
||||||
|
*entry = (*entry * (CORRHIST_WEIGHT_SCALE - newWeight) + scaledDiff * newWeight) / CORRHIST_WEIGHT_SCALE;
|
||||||
|
*entry = std::clamp(*entry, -CORRHIST_MAX, CORRHIST_MAX);
|
||||||
|
}
|
||||||
|
|
||||||
|
void UpdateAll(Board& board, int depth, int diff) {
|
||||||
|
Update(board, depth, diff, &t->pawnHist[board.sideToMove][board.pawnKey % CORRHIST_SIZE]);
|
||||||
|
Update(board, depth, diff, &t->nonPawnHist[board.sideToMove][board.nonPawnKey % CORRHIST_SIZE]);
|
||||||
|
Update(board, depth, diff, &t->majorHist[board.sideToMove][board.majorKey % CORRHIST_SIZE]);
|
||||||
|
}
|
||||||
|
|
||||||
|
int GetAllHist(Board& board) {
|
||||||
|
return t->pawnHist[board.sideToMove][board.pawnKey % CORRHIST_SIZE]
|
||||||
|
+ t->nonPawnHist[board.sideToMove][board.nonPawnKey % CORRHIST_SIZE]
|
||||||
|
+ t->majorHist[board.sideToMove][board.majorKey % CORRHIST_SIZE];
|
||||||
|
}
|
||||||
|
|
||||||
|
void Clear() {
|
||||||
|
std::fill(&t->pawnHist[0][0], &t->pawnHist[0][0] + sizeof(t->pawnHist) / sizeof(int), 0);
|
||||||
|
std::fill(&t->nonPawnHist[0][0], &t->nonPawnHist[0][0] + sizeof(t->nonPawnHist) / sizeof(int), 0);
|
||||||
|
std::fill(&t->majorHist[0][0], &t->majorHist[0][0] + sizeof(t->majorHist) / sizeof(int), 0);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
class ContHistory {
|
class ContHistory {
|
||||||
private:
|
private:
|
||||||
// indexed by [other color][prev move piece][stm][prev move to][piece][to]
|
|
||||||
MultiArray<int16_t, 2, 6, 64, 2, 6, 64> contHistMoves;
|
MultiArray<int16_t, 2, 6, 64, 2, 6, 64> contHistMoves;
|
||||||
public:
|
public:
|
||||||
void Update(bool stm, bool otherColor, int prevType, int prevTo, int type, int to, int bonus) {
|
void Update(bool stm, bool otherColor, int prevType, int prevTo, int type, int to, int bonus) {
|
||||||
@@ -51,8 +135,7 @@ public:
|
|||||||
std::fill(&contHistMoves[0][0][0][0][0][0], &contHistMoves[0][0][0][0][0][0] + sizeof(contHistMoves) / sizeof(int16_t), 0);
|
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 GetNPly(Board& board, Move& move, SearchContext* ctx, int ply, int n);
|
||||||
int16_t GetTwoPly(Board& board, Move& move, SearchContext* ctx, int ply);
|
|
||||||
|
|
||||||
auto& operator[](int index) {
|
auto& operator[](int index) {
|
||||||
return contHistMoves[index];
|
return contHistMoves[index];
|
||||||
@@ -61,16 +144,16 @@ public:
|
|||||||
|
|
||||||
class History {
|
class History {
|
||||||
private:
|
private:
|
||||||
MultiArray<int, 2, 64, 64> historyMoves;
|
MultiArray<int, 2, 64, 64, 2, 2> historyMoves;
|
||||||
public:
|
public:
|
||||||
void Update(bool stm, Move move, int bonus) {
|
void Update(bool stm, Move move, bool source, bool target, int bonus) {
|
||||||
int clampedBonus = std::clamp(bonus, -MAX_HISTORY, MAX_HISTORY);
|
int clampedBonus = std::clamp(bonus, -MAX_HISTORY, MAX_HISTORY);
|
||||||
historyMoves[stm][move.MoveFrom()][move.MoveTo()] +=
|
historyMoves[stm][move.MoveFrom()][move.MoveTo()][source][target] +=
|
||||||
clampedBonus - historyMoves[stm][move.MoveFrom()][move.MoveTo()] * std::abs(clampedBonus) / MAX_HISTORY;
|
clampedBonus - historyMoves[stm][move.MoveFrom()][move.MoveTo()][source][target] * std::abs(clampedBonus) / MAX_HISTORY;
|
||||||
}
|
}
|
||||||
|
|
||||||
void Clear() {
|
void Clear() {
|
||||||
std::fill(&historyMoves[0][0][0], &historyMoves[0][0][0] + sizeof(historyMoves) / sizeof(int), 0);
|
std::fill(&historyMoves[0][0][0][0][0], &historyMoves[0][0][0][0][0] + sizeof(historyMoves) / sizeof(int), 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
auto& operator[](int index) {
|
auto& operator[](int index) {
|
||||||
@@ -80,8 +163,8 @@ public:
|
|||||||
|
|
||||||
class PVLine {
|
class PVLine {
|
||||||
private:
|
private:
|
||||||
int length[MAX_PLY] = {};
|
int length[MAX_DEPTH] = {};
|
||||||
Move table[MAX_PLY][MAX_PLY] = {};
|
Move table[MAX_DEPTH][MAX_DEPTH] = {};
|
||||||
public:
|
public:
|
||||||
void SetLength(int ply) {
|
void SetLength(int ply) {
|
||||||
length[ply] = ply;
|
length[ply] = ply;
|
||||||
@@ -97,13 +180,36 @@ public:
|
|||||||
length[ply] = length[ply + 1];
|
length[ply] = length[ply + 1];
|
||||||
}
|
}
|
||||||
|
|
||||||
void Print(int n) {
|
void Print(int n, bool isEven = false) {
|
||||||
for (int i = 0; i < length[n]; i++) {
|
for (int i = 0; i < length[n]; i++) {
|
||||||
table[n][i].PrintMove();
|
if (i == 0 && !UCIEnabled) {
|
||||||
std::cout << ' ';
|
std::cout << termcolor::bold << termcolor::bright_cyan;
|
||||||
|
table[n][i].PrintMove();
|
||||||
|
std::cout << termcolor::reset;
|
||||||
|
|
||||||
|
if (isEven) {
|
||||||
|
std::cout << termcolor::color<247>;
|
||||||
|
} else {
|
||||||
|
std::cout << termcolor::color<251>;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
table[n][i].PrintMove();
|
||||||
|
}
|
||||||
|
if (i + 1 < length[n])
|
||||||
|
std::cout << ' ';
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::string GetLine(int n) {
|
||||||
|
std::string result = "";
|
||||||
|
for (int i = 0; i < length[n]; i++) {
|
||||||
|
result += table[n][i].GetMoveString();
|
||||||
|
result += ' ';
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
void Clear() {
|
void Clear() {
|
||||||
length[MAX_DEPTH - 1] = {};
|
length[MAX_DEPTH - 1] = {};
|
||||||
table[MAX_DEPTH - 1][MAX_DEPTH - 1] = {};
|
table[MAX_DEPTH - 1][MAX_DEPTH - 1] = {};
|
||||||
@@ -121,28 +227,41 @@ public:
|
|||||||
|
|
||||||
class SearchContext {
|
class SearchContext {
|
||||||
public:
|
public:
|
||||||
|
bool doPrint = false;
|
||||||
|
|
||||||
|
int threadId = 0;
|
||||||
|
std::vector<RootVote>* voteTable = nullptr;
|
||||||
|
std::mutex* voteMutex = nullptr;
|
||||||
|
|
||||||
U64 nodes = 0;
|
U64 nodes = 0;
|
||||||
U64 nodesToGo = 0;
|
U64 nodesToGo = 0;
|
||||||
int timeToSearch = 0;
|
int timeToSearch = 0;
|
||||||
|
std::vector<Move> searchMoves;
|
||||||
|
|
||||||
|
std::array<U64, 4096> nodesTable{};
|
||||||
|
|
||||||
int seldepth = 0;
|
int seldepth = 0;
|
||||||
|
int rootDepth = 0;
|
||||||
|
|
||||||
Move excluded = Move();
|
Move excluded = Move();
|
||||||
|
|
||||||
bool doingNullMove = false;
|
int minNmpPly = 0;
|
||||||
bool searchStopped = false;
|
|
||||||
|
|
||||||
PVLine pvLine;
|
PVLine pvLine;
|
||||||
History history;
|
History history;
|
||||||
ContHistory conthist;
|
ContHistory conthist;
|
||||||
|
CorrHist corrhist;
|
||||||
|
CaptHistory capthist;
|
||||||
|
|
||||||
std::array<std::array<int, MAX_PLY>, 2> killerMoves{};
|
std::array<Move, MAX_DEPTH> killerMoves{};
|
||||||
|
|
||||||
std::vector<U64> positionHistory;
|
std::vector<U64> positionHistory;
|
||||||
|
|
||||||
TTable TT;
|
TTable* TT = &SharedTT;
|
||||||
|
|
||||||
std::array<Stack, MAX_PLY> ss{};
|
std::array<Stack, MAX_DEPTH> ss{};
|
||||||
|
|
||||||
|
ACC::AccStack accStack{MAX_DEPTH + 2};
|
||||||
|
|
||||||
Stopwatch sw;
|
Stopwatch sw;
|
||||||
|
|
||||||
@@ -150,12 +269,20 @@ public:
|
|||||||
pvLine.Clear();
|
pvLine.Clear();
|
||||||
history.Clear();
|
history.Clear();
|
||||||
conthist.Clear();
|
conthist.Clear();
|
||||||
TT.Clear();
|
corrhist.Clear();
|
||||||
|
capthist.Clear();
|
||||||
sw.Restart();
|
sw.Restart();
|
||||||
killerMoves = {};
|
killerMoves = {};
|
||||||
ss = {};
|
ss = {};
|
||||||
positionHistory.resize(1000);
|
positionHistory.resize(1000);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void CopyLearningFrom(const SearchContext& other) {
|
||||||
|
history = other.history;
|
||||||
|
conthist = other.conthist;
|
||||||
|
capthist = other.capthist;
|
||||||
|
killerMoves = other.killerMoves;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
bool SEE(Board& board, Move& move, int threshold);
|
bool SEE(Board& board, Move& move, int threshold);
|
||||||
@@ -168,7 +295,9 @@ SearchResults SearchPosition(Board &board, SearchParams params, SearchContext* c
|
|||||||
|
|
||||||
bool IsDraw(Board &board, SearchContext* ctx);
|
bool IsDraw(Board &board, SearchContext* ctx);
|
||||||
|
|
||||||
void ListScores(Board &board, SearchContext* ctx);
|
void PrintSearchInfo(Board& board, SearchContext* ctx, SearchResults& results, int depth, int elapsed);
|
||||||
|
|
||||||
|
void PrintSearchHeader();
|
||||||
|
|
||||||
int MoveEstimatedValue(Board& board, Move& move);
|
int MoveEstimatedValue(Board& board, Move& move);
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,940 @@
|
|||||||
|
//!
|
||||||
|
//! termcolor
|
||||||
|
//! ~~~~~~~~~
|
||||||
|
//!
|
||||||
|
//! termcolor is a header-only c++ library for printing colored messages
|
||||||
|
//! to the terminal. Written just for fun with a help of the Force.
|
||||||
|
//!
|
||||||
|
//! :copyright: (c) 2013 by Ihor Kalnytskyi
|
||||||
|
//! :license: BSD, see LICENSE for details
|
||||||
|
//!
|
||||||
|
|
||||||
|
#ifndef TERMCOLOR_HPP_
|
||||||
|
#define TERMCOLOR_HPP_
|
||||||
|
|
||||||
|
#include <cstdint>
|
||||||
|
#include <iostream>
|
||||||
|
|
||||||
|
// Detect target's platform and set some macros in order to wrap platform
|
||||||
|
// specific code this library depends on.
|
||||||
|
#if defined(_WIN32) || defined(_WIN64)
|
||||||
|
# define TERMCOLOR_TARGET_WINDOWS
|
||||||
|
#elif defined(__unix__) || defined(__unix) || (defined(__APPLE__) && defined(__MACH__))
|
||||||
|
# define TERMCOLOR_TARGET_POSIX
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// If implementation has not been explicitly set, try to choose one based on
|
||||||
|
// target platform.
|
||||||
|
#if !defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES) && !defined(TERMCOLOR_USE_WINDOWS_API) && !defined(TERMCOLOR_USE_NOOP)
|
||||||
|
# if defined(TERMCOLOR_TARGET_POSIX)
|
||||||
|
# define TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES
|
||||||
|
# define TERMCOLOR_AUTODETECTED_IMPLEMENTATION
|
||||||
|
# elif defined(TERMCOLOR_TARGET_WINDOWS)
|
||||||
|
# define TERMCOLOR_USE_WINDOWS_API
|
||||||
|
# define TERMCOLOR_AUTODETECTED_IMPLEMENTATION
|
||||||
|
# endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// These headers provide isatty()/fileno() functions, which are used for
|
||||||
|
// testing whether a standard stream refers to the terminal.
|
||||||
|
#if defined(TERMCOLOR_TARGET_POSIX)
|
||||||
|
# include <unistd.h>
|
||||||
|
#elif defined(TERMCOLOR_TARGET_WINDOWS)
|
||||||
|
# include <io.h>
|
||||||
|
# include <windows.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
|
||||||
|
namespace termcolor
|
||||||
|
{
|
||||||
|
// Forward declaration of the `_internal` namespace.
|
||||||
|
// All comments are below.
|
||||||
|
namespace _internal
|
||||||
|
{
|
||||||
|
inline int colorize_index();
|
||||||
|
inline FILE* get_standard_stream(const std::ostream& stream);
|
||||||
|
inline FILE* get_standard_stream(const std::wostream& stream);
|
||||||
|
template <typename CharT>
|
||||||
|
bool is_colorized(std::basic_ostream<CharT>& stream);
|
||||||
|
template <typename CharT>
|
||||||
|
bool is_atty(const std::basic_ostream<CharT>& stream);
|
||||||
|
|
||||||
|
#if defined(TERMCOLOR_TARGET_WINDOWS)
|
||||||
|
template <typename CharT>
|
||||||
|
void win_change_attributes(std::basic_ostream<CharT>& stream, int foreground, int background = -1);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& colorize(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
stream.iword(_internal::colorize_index()) = 1L;
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& nocolorize(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
stream.iword(_internal::colorize_index()) = 0L;
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& reset(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[00m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1, -1);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& bold(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[1m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& dark(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[2m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& italic(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[3m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& underline(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[4m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1, COMMON_LVB_UNDERSCORE);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& blink(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[5m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& reverse(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[7m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& concealed(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[8m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& crossed(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[9m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <uint8_t code, typename CharT>
|
||||||
|
std::basic_ostream<CharT>& color(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[38;5;" << +code << "m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <uint8_t code, typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_color(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[48;5;" << +code << "m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <uint8_t r, uint8_t g, uint8_t b, typename CharT>
|
||||||
|
std::basic_ostream<CharT>& color(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[38;2;" << +r << ";" << +g << ";" << +b << "m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <uint8_t r, uint8_t g, uint8_t b, typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_color(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[48;2;" << +r << ";" << +g << ";" << +b << "m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& grey(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[30m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream,
|
||||||
|
0 // grey (black)
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& red(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[31m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream,
|
||||||
|
FOREGROUND_RED
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& green(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[32m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream,
|
||||||
|
FOREGROUND_GREEN
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& yellow(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[33m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream,
|
||||||
|
FOREGROUND_GREEN | FOREGROUND_RED
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& blue(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[34m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream,
|
||||||
|
FOREGROUND_BLUE
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& magenta(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[35m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream,
|
||||||
|
FOREGROUND_BLUE | FOREGROUND_RED
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& cyan(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[36m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream,
|
||||||
|
FOREGROUND_BLUE | FOREGROUND_GREEN
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& white(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[37m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream,
|
||||||
|
FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& bright_grey(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[90m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream,
|
||||||
|
0 | FOREGROUND_INTENSITY // grey (black)
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& bright_red(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[91m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream,
|
||||||
|
FOREGROUND_RED | FOREGROUND_INTENSITY
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& bright_green(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[92m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream,
|
||||||
|
FOREGROUND_GREEN | FOREGROUND_INTENSITY
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& bright_yellow(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[93m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream,
|
||||||
|
FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& bright_blue(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[94m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream,
|
||||||
|
FOREGROUND_BLUE | FOREGROUND_INTENSITY
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& bright_magenta(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[95m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream,
|
||||||
|
FOREGROUND_BLUE | FOREGROUND_RED | FOREGROUND_INTENSITY
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& bright_cyan(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[96m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream,
|
||||||
|
FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_INTENSITY
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& bright_white(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[97m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream,
|
||||||
|
FOREGROUND_BLUE | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_INTENSITY
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_grey(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[40m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1,
|
||||||
|
0 // grey (black)
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_red(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[41m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1,
|
||||||
|
BACKGROUND_RED
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_green(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[42m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1,
|
||||||
|
BACKGROUND_GREEN
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_yellow(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[43m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1,
|
||||||
|
BACKGROUND_GREEN | BACKGROUND_RED
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_blue(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[44m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1,
|
||||||
|
BACKGROUND_BLUE
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_magenta(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[45m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1,
|
||||||
|
BACKGROUND_BLUE | BACKGROUND_RED
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_cyan(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[46m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1,
|
||||||
|
BACKGROUND_GREEN | BACKGROUND_BLUE
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_white(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[47m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1,
|
||||||
|
BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_RED
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_bright_grey(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[100m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1,
|
||||||
|
0 | BACKGROUND_INTENSITY // grey (black)
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_bright_red(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[101m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1,
|
||||||
|
BACKGROUND_RED | BACKGROUND_INTENSITY
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_bright_green(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[102m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1,
|
||||||
|
BACKGROUND_GREEN | BACKGROUND_INTENSITY
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_bright_yellow(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[103m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1,
|
||||||
|
BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_INTENSITY
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_bright_blue(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[104m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1,
|
||||||
|
BACKGROUND_BLUE | BACKGROUND_INTENSITY
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_bright_magenta(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[105m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1,
|
||||||
|
BACKGROUND_BLUE | BACKGROUND_RED | BACKGROUND_INTENSITY
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_bright_cyan(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[106m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1,
|
||||||
|
BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_INTENSITY
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename CharT>
|
||||||
|
std::basic_ostream<CharT>& on_bright_white(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
if (_internal::is_colorized(stream))
|
||||||
|
{
|
||||||
|
#if defined(TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES)
|
||||||
|
stream << "\033[107m";
|
||||||
|
#elif defined(TERMCOLOR_USE_WINDOWS_API)
|
||||||
|
_internal::win_change_attributes(stream, -1,
|
||||||
|
BACKGROUND_GREEN | BACKGROUND_BLUE | BACKGROUND_RED | BACKGROUND_INTENSITY
|
||||||
|
);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
return stream;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
//! Since C++ hasn't a way to hide something in the header from
|
||||||
|
//! the outer access, I have to introduce this namespace which
|
||||||
|
//! is used for internal purpose and should't be access from
|
||||||
|
//! the user code.
|
||||||
|
namespace _internal
|
||||||
|
{
|
||||||
|
// An index to be used to access a private storage of I/O streams. See
|
||||||
|
// colorize / nocolorize I/O manipulators for details. Due to the fact
|
||||||
|
// that static variables ain't shared between translation units, inline
|
||||||
|
// function with local static variable is used to do the trick and share
|
||||||
|
// the variable value between translation units.
|
||||||
|
inline int colorize_index()
|
||||||
|
{
|
||||||
|
static int colorize_index = std::ios_base::xalloc();
|
||||||
|
return colorize_index;
|
||||||
|
}
|
||||||
|
|
||||||
|
//! Since C++ hasn't a true way to extract stream handler
|
||||||
|
//! from the a given `std::ostream` object, I have to write
|
||||||
|
//! this kind of hack.
|
||||||
|
inline
|
||||||
|
FILE* get_standard_stream(const std::ostream& stream)
|
||||||
|
{
|
||||||
|
if (&stream == &std::cout)
|
||||||
|
return stdout;
|
||||||
|
else if (&stream == &std::cerr || &stream == &std::clog)
|
||||||
|
return stderr;
|
||||||
|
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
//! Since C++ hasn't a true way to extract stream handler
|
||||||
|
//! from the a given `std::wostream` object, I have to write
|
||||||
|
//! this kind of hack.
|
||||||
|
inline
|
||||||
|
FILE* get_standard_stream(const std::wostream& stream)
|
||||||
|
{
|
||||||
|
if (&stream == &std::wcout)
|
||||||
|
return stdout;
|
||||||
|
else if (&stream == &std::wcerr || &stream == &std::wclog)
|
||||||
|
return stderr;
|
||||||
|
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Say whether a given stream should be colorized or not. It's always
|
||||||
|
// true for ATTY streams and may be true for streams marked with
|
||||||
|
// colorize flag.
|
||||||
|
template <typename CharT>
|
||||||
|
bool is_colorized(std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
return is_atty(stream) || static_cast<bool>(stream.iword(colorize_index()));
|
||||||
|
}
|
||||||
|
|
||||||
|
//! Test whether a given `std::ostream` object refers to
|
||||||
|
//! a terminal.
|
||||||
|
template <typename CharT>
|
||||||
|
bool is_atty(const std::basic_ostream<CharT>& stream)
|
||||||
|
{
|
||||||
|
FILE* std_stream = get_standard_stream(stream);
|
||||||
|
|
||||||
|
// Unfortunately, fileno() ends with segmentation fault
|
||||||
|
// if invalid file descriptor is passed. So we need to
|
||||||
|
// handle this case gracefully and assume it's not a tty
|
||||||
|
// if standard stream is not detected, and 0 is returned.
|
||||||
|
if (!std_stream)
|
||||||
|
return false;
|
||||||
|
|
||||||
|
#if defined(TERMCOLOR_TARGET_POSIX)
|
||||||
|
return ::isatty(fileno(std_stream));
|
||||||
|
#elif defined(TERMCOLOR_TARGET_WINDOWS)
|
||||||
|
return ::_isatty(_fileno(std_stream));
|
||||||
|
#else
|
||||||
|
return false;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
#if defined(TERMCOLOR_TARGET_WINDOWS)
|
||||||
|
|
||||||
|
//! same hack as used in get_standard_stream function, but for Windows with `std::ostream`
|
||||||
|
inline HANDLE get_terminal_handle(std::ostream& stream)
|
||||||
|
{
|
||||||
|
if (&stream == &std::cout)
|
||||||
|
return GetStdHandle(STD_OUTPUT_HANDLE);
|
||||||
|
else if (&stream == &std::cerr || &stream == &std::clog)
|
||||||
|
return GetStdHandle(STD_ERROR_HANDLE);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
//! same hack as used in get_standard_stream function, but for Windows with `std::wostream`
|
||||||
|
inline HANDLE get_terminal_handle(std::wostream& stream)
|
||||||
|
{
|
||||||
|
if (&stream == &std::wcout)
|
||||||
|
return GetStdHandle(STD_OUTPUT_HANDLE);
|
||||||
|
else if (&stream == &std::wcerr || &stream == &std::wclog)
|
||||||
|
return GetStdHandle(STD_ERROR_HANDLE);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
//! Change Windows Terminal colors attribute. If some
|
||||||
|
//! parameter is `-1` then attribute won't changed.
|
||||||
|
template <typename CharT>
|
||||||
|
void win_change_attributes(std::basic_ostream<CharT>& stream, int foreground, int background)
|
||||||
|
{
|
||||||
|
// yeah, i know.. it's ugly, it's windows.
|
||||||
|
static WORD defaultAttributes = 0;
|
||||||
|
|
||||||
|
// Windows doesn't have ANSI escape sequences and so we use special
|
||||||
|
// API to change Terminal output color. That means we can't
|
||||||
|
// manipulate colors by means of "std::stringstream" and hence
|
||||||
|
// should do nothing in this case.
|
||||||
|
if (!_internal::is_atty(stream))
|
||||||
|
return;
|
||||||
|
|
||||||
|
// get terminal handle
|
||||||
|
HANDLE hTerminal = INVALID_HANDLE_VALUE;
|
||||||
|
hTerminal = get_terminal_handle(stream);
|
||||||
|
|
||||||
|
// save default terminal attributes if it unsaved
|
||||||
|
if (!defaultAttributes)
|
||||||
|
{
|
||||||
|
CONSOLE_SCREEN_BUFFER_INFO info;
|
||||||
|
if (!GetConsoleScreenBufferInfo(hTerminal, &info))
|
||||||
|
return;
|
||||||
|
defaultAttributes = info.wAttributes;
|
||||||
|
}
|
||||||
|
|
||||||
|
// restore all default settings
|
||||||
|
if (foreground == -1 && background == -1)
|
||||||
|
{
|
||||||
|
SetConsoleTextAttribute(hTerminal, defaultAttributes);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// get current settings
|
||||||
|
CONSOLE_SCREEN_BUFFER_INFO info;
|
||||||
|
if (!GetConsoleScreenBufferInfo(hTerminal, &info))
|
||||||
|
return;
|
||||||
|
|
||||||
|
if (foreground != -1)
|
||||||
|
{
|
||||||
|
info.wAttributes &= ~(info.wAttributes & 0x0F);
|
||||||
|
info.wAttributes |= static_cast<WORD>(foreground);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (background != -1)
|
||||||
|
{
|
||||||
|
info.wAttributes &= ~(info.wAttributes & 0xF0);
|
||||||
|
info.wAttributes |= static_cast<WORD>(background);
|
||||||
|
}
|
||||||
|
|
||||||
|
SetConsoleTextAttribute(hTerminal, info.wAttributes);
|
||||||
|
}
|
||||||
|
#endif // TERMCOLOR_TARGET_WINDOWS
|
||||||
|
|
||||||
|
} // namespace _internal
|
||||||
|
|
||||||
|
} // namespace termcolor
|
||||||
|
|
||||||
|
|
||||||
|
#undef TERMCOLOR_TARGET_POSIX
|
||||||
|
#undef TERMCOLOR_TARGET_WINDOWS
|
||||||
|
|
||||||
|
#if defined(TERMCOLOR_AUTODETECTED_IMPLEMENTATION)
|
||||||
|
# undef TERMCOLOR_USE_ANSI_ESCAPE_SEQUENCES
|
||||||
|
# undef TERMCOLOR_USE_WINDOWS_API
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#endif // TERMCOLOR_HPP_
|
||||||
+42
-3
@@ -1,11 +1,50 @@
|
|||||||
#include "tt.h"
|
#include "tt.h"
|
||||||
|
|
||||||
void TTable::WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move bestMove) {
|
TTable SharedTT;
|
||||||
TTEntry *current = &table[hashKey % table.size()];
|
|
||||||
|
void TTable::WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move bestMove, bool ttpv) {
|
||||||
|
TTBucket *bucket = &table[hashKey % table.size()];
|
||||||
|
TTEntry *current = nullptr;
|
||||||
|
|
||||||
|
if (bucket->depthPreferred && bucket->depthPreferred.hashKey == hashKey) {
|
||||||
|
current = &bucket->depthPreferred;
|
||||||
|
} else if (bucket->alwaysReplace && bucket->alwaysReplace.hashKey == hashKey) {
|
||||||
|
current = &bucket->alwaysReplace;
|
||||||
|
} else if (!bucket->alwaysReplace) {
|
||||||
|
current = &bucket->alwaysReplace;
|
||||||
|
} else if (!bucket->depthPreferred) {
|
||||||
|
current = &bucket->depthPreferred;
|
||||||
|
} else if (ttpv) {
|
||||||
|
current = &bucket->depthPreferred;
|
||||||
|
} else {
|
||||||
|
const int depthPreferredValue = GetReplacementValue(bucket->depthPreferred);
|
||||||
|
const int alwaysReplaceValue = GetReplacementValue(bucket->alwaysReplace);
|
||||||
|
|
||||||
|
if (depthPreferredValue <= alwaysReplaceValue) {
|
||||||
|
current = &bucket->depthPreferred;
|
||||||
|
} else {
|
||||||
|
current = &bucket->alwaysReplace;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const bool samePosition = current->hashKey == hashKey;
|
||||||
|
const bool exactBound = nodeType == PV;
|
||||||
|
const bool entryFromCurrentAge = current->age == age;
|
||||||
|
const int writeDepth = depth + 4 + ttpv * 2;
|
||||||
|
|
||||||
|
if (samePosition && !exactBound && entryFromCurrentAge && writeDepth <= current->depth) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
current->hashKey = hashKey;
|
current->hashKey = hashKey;
|
||||||
current->nodeType = nodeType;
|
current->nodeType = nodeType;
|
||||||
current->score = score;
|
current->score = score;
|
||||||
current->depth = depth;
|
current->depth = depth;
|
||||||
current->bestMove = bestMove;
|
|
||||||
|
if (bestMove || !samePosition) {
|
||||||
|
current->bestMove = bestMove;
|
||||||
|
}
|
||||||
|
|
||||||
|
current->age = age;
|
||||||
|
current->ttpv = ttpv;
|
||||||
}
|
}
|
||||||
+41
-14
@@ -26,6 +26,8 @@ public:
|
|||||||
Move bestMove = Move();
|
Move bestMove = Move();
|
||||||
uint8_t depth = 0;
|
uint8_t depth = 0;
|
||||||
uint8_t nodeType = 0;
|
uint8_t nodeType = 0;
|
||||||
|
uint8_t age = 0;
|
||||||
|
bool ttpv = false;
|
||||||
|
|
||||||
TTEntry() {}
|
TTEntry() {}
|
||||||
|
|
||||||
@@ -38,32 +40,57 @@ public:
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
class TTBucket {
|
||||||
|
public:
|
||||||
|
TTEntry depthPreferred;
|
||||||
|
TTEntry alwaysReplace;
|
||||||
|
};
|
||||||
|
|
||||||
// 1024 MB
|
// 1024 MB
|
||||||
constexpr U64 maxHash = (1024 * 1000000) / sizeof(TTEntry);
|
constexpr U64 maxHash = (1024 * 1000000) / sizeof(TTBucket);
|
||||||
// 8 MB
|
// 8 MB
|
||||||
constexpr U64 defaultHash = (8 * 1000000) / sizeof(TTEntry);
|
constexpr U64 defaultHash = (8 * 1000000) / sizeof(TTBucket);
|
||||||
|
|
||||||
constexpr int16_t invalidEntry = 11111;
|
constexpr int16_t invalidEntry = 11111;
|
||||||
|
|
||||||
class TTable {
|
class TTable {
|
||||||
private:
|
private:
|
||||||
std::vector<TTEntry> table;
|
std::vector<TTBucket> table;
|
||||||
|
|
||||||
|
uint8_t age = 0;
|
||||||
|
|
||||||
|
int GetReplacementValue(const TTEntry& entry) const {
|
||||||
|
const int ageDelta = uint8_t(age - entry.age);
|
||||||
|
return entry.depth - ageDelta * 4 + entry.ttpv * 2;
|
||||||
|
}
|
||||||
public:
|
public:
|
||||||
TTable() : table(defaultHash) {};
|
TTable() : table(defaultHash) {};
|
||||||
|
|
||||||
void Resize(U64 size) {
|
void Resize(U64 size) {
|
||||||
table.resize(size);
|
table.assign(size, {});
|
||||||
}
|
}
|
||||||
|
|
||||||
void Clear() {
|
void Clear() {
|
||||||
U64 size = table.size();
|
std::fill(table.begin(), table.end(), TTBucket());
|
||||||
table.clear();
|
|
||||||
table.resize(size);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
TTEntry GetRawEntry(U64 &hashKey) {
|
void PrefetchEntry(U64 &hashKey) {
|
||||||
TTEntry *current = &table[hashKey % table.size()];
|
__builtin_prefetch(&table[hashKey % table.size()]);
|
||||||
return *current;
|
}
|
||||||
|
|
||||||
|
void IncreaseAge() {
|
||||||
|
age++;
|
||||||
|
}
|
||||||
|
|
||||||
|
TTEntry GetEntry(U64 &hashKey) {
|
||||||
|
TTBucket *current = &table[hashKey % table.size()];
|
||||||
|
if (current->depthPreferred.hashKey == hashKey) {
|
||||||
|
return current->depthPreferred;
|
||||||
|
} else if (current->alwaysReplace.hashKey == hashKey) {
|
||||||
|
return current->alwaysReplace;
|
||||||
|
}
|
||||||
|
|
||||||
|
return TTEntry();
|
||||||
}
|
}
|
||||||
|
|
||||||
// returns used space per mill
|
// returns used space per mill
|
||||||
@@ -71,13 +98,13 @@ public:
|
|||||||
int count = 0;
|
int count = 0;
|
||||||
|
|
||||||
for (int i = 0; i < 1000; i++) {
|
for (int i = 0; i < 1000; i++) {
|
||||||
if (table[i]) count++;
|
if (table[i].depthPreferred || table[i].alwaysReplace) count++;
|
||||||
}
|
}
|
||||||
|
|
||||||
return count;
|
return count;
|
||||||
}
|
}
|
||||||
|
|
||||||
TTEntry ReadEntry(U64 &hashKey, int depth, int alpha, int beta);
|
void WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move bestMove, bool ttpv);
|
||||||
|
|
||||||
void WriteEntry(U64 &hashKey, int depth, int score, int nodeType, Move besteMove);
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
extern TTable SharedTT;
|
||||||
@@ -0,0 +1,120 @@
|
|||||||
|
#pragma once
|
||||||
|
#include <algorithm>
|
||||||
|
#include <iostream>
|
||||||
|
|
||||||
|
//#define TUNING
|
||||||
|
|
||||||
|
#define AUTO_STEP(min_val, max_val) ((max_val - min_val) / 20.0)
|
||||||
|
#define AUTO_R_END_INT(min_val, max_val) \
|
||||||
|
(0.002 / (std::min(0.5, static_cast<double>(AUTO_STEP(min_val, max_val))) / 0.5))
|
||||||
|
#define AUTO_R_END_FLOAT 0.002
|
||||||
|
|
||||||
|
#define TUNABLE_LIST \
|
||||||
|
X_DOUBLE(lmrBaseQuiet, 1.1029723689888005, 0.6, 1.6) \
|
||||||
|
X_DOUBLE(lmrDivisorQuiet, 2.3063513397139945, 1.6, 3.6) \
|
||||||
|
X_DOUBLE(lmrBaseNoisy, 0.451805556082857, 0.1, 1.1) \
|
||||||
|
X_DOUBLE(lmrDivisorNoisy, 3.1355330830404338, 2.0, 4.5) \
|
||||||
|
X_INT(lmrCutnode, 2005, 1024, 3072) \
|
||||||
|
X_INT(lmrIsPV, 982, 256, 2048) \
|
||||||
|
X_INT(lmrTTPV, 936, 256, 2048) \
|
||||||
|
X_INT(lmrHistoryDivisor, 8377, 4096, 16384) \
|
||||||
|
X_INT(lmrImproving, 1131, 256, 2048) \
|
||||||
|
X_INT(lmrCorrplexity, 830, 256, 2048) \
|
||||||
|
X_INT(lmrTTPVFailLow, 913, 256, 2048) \
|
||||||
|
X_INT(lmrDeeperBase, 46, 0, 96) \
|
||||||
|
X_INT(rfpBase, 21, 0, 100) \
|
||||||
|
X_INT(rfpMargin, 97, 50, 200) \
|
||||||
|
X_INT(fpMargin, 86, 50, 200) \
|
||||||
|
X_INT(qsFPMargin, 100, 50, 200) \
|
||||||
|
X_INT(probcutBetaMargin, 190, 100, 300) \
|
||||||
|
X_INT(razoringScalar, 195, 80, 320) \
|
||||||
|
X_INT(doubleExtMargin, 32, 8, 64) \
|
||||||
|
X_INT(seeQuietThreshold, -81, -160, 0) \
|
||||||
|
X_INT(seeNoisyThreshold, -32, -120, 40) \
|
||||||
|
X_INT(aspInitialDelta, 26, 8, 96) \
|
||||||
|
X_INT(nmpBetaMargin, 25, 8, 96) \
|
||||||
|
X_INT(seePawnValue, 98, 80, 140) \
|
||||||
|
X_INT(seeKnightValue, 301, 240, 420) \
|
||||||
|
X_INT(seeBishopValue, 346, 250, 450) \
|
||||||
|
X_INT(seeRookValue, 507, 400, 700) \
|
||||||
|
X_INT(seeQueenValue, 924, 700, 1300) \
|
||||||
|
X_INT(seeQsThreshold, -13, -120, 120) \
|
||||||
|
X_INT(seeOrderingThreshold, -102, -200, 0) \
|
||||||
|
X_INT(ldseMargin, 26, 0, 96) \
|
||||||
|
X_INT(noisyScoreScale, 32, 0, 96) \
|
||||||
|
X_INT(historyBonusMultiplier, 306, 280, 320) \
|
||||||
|
X_INT(historyBonusSub, 252, 235, 265) \
|
||||||
|
X_INT(historyMalusMultiplier, 301, 280, 320) \
|
||||||
|
X_INT(historyMalusSub, 250, 235, 265) \
|
||||||
|
X_INT(contHistoryBonusMultiplier, 300, 280, 320) \
|
||||||
|
X_INT(contHistoryBonusSub, 252, 235, 265) \
|
||||||
|
X_INT(contHistoryMalusMultiplier, 300, 280, 320) \
|
||||||
|
X_INT(contHistoryMalusSub, 249, 235, 265) \
|
||||||
|
X_INT(captHistoryBonusMultiplier, 302, 280, 320) \
|
||||||
|
X_INT(captHistoryBonusSub, 249, 235, 265) \
|
||||||
|
X_INT(captHistoryMalusMultiplier, 300, 280, 320) \
|
||||||
|
X_INT(captHistoryMalusSub, 249, 235, 265) \
|
||||||
|
X_INT(fiftyMoveScaleBase, 200, 100, 400)
|
||||||
|
|
||||||
|
#ifdef TUNING
|
||||||
|
#define X_DOUBLE(name, default_val, min_val, max_val) \
|
||||||
|
inline double name = default_val; \
|
||||||
|
constexpr double name##_step = AUTO_STEP(min_val, max_val);
|
||||||
|
#define X_INT(name, default_val, min_val, max_val) \
|
||||||
|
inline int name = default_val; \
|
||||||
|
constexpr double name##_step = AUTO_STEP(min_val, max_val);
|
||||||
|
#else
|
||||||
|
#define X_DOUBLE(name, default_val, min_val, max_val) \
|
||||||
|
constexpr double name = default_val; \
|
||||||
|
constexpr double name##_step = AUTO_STEP(min_val, max_val);
|
||||||
|
#define X_INT(name, default_val, min_val, max_val) \
|
||||||
|
constexpr int name = default_val; \
|
||||||
|
constexpr double name##_step = AUTO_STEP(min_val, max_val);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
TUNABLE_LIST
|
||||||
|
|
||||||
|
#undef X_DOUBLE
|
||||||
|
#undef X_INT
|
||||||
|
|
||||||
|
inline void PrintTunables() {
|
||||||
|
#define X_DOUBLE(name, default_val, min_val, max_val) \
|
||||||
|
std::cout << #name << ", float, " << name \
|
||||||
|
<< ", " << min_val \
|
||||||
|
<< ", " << max_val \
|
||||||
|
<< ", " << name##_step \
|
||||||
|
<< ", " << AUTO_R_END_FLOAT << std::endl;
|
||||||
|
|
||||||
|
#define X_INT(name, default_val, min_val, max_val) \
|
||||||
|
std::cout << #name << ", int, " << name \
|
||||||
|
<< ", " << min_val \
|
||||||
|
<< ", " << max_val \
|
||||||
|
<< ", " << name##_step \
|
||||||
|
<< ", " << AUTO_R_END_INT(min_val, max_val) << std::endl;
|
||||||
|
|
||||||
|
TUNABLE_LIST
|
||||||
|
|
||||||
|
#undef X_DOUBLE
|
||||||
|
#undef X_INT
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void PrintTunablesUCI() {
|
||||||
|
#define X_DOUBLE(name, default_val, min_val, max_val) \
|
||||||
|
std::cout << "option name " #name \
|
||||||
|
<< " type string default " << name \
|
||||||
|
<< " min " << min_val \
|
||||||
|
<< " max " << max_val \
|
||||||
|
<< std::endl;
|
||||||
|
|
||||||
|
#define X_INT(name, default_val, min_val, max_val) \
|
||||||
|
std::cout << "option name " #name \
|
||||||
|
<< " type spin default " << name \
|
||||||
|
<< " min " << min_val \
|
||||||
|
<< " max " << max_val \
|
||||||
|
<< std::endl;
|
||||||
|
|
||||||
|
TUNABLE_LIST
|
||||||
|
|
||||||
|
#undef X_DOUBLE
|
||||||
|
#undef X_INT
|
||||||
|
}
|
||||||
+344
-55
@@ -4,6 +4,7 @@
|
|||||||
#include <string>
|
#include <string>
|
||||||
#include <tuple>
|
#include <tuple>
|
||||||
#include <memory>
|
#include <memory>
|
||||||
|
#include <algorithm>
|
||||||
#include "types.h"
|
#include "types.h"
|
||||||
#include "movegen.h"
|
#include "movegen.h"
|
||||||
#include "search.h"
|
#include "search.h"
|
||||||
@@ -11,6 +12,8 @@
|
|||||||
#include "perft.h"
|
#include "perft.h"
|
||||||
#include "utils.h"
|
#include "utils.h"
|
||||||
#include "datagen.h"
|
#include "datagen.h"
|
||||||
|
#include "tunables.h"
|
||||||
|
#include "termcolor.hpp"
|
||||||
|
|
||||||
// OS-dependent threading includes
|
// OS-dependent threading includes
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
@@ -18,10 +21,109 @@
|
|||||||
#else
|
#else
|
||||||
#include <pthread.h>
|
#include <pthread.h>
|
||||||
#endif
|
#endif
|
||||||
|
#include <mutex>
|
||||||
|
#include <atomic>
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
constexpr size_t DefaultPositionHistorySize = 1000;
|
||||||
|
|
||||||
|
static void EnsurePositionHistory(SEARCH::SearchContext* ctx, int positionIndex) {
|
||||||
|
if (positionIndex >= static_cast<int>(ctx->positionHistory.size())) {
|
||||||
|
ctx->positionHistory.resize(positionIndex + 100);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static void ResetPositionHistory(SEARCH::SearchContext* ctx, const Board& board) {
|
||||||
|
const size_t historySize = std::max(DefaultPositionHistorySize, static_cast<size_t>(board.positionIndex + 100));
|
||||||
|
ctx->positionHistory.assign(historySize, 0);
|
||||||
|
ctx->positionHistory[board.positionIndex] = board.hashKey;
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef _WIN32
|
||||||
|
static std::vector<std::thread> searchThreads;
|
||||||
|
#else
|
||||||
|
static std::vector<pthread_t> searchThreads;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
static std::vector<SEARCH::RootVote> rootVotes;
|
||||||
|
static std::mutex voteMutex;
|
||||||
|
static std::atomic<bool> votePrinted{false};
|
||||||
|
|
||||||
|
static void PrintVotedBestmove(Move move) {
|
||||||
|
if (UCIEnabled) {
|
||||||
|
std::cout << "bestmove ";
|
||||||
|
if (!move)
|
||||||
|
std::cout << "0000";
|
||||||
|
else
|
||||||
|
move.PrintMove();
|
||||||
|
std::cout << std::endl;
|
||||||
|
} else {
|
||||||
|
std::cout << termcolor::color<244> << "bestmove " << termcolor::reset;
|
||||||
|
if (!move) {
|
||||||
|
std::cout << "0000" << std::endl;
|
||||||
|
} else {
|
||||||
|
std::cout << termcolor::bold << termcolor::bright_green;
|
||||||
|
move.PrintMove();
|
||||||
|
std::cout << termcolor::reset << std::endl;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
static SearchResults GetVotedResult(const SearchResults& fallback) {
|
||||||
|
std::lock_guard<std::mutex> lock(voteMutex);
|
||||||
|
SearchResults voted = SEARCH::VoteRootMoves(rootVotes);
|
||||||
|
Move m = voted.bestMove;
|
||||||
|
if (uint16_t(m) == 0)
|
||||||
|
return fallback;
|
||||||
|
return voted;
|
||||||
|
}
|
||||||
|
|
||||||
|
static bool TryPrintVotedBestmove(const SearchResults& fallback) {
|
||||||
|
if (votePrinted.exchange(true, std::memory_order_acq_rel))
|
||||||
|
return false;
|
||||||
|
SearchResults voted = GetVotedResult(fallback);
|
||||||
|
PrintVotedBestmove(voted.bestMove);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
static void JoinSearchThreads() {
|
||||||
|
#ifdef _WIN32
|
||||||
|
for (auto& thread : searchThreads) {
|
||||||
|
if (thread.joinable()) {
|
||||||
|
thread.join();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#else
|
||||||
|
for (pthread_t& thread : searchThreads) {
|
||||||
|
pthread_join(thread, nullptr);
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
searchThreads.clear();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void StopSearchThreads() {
|
||||||
|
searchStopped.store(true, std::memory_order_relaxed);
|
||||||
|
JoinSearchThreads();
|
||||||
|
}
|
||||||
|
|
||||||
|
static void StopSearchThreadsAndVote() {
|
||||||
|
if (searchThreads.empty()) {
|
||||||
|
searchStopped.store(true, std::memory_order_relaxed);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
searchStopped.store(true, std::memory_order_relaxed);
|
||||||
|
JoinSearchThreads();
|
||||||
|
TryPrintVotedBestmove(SearchResults(0, Move()));
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
static void ParsePosition(Board &board, std::string_view command, SEARCH::SearchContext* ctx) {
|
static void ParsePosition(Board &board, std::string_view command, SEARCH::SearchContext* ctx) {
|
||||||
if (command.find("startpos") != std::string::npos) {
|
if (command.find("startpos") != std::string::npos) {
|
||||||
board.SetByFen(StartingFen);
|
board.SetByFen(StartingFen);
|
||||||
|
ResetPositionHistory(ctx, board);
|
||||||
}
|
}
|
||||||
|
|
||||||
int fenIndex = command.find("fen");
|
int fenIndex = command.find("fen");
|
||||||
@@ -33,6 +135,8 @@ static void ParsePosition(Board &board, std::string_view command, SEARCH::Search
|
|||||||
} else {
|
} else {
|
||||||
board.SetByFen(command.substr(fenIndex + 4, command.length() - (fenIndex + 3)));
|
board.SetByFen(command.substr(fenIndex + 4, command.length() - (fenIndex + 3)));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
ResetPositionHistory(ctx, board);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (movesIndex != std::string::npos) {
|
if (movesIndex != std::string::npos) {
|
||||||
@@ -40,92 +144,156 @@ static void ParsePosition(Board &board, std::string_view command, SEARCH::Search
|
|||||||
|
|
||||||
for (std::string_view move : moves) {
|
for (std::string_view move : moves) {
|
||||||
board.MakeMove(UTILS::parseMove(board, move));
|
board.MakeMove(UTILS::parseMove(board, move));
|
||||||
|
EnsurePositionHistory(ctx, board.positionIndex);
|
||||||
ctx->positionHistory[board.positionIndex] = board.hashKey;
|
ctx->positionHistory[board.positionIndex] = board.hashKey;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
MOVEGEN::GenerateMoves<All>(board);
|
MOVEGEN::GenerateMoves<All>(board, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
static int ReadParam(std::string param, std::string &command) {
|
static double ReadParam(const std::string& param, const std::string &command) {
|
||||||
size_t pos = command.find(param);
|
size_t pos = command.find(param);
|
||||||
if (pos != std::string::npos) {
|
if (pos == std::string::npos)
|
||||||
pos += param.length() + 1;
|
return 0.0;
|
||||||
bool isNegative = false;
|
|
||||||
std::string result = "";
|
|
||||||
|
|
||||||
// Check for negative sign
|
pos += param.length() + 1; // skip "param "
|
||||||
if (pos < command.length() && command[pos] == '-') {
|
std::string result;
|
||||||
isNegative = true;
|
|
||||||
pos++;
|
// optional sign
|
||||||
|
if (pos < command.length() && (command[pos] == '-' || command[pos] == '+')) {
|
||||||
|
result += command[pos];
|
||||||
|
pos++;
|
||||||
|
}
|
||||||
|
|
||||||
|
// digits and optional decimal point
|
||||||
|
bool decimalSeen = false;
|
||||||
|
while (pos < command.length() && (std::isdigit(command[pos]) || command[pos] == '.')) {
|
||||||
|
if (command[pos] == '.') {
|
||||||
|
if (decimalSeen) break; // only one decimal point
|
||||||
|
decimalSeen = true;
|
||||||
}
|
}
|
||||||
|
result += command[pos++];
|
||||||
|
}
|
||||||
|
|
||||||
// Extract digits
|
if (!result.empty()) {
|
||||||
while (pos < command.length() && std::isdigit(command[pos])) {
|
try {
|
||||||
result += command[pos];
|
return std::stod(result);
|
||||||
pos++;
|
} catch (const std::out_of_range&) {
|
||||||
}
|
return (result[0] == '-') ? -1e308 : 1e308; // clamp to double range
|
||||||
|
} catch (const std::invalid_argument&) {
|
||||||
// Ensure result is not empty before calling stoi
|
return 0.0;
|
||||||
if (!result.empty()) {
|
|
||||||
int value = std::stoi(result);
|
|
||||||
return isNegative ? -value : value;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return 0;
|
return 0.0;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#ifdef _WIN32
|
#ifdef _WIN32
|
||||||
// Windows implementation using std::thread
|
// Windows implementation using std::thread
|
||||||
template <SEARCH::searchMode mode>
|
template <SEARCH::searchMode mode>
|
||||||
static void ThreadFunc(Board* board, SearchParams params, SEARCH::SearchContext* ctx) {
|
static void ThreadFunc(Board board, SearchParams params, SEARCH::SearchContext* ctx, SEARCH::SearchContext* master) {
|
||||||
SEARCH::SearchPosition<mode>(*board, params, ctx);
|
SearchResults results = SEARCH::SearchPosition<mode>(board, params, ctx);
|
||||||
|
int id = ctx->threadId;
|
||||||
|
if (id == 0) {
|
||||||
|
master->CopyLearningFrom(*ctx);
|
||||||
|
}
|
||||||
|
delete ctx;
|
||||||
|
if (id == 0) {
|
||||||
|
searchStopped.store(true, std::memory_order_relaxed);
|
||||||
|
TryPrintVotedBestmove(results);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchContext* ctx) {
|
static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchContext* ctx, int id) {
|
||||||
std::thread searchThread;
|
SEARCH::SearchContext* ctxCopy = new SEARCH::SearchContext(*ctx);
|
||||||
|
ctxCopy->threadId = id;
|
||||||
|
ctxCopy->voteTable = &rootVotes;
|
||||||
|
ctxCopy->voteMutex = &voteMutex;
|
||||||
|
if (id == 0)
|
||||||
|
ctxCopy->doPrint = true;
|
||||||
|
|
||||||
if (params.nodes) {
|
if (params.nodes) {
|
||||||
searchThread = std::thread(ThreadFunc<SEARCH::nodesMode>, &board, params, ctx);
|
searchThreads.emplace_back(ThreadFunc<SEARCH::nodesMode>, board, params, ctxCopy, ctx);
|
||||||
} else {
|
} else {
|
||||||
searchThread = std::thread(ThreadFunc<SEARCH::normal>, &board, params, ctx);
|
searchThreads.emplace_back(ThreadFunc<SEARCH::normal>, board, params, ctxCopy, ctx);
|
||||||
}
|
}
|
||||||
|
|
||||||
searchThread.detach();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#else
|
#else
|
||||||
// Unix/Linux implementation using pthread
|
// Unix/Linux implementation using pthread
|
||||||
template <SEARCH::searchMode mode>
|
template <SEARCH::searchMode mode>
|
||||||
static void* ThreadFunc(void* arg) {
|
static void* ThreadFunc(void* arg) {
|
||||||
auto* tup = static_cast<std::tuple<Board*, SearchParams, SEARCH::SearchContext*>*>(arg);
|
auto* tup = static_cast<std::tuple<Board, SearchParams, SEARCH::SearchContext*, SEARCH::SearchContext*>*>(arg);
|
||||||
SEARCH::SearchPosition<mode>(*std::get<0>(*tup), std::get<1>(*tup), std::get<2>(*tup));
|
SEARCH::SearchContext* ctx = std::get<2>(*tup);
|
||||||
|
SEARCH::SearchContext* master = std::get<3>(*tup);
|
||||||
|
SearchResults results = SEARCH::SearchPosition<mode>(std::get<0>(*tup), std::get<1>(*tup), ctx);
|
||||||
|
int id = ctx->threadId;
|
||||||
|
if (id == 0) {
|
||||||
|
master->CopyLearningFrom(*ctx);
|
||||||
|
}
|
||||||
|
delete ctx;
|
||||||
delete tup;
|
delete tup;
|
||||||
|
if (id == 0) {
|
||||||
|
searchStopped.store(true, std::memory_order_relaxed);
|
||||||
|
TryPrintVotedBestmove(results);
|
||||||
|
}
|
||||||
return nullptr;
|
return nullptr;
|
||||||
}
|
}
|
||||||
|
|
||||||
static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchContext* ctx) {
|
static void StartSearchThread(Board& board, SearchParams params, SEARCH::SearchContext* ctx, int id) {
|
||||||
pthread_attr_t attr;
|
pthread_attr_t attr;
|
||||||
pthread_attr_init(&attr);
|
pthread_attr_init(&attr);
|
||||||
pthread_attr_setstacksize(&attr, 8 * 1024 * 1024); // 8 MB stack
|
pthread_attr_setstacksize(&attr, 8 * 1024 * 1024); // 8 MB stack
|
||||||
|
|
||||||
|
SEARCH::SearchContext* ctxCopy = new SEARCH::SearchContext(*ctx);
|
||||||
|
ctxCopy->threadId = id;
|
||||||
|
ctxCopy->voteTable = &rootVotes;
|
||||||
|
ctxCopy->voteMutex = &voteMutex;
|
||||||
|
if (id == 0)
|
||||||
|
ctxCopy->doPrint = true;
|
||||||
|
|
||||||
pthread_t thread;
|
pthread_t thread;
|
||||||
|
int rc = 0;
|
||||||
|
|
||||||
if (params.nodes) {
|
if (params.nodes) {
|
||||||
auto* arg = new std::tuple<Board*, SearchParams, SEARCH::SearchContext*>(&board, params, ctx);
|
auto* arg = new std::tuple<Board, SearchParams, SEARCH::SearchContext*, SEARCH::SearchContext*>(board, params, ctxCopy, ctx);
|
||||||
pthread_create(&thread, &attr, ThreadFunc<SEARCH::nodesMode>, arg);
|
rc = pthread_create(&thread, &attr, ThreadFunc<SEARCH::nodesMode>, arg);
|
||||||
|
if (rc != 0) {
|
||||||
|
delete std::get<2>(*arg);
|
||||||
|
delete arg;
|
||||||
|
ctxCopy = nullptr;
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
auto* arg = new std::tuple<Board*, SearchParams, SEARCH::SearchContext*>(&board, params, ctx);
|
auto* arg = new std::tuple<Board, SearchParams, SEARCH::SearchContext*, SEARCH::SearchContext*>(board, params, ctxCopy, ctx);
|
||||||
pthread_create(&thread, &attr, ThreadFunc<SEARCH::normal>, arg);
|
rc = pthread_create(&thread, &attr, ThreadFunc<SEARCH::normal>, arg);
|
||||||
|
if (rc != 0) {
|
||||||
|
delete std::get<2>(*arg);
|
||||||
|
delete arg;
|
||||||
|
ctxCopy = nullptr;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pthread_attr_destroy(&attr);
|
pthread_attr_destroy(&attr);
|
||||||
pthread_detach(thread);
|
|
||||||
|
if (rc == 0) {
|
||||||
|
searchThreads.push_back(thread);
|
||||||
|
} else {
|
||||||
|
delete ctxCopy;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
static bool IsGoToken(const std::string &token) {
|
||||||
|
return token == "searchmoves" || token == "ponder" || token == "wtime" || token == "btime" || token == "winc" || token == "binc" || token == "movestogo" || token == "depth" || token == "nodes" || token == "mate" || token == "movetime" || token == "infinite";
|
||||||
|
}
|
||||||
|
|
||||||
static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext* ctx) {
|
static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext* ctx) {
|
||||||
|
StopSearchThreads();
|
||||||
|
searchStopped.store(false, std::memory_order_relaxed);
|
||||||
|
ctx->TT->IncreaseAge();
|
||||||
|
|
||||||
SearchParams params;
|
SearchParams params;
|
||||||
|
|
||||||
params.wtime = ReadParam("wtime", command);
|
params.wtime = ReadParam("wtime", command);
|
||||||
@@ -134,30 +302,143 @@ static void ParseGo(Board &board, std::string &command, SEARCH::SearchContext* c
|
|||||||
params.binc = ReadParam("binc", command);
|
params.binc = ReadParam("binc", command);
|
||||||
params.movesToGo = ReadParam("movestogo", command);
|
params.movesToGo = ReadParam("movestogo", command);
|
||||||
params.nodes = ReadParam("nodes", command);
|
params.nodes = ReadParam("nodes", command);
|
||||||
|
params.depth = ReadParam("depth", command);
|
||||||
|
params.mate = ReadParam("mate", command);
|
||||||
|
params.movetime = ReadParam("movetime", command);
|
||||||
|
|
||||||
if (command.find("movetime") != std::string::npos) {
|
if (params.depth < 0)
|
||||||
params.wtime = ReadParam("movetime", command);
|
params.depth = 0;
|
||||||
params.btime = ReadParam("movetime", command);
|
if (params.mate < 0)
|
||||||
} else if (command.find("infinite") != std::string::npos) {
|
params.mate = 0;
|
||||||
params.wtime = 99999999;
|
if (params.movetime < 0)
|
||||||
params.btime = 99999999;
|
params.movetime = 0;
|
||||||
|
if (params.nodes < 0)
|
||||||
|
params.nodes = 0;
|
||||||
|
if (params.depth > SEARCH::MAX_DEPTH)
|
||||||
|
params.depth = SEARCH::MAX_DEPTH;
|
||||||
|
if (params.mate * 2 > SEARCH::MAX_DEPTH)
|
||||||
|
params.mate = SEARCH::MAX_DEPTH / 2;
|
||||||
|
|
||||||
|
if (command.find("infinite") != std::string::npos)
|
||||||
|
params.infinite = true;
|
||||||
|
if (command.find("ponder") != std::string::npos)
|
||||||
|
params.infinite = true;
|
||||||
|
|
||||||
|
size_t searchmovesPos = command.find("searchmoves");
|
||||||
|
if (searchmovesPos != std::string::npos) {
|
||||||
|
std::vector<std::string> tokens = UTILS::split(command.substr(searchmovesPos + 11), ' ');
|
||||||
|
for (std::string &token : tokens) {
|
||||||
|
if (token.empty())
|
||||||
|
continue;
|
||||||
|
if (IsGoToken(token))
|
||||||
|
break;
|
||||||
|
if (token.size() < 4)
|
||||||
|
continue;
|
||||||
|
Move m = UTILS::parseMove(board, token);
|
||||||
|
if (m != 0)
|
||||||
|
params.searchMoves.push_back(m);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
StartSearchThread(board, params, ctx);
|
ctx->searchMoves = params.searchMoves;
|
||||||
|
|
||||||
|
int numThreads = threads;
|
||||||
|
if (numThreads < 1)
|
||||||
|
numThreads = 1;
|
||||||
|
if (numThreads > 512)
|
||||||
|
numThreads = 512;
|
||||||
|
|
||||||
|
{
|
||||||
|
std::lock_guard<std::mutex> lock(voteMutex);
|
||||||
|
rootVotes.assign(numThreads, SEARCH::RootVote());
|
||||||
|
}
|
||||||
|
votePrinted.store(false, std::memory_order_relaxed);
|
||||||
|
|
||||||
|
searchThreads.reserve(numThreads);
|
||||||
|
for (int i = 0; i < numThreads; i++) {
|
||||||
|
StartSearchThread(board, params, ctx, i);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static void SetOption(std::string &command, SEARCH::SearchContext* ctx) {
|
static void SetOption(std::string& command, SEARCH::SearchContext* ctx) {
|
||||||
|
StopSearchThreads();
|
||||||
|
|
||||||
if (command.find("Hash") != std::string::npos) {
|
if (command.find("Hash") != std::string::npos) {
|
||||||
U64 hashSize = (ReadParam("value", command) * 1000000) / sizeof(TTEntry);
|
U64 hashSize = (ReadParam("value", command) * 1000000ULL) / sizeof(TTEntry);
|
||||||
ctx->TT.Resize(hashSize);
|
ctx->TT->Resize(hashSize);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (command.find("Threads") != std::string::npos) {
|
||||||
|
threads = static_cast<int>(ReadParam("value", command));
|
||||||
|
if (threads < 1)
|
||||||
|
threads = 1;
|
||||||
|
if (threads > 512)
|
||||||
|
threads = 512;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (command.find("UCI_ShowWDL") != std::string::npos) {
|
||||||
|
UCIShowWDL = command.find("value true") != std::string::npos
|
||||||
|
|| command.find("value 1") != std::string::npos;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
#ifdef TUNING
|
||||||
|
|
||||||
|
size_t namePos = command.find("name");
|
||||||
|
if (namePos == std::string::npos)
|
||||||
|
return;
|
||||||
|
|
||||||
|
namePos += 5; // skip "name "
|
||||||
|
size_t valuePos = command.find(" value");
|
||||||
|
if (valuePos == std::string::npos)
|
||||||
|
return;
|
||||||
|
|
||||||
|
std::string name = command.substr(namePos, valuePos - namePos);
|
||||||
|
name.erase(0, name.find_first_not_of(' '));
|
||||||
|
name.erase(name.find_last_not_of(' ') + 1);
|
||||||
|
|
||||||
|
double rawValue = ReadParam("value", command);
|
||||||
|
|
||||||
|
#define X_DOUBLE(paramName, default_val, min_val, max_val) \
|
||||||
|
if (name == #paramName) { \
|
||||||
|
double v = rawValue; \
|
||||||
|
if (v < min_val) v = min_val; \
|
||||||
|
if (v > max_val) v = max_val; \
|
||||||
|
paramName = v; \
|
||||||
|
SEARCH::RefreshTunableCaches(); \
|
||||||
|
return; \
|
||||||
|
}
|
||||||
|
|
||||||
|
#define X_INT(paramName, default_val, min_val, max_val) \
|
||||||
|
if (name == #paramName) { \
|
||||||
|
int v = static_cast<int>(rawValue); \
|
||||||
|
if (v < min_val) v = min_val; \
|
||||||
|
if (v > max_val) v = max_val; \
|
||||||
|
paramName = v; \
|
||||||
|
SEARCH::RefreshTunableCaches(); \
|
||||||
|
return; \
|
||||||
|
}
|
||||||
|
|
||||||
|
TUNABLE_LIST
|
||||||
|
|
||||||
|
#undef X_DOUBLE
|
||||||
|
#undef X_INT
|
||||||
|
#endif
|
||||||
}
|
}
|
||||||
|
|
||||||
static void PrintEngineInfo() {
|
static void PrintEngineInfo() {
|
||||||
std::cout << "id name Eleanor v2.0" << std::endl;
|
std::cout << "id name Eleanor v" << EleanorVersion << std::endl;
|
||||||
std::cout << "id author rektdie" << 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 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;
|
std::cout << "option name Threads type spin default 1 min 1 max 512" << std::endl;
|
||||||
|
std::cout << "option name UCI_ShowWDL type check default false" << std::endl;
|
||||||
|
|
||||||
|
#ifdef TUNING
|
||||||
|
PrintTunablesUCI();
|
||||||
|
#endif
|
||||||
|
|
||||||
std::cout << "uciok" << std::endl;
|
std::cout << "uciok" << std::endl;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -185,41 +466,44 @@ void UCILoop(Board &board) {
|
|||||||
|
|
||||||
// parse UCI "ucinewgame" command
|
// parse UCI "ucinewgame" command
|
||||||
if (input.find("ucinewgame") != std::string::npos) {
|
if (input.find("ucinewgame") != std::string::npos) {
|
||||||
|
StopSearchThreads();
|
||||||
board.SetByFen(StartingFen);
|
board.SetByFen(StartingFen);
|
||||||
|
|
||||||
// Clearing
|
// Clearing
|
||||||
ctx->TT.Clear();
|
ctx->TT->Clear();
|
||||||
|
|
||||||
ctx->killerMoves = {};
|
ctx->killerMoves = {};
|
||||||
ctx->history.Clear();
|
ctx->history.Clear();
|
||||||
ctx->conthist.Clear();
|
ctx->conthist.Clear();
|
||||||
ctx->positionHistory = {};
|
ctx->corrhist.Clear();
|
||||||
|
ResetPositionHistory(ctx.get(), board);
|
||||||
ctx->ss = {};
|
ctx->ss = {};
|
||||||
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// parse UCI "go" command
|
// parse UCI "go" command
|
||||||
if (input.find("go") != std::string::npos) {
|
if (input == "go" || input.rfind("go ", 0) == 0) {
|
||||||
ParseGo(board, input, ctx.get());
|
ParseGo(board, input, ctx.get());
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// parse UCI "quit" command
|
// parse UCI "quit" command
|
||||||
if (input.find("quit") != std::string::npos) {
|
if (input.find("quit") != std::string::npos) {
|
||||||
|
StopSearchThreads();
|
||||||
// stop the loop
|
// stop the loop
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// parse UCI "stop" command
|
// parse UCI "stop" command
|
||||||
if (input.find("stop") != std::string::npos) {
|
if (input.find("stop") != std::string::npos) {
|
||||||
// stop the loop
|
StopSearchThreadsAndVote();
|
||||||
ctx->searchStopped = true;
|
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// parse UCI "uci" command
|
// parse UCI "uci" command
|
||||||
if (input.find("uci") != std::string::npos) {
|
if (input.find("uci") != std::string::npos) {
|
||||||
|
UCIEnabled = true;
|
||||||
// print engine info
|
// print engine info
|
||||||
PrintEngineInfo();
|
PrintEngineInfo();
|
||||||
continue;
|
continue;
|
||||||
@@ -252,7 +536,12 @@ void UCILoop(Board &board) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (input.find("nnue") != std::string::npos) {
|
if (input.find("nnue") != std::string::npos) {
|
||||||
board.PrintNNUE();
|
board.PrintNNUE(input.find("full") != std::string::npos);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.find("tunables") != std::string::npos) {
|
||||||
|
PrintTunables();
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,17 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
#include <atomic>
|
||||||
|
#include <string_view>
|
||||||
|
#include <vector>
|
||||||
#include "move.h"
|
#include "move.h"
|
||||||
#include "board.h"
|
#include "board.h"
|
||||||
|
|
||||||
|
inline bool UCIEnabled = false;
|
||||||
|
inline bool UCIShowWDL = false;
|
||||||
|
inline int threads = 1;
|
||||||
|
inline std::atomic<bool> searchStopped = false;
|
||||||
|
|
||||||
|
constexpr std::string_view EleanorVersion = "4.1";
|
||||||
|
|
||||||
class SearchParams {
|
class SearchParams {
|
||||||
public:
|
public:
|
||||||
int wtime = 0;
|
int wtime = 0;
|
||||||
@@ -10,6 +20,13 @@ public:
|
|||||||
int binc = 0;
|
int binc = 0;
|
||||||
int movesToGo = 0;
|
int movesToGo = 0;
|
||||||
int nodes = 0;
|
int nodes = 0;
|
||||||
|
int depth = 0;
|
||||||
|
int mate = 0;
|
||||||
|
int movetime = 0;
|
||||||
|
bool infinite = false;
|
||||||
|
std::vector<Move> searchMoves;
|
||||||
|
|
||||||
|
int threads = 1;
|
||||||
|
|
||||||
SearchParams(){}
|
SearchParams(){}
|
||||||
};
|
};
|
||||||
|
|||||||
+1
-1
@@ -111,7 +111,7 @@ int parseSquare(std::string_view str) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Move parseMove(Board &board, std::string_view str) {
|
Move parseMove(Board &board, std::string_view str) {
|
||||||
MOVEGEN::GenerateMoves<All>(board);
|
MOVEGEN::GenerateMoves<All>(board, true);
|
||||||
|
|
||||||
int from = parseSquare(str.substr(0, 2));
|
int from = parseSquare(str.substr(0, 2));
|
||||||
int to = parseSquare(str.substr(2, 2));
|
int to = parseSquare(str.substr(2, 2));
|
||||||
|
|||||||
@@ -0,0 +1,71 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <cmath>
|
||||||
|
|
||||||
|
#include "board.h"
|
||||||
|
|
||||||
|
struct WinRateParams {
|
||||||
|
double a;
|
||||||
|
double b;
|
||||||
|
};
|
||||||
|
|
||||||
|
// From SF
|
||||||
|
inline WinRateParams winRateParams(const Board& board) {
|
||||||
|
int material = board.pieces[Pawn].PopCount() +
|
||||||
|
3 * board.pieces[Knight].PopCount() +
|
||||||
|
3 * board.pieces[Bishop].PopCount() +
|
||||||
|
5 * board.pieces[Rook].PopCount() +
|
||||||
|
9 * board.pieces[Queen].PopCount();
|
||||||
|
|
||||||
|
// The fitted model only uses data for material counts in [17, 78], and is anchored at count 58.
|
||||||
|
double m = std::clamp(material, 17, 78) / 58.0;
|
||||||
|
|
||||||
|
// Return a = p_a(material) and b = p_b(material), see github.com/official-stockfish/WDL_model
|
||||||
|
constexpr double as[] = {-977.81543545, 2519.99289616, -2279.71042020, 1197.60065700};
|
||||||
|
constexpr double bs[] = {-224.61509659, 557.03359920, -440.33347428, 226.68436468};
|
||||||
|
|
||||||
|
double a = (((as[0] * m + as[1]) * m + as[2]) * m) + as[3];
|
||||||
|
double b = (((bs[0] * m + bs[1]) * m + bs[2]) * m) + bs[3];
|
||||||
|
|
||||||
|
return {a, b};
|
||||||
|
}
|
||||||
|
|
||||||
|
// The win rate model is 1 / (1 + exp((a - eval) / b)), where a = p_a(material) and b = p_b(material).
|
||||||
|
// It fits the LTC fishtest statistics rather accurately.
|
||||||
|
inline int winRateModel(int v, const Board& board) {
|
||||||
|
auto [a, b] = winRateParams(board);
|
||||||
|
|
||||||
|
// Return the win rate in per mille units, rounded to the nearest integer.
|
||||||
|
return int(0.5 + 1000 / (1 + std::exp((a - static_cast<double>(v)) / b)));
|
||||||
|
}
|
||||||
|
|
||||||
|
struct WDLTriplet {
|
||||||
|
int wins;
|
||||||
|
int draws;
|
||||||
|
int losses;
|
||||||
|
};
|
||||||
|
|
||||||
|
inline WDLTriplet getWDL(int v, const Board& board) {
|
||||||
|
int wins = std::clamp(winRateModel(v, board), 0, 1000);
|
||||||
|
int losses = std::clamp(winRateModel(-v, board), 0, 1000);
|
||||||
|
int draws = 1000 - wins - losses;
|
||||||
|
|
||||||
|
if (draws < 0) {
|
||||||
|
if (wins >= losses) {
|
||||||
|
wins += draws;
|
||||||
|
} else {
|
||||||
|
losses += draws;
|
||||||
|
}
|
||||||
|
|
||||||
|
draws = 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {wins, draws, losses};
|
||||||
|
}
|
||||||
|
|
||||||
|
inline int scaleEval(int eval, const Board& board) {
|
||||||
|
auto [a, b] = winRateParams(board);
|
||||||
|
|
||||||
|
return std::round(100 * eval / a);
|
||||||
|
}
|
||||||
Reference in new issue
Block a user