1 Commits
Author SHA1 Message Date
rektdieandclaude 30b0c36cd5 feat: value network trained on Lc0 data
The static evaluation behind the quiescence search is now a
(768 -> 128)x2 -> 1 SCReLU network instead of the hand-written
evaluation. It was trained with bullet on linrock's Lc0-derived test80
2024-02 binpack, 40 superbatches (10 min on an RTX 3070), final loss
0.0220. The quiescence search itself is unchanged.

The network is embedded with incbin (EVALFILE, default
networks/rigby-value-v1.bin). Q is tanh(cp / 800), the same scale the
network was trained on (sigmoid(cp / 400) = expected score).

Checked: bullet's float evaluation of fixed positions (trainer --check)
and the engine's quantised inference (evalfens) agree within 6 cp; an
integer re-implementation in Python matches the engine exactly. Perft
passes, bench is deterministic.

Bench: 545914

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-15 04:12:52 +01:00
14 changed files with 700 additions and 68 deletions

No files matched your search

+2
View File
@@ -0,0 +1,2 @@
# Networks are raw binary weights; never convert line endings
*.bin binary
+1
View File
@@ -5,6 +5,7 @@ Rigby
# Networks and data # Networks and data
*.bin *.bin
!networks/*.bin
*.nnue *.nnue
*.pb *.pb
*.pb.gz *.pb.gz
+7 -5
View File
@@ -5,7 +5,8 @@ SRC_DIR := src
OBJ_DIR := obj OBJ_DIR := obj
EXE ?= Rigby EXE ?= Rigby
EVALFILE ?= # The value network embedded into the binary
EVALFILE ?= networks/rigby-value-v1.bin
CXX ?= clang++ CXX ?= clang++
ifeq ($(origin CXX),default) ifeq ($(origin CXX),default)
CXX := clang++ CXX := clang++
@@ -25,7 +26,7 @@ else
endif endif
endif endif
CXXFLAGS := -std=c++20 -O3 -flto -Wall -Wextra -DNDEBUG CXXFLAGS := -std=c++20 -O3 -flto -Wall -Wextra -DNDEBUG -Iexternal
LDFLAGS := -O3 -flto LDFLAGS := -O3 -flto
ifeq ($(PLATFORM),windows) ifeq ($(PLATFORM),windows)
@@ -55,9 +56,7 @@ else
LDFLAGS += -pthread -static LDFLAGS += -pthread -static
endif endif
ifneq ($(EVALFILE),) CXXFLAGS += -DEVALFILE=\"$(EVALFILE)\"
CXXFLAGS += -DEVALFILE=\"$(EVALFILE)\"
endif
CXXFLAGS += $(ARCH_FLAGS) CXXFLAGS += $(ARCH_FLAGS)
LDFLAGS += $(ARCH_FLAGS) LDFLAGS += $(ARCH_FLAGS)
@@ -77,6 +76,9 @@ $(OBJ_DIR)/%.o: $(SRC_DIR)/%.cpp | $(OBJ_DIR)
$(OBJ_DIR): $(OBJ_DIR):
mkdir $(OBJ_DIR) mkdir $(OBJ_DIR)
# Rebuild the network's translation unit when the network changes
$(OBJ_DIR)/nnue.o: $(EVALFILE)
-include $(DEPS) -include $(DEPS)
.PHONY: clean .PHONY: clean
+9 -4
View File
@@ -13,9 +13,10 @@ Every change is validated with SPRT on OpenBench.
Verified with a perft suite (`Rigby perftsuite`). Verified with a perft suite (`Rigby perftsuite`).
- PUCT search: node arena with contiguous children, first-play urgency reduction, - PUCT search: node arena with contiguous children, first-play urgency reduction,
two-fold repetition, 50-move and insufficient-material draws inside the tree. two-fold repetition, 50-move and insufficient-material draws inside the tree.
- Placeholder evaluation until the network exists: a small hand-written - Value: a `(768 -> 128)x2 -> 1` network trained with bullet on Lc0 data
evaluation behind a capture-only quiescence search for the value, and move (`networks/rigby-value-v1.bin`, embedded at build time; see `train/README.md`),
heuristics (captures, promotions, checks, pawn threats) for the policy. behind a capture-only quiescence search. Policy: move heuristics (captures,
promotions, checks, pawn threats) until a policy network exists.
- Tree reuse between moves: the subtree of the new position is packed to the - Tree reuse between moves: the subtree of the new position is packed to the
front of the node arena in place, so it costs no extra memory. front of the node arena in place, so it costs no extra memory.
- Single-threaded. - Single-threaded.
@@ -28,8 +29,11 @@ the build targets `x86_64-w64-windows-gnu`, same as Eleanor.
``` ```
make make
make EXE=Rigby-dev make EXE=Rigby-dev
make EVALFILE=path/to/quantised.bin
``` ```
`EVALFILE` defaults to `networks/rigby-value-v1.bin`.
Compiling with `-DRIGBY_VERIFY_TREE` checks the whole tree before and after every Compiling with `-DRIGBY_VERIFY_TREE` checks the whole tree before and after every
reuse (legal moves, visit counts) and aborts on the first inconsistency. It is slow, reuse (legal moves, visit counts) and aborts on the first inconsistency. It is slow,
for debugging only. for debugging only.
@@ -45,7 +49,8 @@ Extra commands:
| Command | Meaning | | Command | Meaning |
| --- | --- | | --- | --- |
| `d` | Print the board, FEN and hash key | | `d` | Print the board, FEN and hash key |
| `eval` | Static and quiescence evaluation of the current position | | `eval` | Static (network) and quiescence evaluation of the current position |
| `evalfens` | Network evaluation of fixed positions, to compare with the trainer's `--check` |
| `perft <depth>` | Perft with per-move breakdown | | `perft <depth>` | Perft with per-move breakdown |
| `perftsuite [maxdepth]` | Standard perft positions with expected counts | | `perftsuite [maxdepth]` | Standard perft positions with expected counts |
| `bench [playouts]` | Fixed playout search over the bench positions | | `bench [playouts]` | Fixed playout search over the bench positions |
+481
View File
@@ -0,0 +1,481 @@
// incbin.h by Dale Weiler, https://github.com/graphitemaster/incbin (Unlicense / public domain).
// Copied unchanged from Eleanor's external/incbin.h.
/**
* @file incbin.h
* @author Dale Weiler
* @brief Utility for including binary files
*
* Facilities for including binary files into the current translation unit and
* making use from them externally in other translation units.
*/
#ifndef INCBIN_HDR
#define INCBIN_HDR
#include <limits.h>
#if defined(__AVX512BW__) || \
defined(__AVX512CD__) || \
defined(__AVX512DQ__) || \
defined(__AVX512ER__) || \
defined(__AVX512PF__) || \
defined(__AVX512VL__) || \
defined(__AVX512F__)
# define INCBIN_ALIGNMENT_INDEX 6
#elif defined(__AVX__) || \
defined(__AVX2__)
# define INCBIN_ALIGNMENT_INDEX 5
#elif defined(__SSE__) || \
defined(__SSE2__) || \
defined(__SSE3__) || \
defined(__SSSE3__) || \
defined(__SSE4_1__) || \
defined(__SSE4_2__) || \
defined(__neon__) || \
defined(__ARM_NEON) || \
defined(__ALTIVEC__)
# define INCBIN_ALIGNMENT_INDEX 4
#elif ULONG_MAX != 0xffffffffu
# define INCBIN_ALIGNMENT_INDEX 3
# else
# define INCBIN_ALIGNMENT_INDEX 2
#endif
/* Lookup table of (1 << n) where `n' is `INCBIN_ALIGNMENT_INDEX' */
#define INCBIN_ALIGN_SHIFT_0 1
#define INCBIN_ALIGN_SHIFT_1 2
#define INCBIN_ALIGN_SHIFT_2 4
#define INCBIN_ALIGN_SHIFT_3 8
#define INCBIN_ALIGN_SHIFT_4 16
#define INCBIN_ALIGN_SHIFT_5 32
#define INCBIN_ALIGN_SHIFT_6 64
/* Actual alignment value */
#define INCBIN_ALIGNMENT \
INCBIN_CONCATENATE( \
INCBIN_CONCATENATE(INCBIN_ALIGN_SHIFT, _), \
INCBIN_ALIGNMENT_INDEX)
/* Stringize */
#define INCBIN_STR(X) \
#X
#define INCBIN_STRINGIZE(X) \
INCBIN_STR(X)
/* Concatenate */
#define INCBIN_CAT(X, Y) \
X ## Y
#define INCBIN_CONCATENATE(X, Y) \
INCBIN_CAT(X, Y)
/* Deferred macro expansion */
#define INCBIN_EVAL(X) \
X
#define INCBIN_INVOKE(N, ...) \
INCBIN_EVAL(N(__VA_ARGS__))
/* Variable argument count for overloading by arity */
#define INCBIN_VA_ARG_COUNTER(_1, _2, _3, N, ...) N
#define INCBIN_VA_ARGC(...) INCBIN_VA_ARG_COUNTER(__VA_ARGS__, 3, 2, 1, 0)
/* Green Hills uses a different directive for including binary data */
#if defined(__ghs__)
# if (__ghs_asm == 2)
# define INCBIN_MACRO ".file"
/* Or consider the ".myrawdata" entry in the ld file */
# else
# define INCBIN_MACRO "\tINCBIN"
# endif
#else
# define INCBIN_MACRO ".incbin"
#endif
#ifndef _MSC_VER
# define INCBIN_ALIGN \
__attribute__((aligned(INCBIN_ALIGNMENT)))
#else
# define INCBIN_ALIGN __declspec(align(INCBIN_ALIGNMENT))
#endif
#if defined(__arm__) || /* GNU C and RealView */ \
defined(__arm) || /* Diab */ \
defined(_ARM) /* ImageCraft */
# define INCBIN_ARM
#endif
#ifdef __GNUC__
/* Utilize .balign where supported */
# define INCBIN_ALIGN_HOST ".balign " INCBIN_STRINGIZE(INCBIN_ALIGNMENT) "\n"
# define INCBIN_ALIGN_BYTE ".balign 1\n"
#elif defined(INCBIN_ARM)
/*
* On arm assemblers, the alignment value is calculated as (1 << n) where `n' is
* the shift count. This is the value passed to `.align'
*/
# define INCBIN_ALIGN_HOST ".align " INCBIN_STRINGIZE(INCBIN_ALIGNMENT_INDEX) "\n"
# define INCBIN_ALIGN_BYTE ".align 0\n"
#else
/* We assume other inline assembler's treat `.align' as `.balign' */
# define INCBIN_ALIGN_HOST ".align " INCBIN_STRINGIZE(INCBIN_ALIGNMENT) "\n"
# define INCBIN_ALIGN_BYTE ".align 1\n"
#endif
/* INCBIN_CONST is used by incbin.c generated files */
#if defined(__cplusplus)
# define INCBIN_EXTERNAL extern "C"
# define INCBIN_CONST extern const
#else
# define INCBIN_EXTERNAL extern
# define INCBIN_CONST const
#endif
/**
* @brief Optionally override the linker section into which size and data is
* emitted.
*
* @warning If you use this facility, you might have to deal with
* platform-specific linker output section naming on your own.
*/
#if !defined(INCBIN_OUTPUT_SECTION)
# if defined(__APPLE__)
# define INCBIN_OUTPUT_SECTION ".const_data"
# else
# define INCBIN_OUTPUT_SECTION ".rodata"
# endif
#endif
/**
* @brief Optionally override the linker section into which data is emitted.
*
* @warning If you use this facility, you might have to deal with
* platform-specific linker output section naming on your own.
*/
#if !defined(INCBIN_OUTPUT_DATA_SECTION)
# define INCBIN_OUTPUT_DATA_SECTION INCBIN_OUTPUT_SECTION
#endif
/**
* @brief Optionally override the linker section into which size is emitted.
*
* @warning If you use this facility, you might have to deal with
* platform-specific linker output section naming on your own.
*
* @note This is useful for Harvard architectures where program memory cannot
* be directly read from the program without special instructions. With this you
* can chose to put the size variable in RAM rather than ROM.
*/
#if !defined(INCBIN_OUTPUT_SIZE_SECTION)
# define INCBIN_OUTPUT_SIZE_SECTION INCBIN_OUTPUT_SECTION
#endif
#if defined(__APPLE__)
# include "TargetConditionals.h"
# if defined(TARGET_OS_IPHONE) && !defined(INCBIN_SILENCE_BITCODE_WARNING)
# warning "incbin is incompatible with bitcode. Using the library will break upload to App Store if you have bitcode enabled. Add `#define INCBIN_SILENCE_BITCODE_WARNING` before including this header to silence this warning."
# endif
/* The directives are different for Apple branded compilers */
# define INCBIN_SECTION INCBIN_OUTPUT_SECTION "\n"
# define INCBIN_GLOBAL(NAME) ".globl " INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME "\n"
# define INCBIN_INT ".long "
# define INCBIN_MANGLE "_"
# define INCBIN_BYTE ".byte "
# define INCBIN_TYPE(...)
#else
# define INCBIN_SECTION ".section " INCBIN_OUTPUT_SECTION "\n"
# define INCBIN_GLOBAL(NAME) ".global " INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME "\n"
# if defined(__ghs__)
# define INCBIN_INT ".word "
# else
# define INCBIN_INT ".int "
# endif
# if defined(__USER_LABEL_PREFIX__)
# define INCBIN_MANGLE INCBIN_STRINGIZE(__USER_LABEL_PREFIX__)
# else
# define INCBIN_MANGLE ""
# endif
# if defined(INCBIN_ARM)
/* On arm assemblers, `@' is used as a line comment token */
# define INCBIN_TYPE(NAME) ".type " INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME ", %object\n"
# elif defined(__MINGW32__) || defined(__MINGW64__)
/* Mingw doesn't support this directive either */
# define INCBIN_TYPE(NAME)
# elif defined(_WIN32)
// CIEKCE: this just doesn't work on windows at all
# define INCBIN_TYPE(NAME)
# else
/* It's safe to use `@' on other architectures */
# define INCBIN_TYPE(NAME) ".type " INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME ", @object\n"
# endif
# define INCBIN_BYTE ".byte "
#endif
/* List of style types used for symbol names */
#define INCBIN_STYLE_CAMEL 0
#define INCBIN_STYLE_SNAKE 1
/**
* @brief Specify the prefix to use for symbol names.
*
* @note By default this is "g".
*
* @code
* #define INCBIN_PREFIX incbin
* #include "incbin.h"
* INCBIN(Foo, "foo.txt");
*
* // Now you have the following symbols instead:
* // const unsigned char incbinFoo<data>[];
* // const unsigned char *const incbinFoo<end>;
* // const unsigned int incbinFoo<size>;
* @endcode
*/
#if !defined(INCBIN_PREFIX)
# define INCBIN_PREFIX g
#endif
/**
* @brief Specify the style used for symbol names.
*
* Possible options are
* - INCBIN_STYLE_CAMEL "CamelCase"
* - INCBIN_STYLE_SNAKE "snake_case"
*
* @note By default this is INCBIN_STYLE_CAMEL
*
* @code
* #define INCBIN_STYLE INCBIN_STYLE_SNAKE
* #include "incbin.h"
* INCBIN(foo, "foo.txt");
*
* // Now you have the following symbols:
* // const unsigned char <prefix>foo_data[];
* // const unsigned char *const <prefix>foo_end;
* // const unsigned int <prefix>foo_size;
* @endcode
*/
#if !defined(INCBIN_STYLE)
# define INCBIN_STYLE INCBIN_STYLE_CAMEL
#endif
/* Style lookup tables */
#define INCBIN_STYLE_0_DATA Data
#define INCBIN_STYLE_0_END End
#define INCBIN_STYLE_0_SIZE Size
#define INCBIN_STYLE_1_DATA _data
#define INCBIN_STYLE_1_END _end
#define INCBIN_STYLE_1_SIZE _size
/* Style lookup: returning identifier */
#define INCBIN_STYLE_IDENT(TYPE) \
INCBIN_CONCATENATE( \
INCBIN_STYLE_, \
INCBIN_CONCATENATE( \
INCBIN_EVAL(INCBIN_STYLE), \
INCBIN_CONCATENATE(_, TYPE)))
/* Style lookup: returning string literal */
#define INCBIN_STYLE_STRING(TYPE) \
INCBIN_STRINGIZE( \
INCBIN_STYLE_IDENT(TYPE)) \
/* Generate the global labels by indirectly invoking the macro with our style
* type and concatenating the name against them. */
#define INCBIN_GLOBAL_LABELS(NAME, TYPE) \
INCBIN_INVOKE( \
INCBIN_GLOBAL, \
INCBIN_CONCATENATE( \
NAME, \
INCBIN_INVOKE( \
INCBIN_STYLE_IDENT, \
TYPE))) \
INCBIN_INVOKE( \
INCBIN_TYPE, \
INCBIN_CONCATENATE( \
NAME, \
INCBIN_INVOKE( \
INCBIN_STYLE_IDENT, \
TYPE)))
/**
* @brief Externally reference binary data included in another translation unit.
*
* Produces three external symbols that reference the binary data included in
* another translation unit.
*
* The symbol names are a concatenation of `INCBIN_PREFIX' before *NAME*; with
* "Data", as well as "End" and "Size" after. An example is provided below.
*
* @param TYPE Optional array type. Omitting this picks a default of `unsigned char`.
* @param NAME The name given for the binary data
*
* @code
* INCBIN_EXTERN(Foo);
*
* // Now you have the following symbols:
* // extern const unsigned char <prefix>Foo<data>[];
* // extern const unsigned char *const <prefix>Foo<end>;
* // extern const unsigned int <prefix>Foo<size>;
* @endcode
*
* You may specify a custom optional data type as well as the first argument.
* @code
* INCBIN_EXTERN(custom_type, Foo);
*
* // Now you have the following symbols:
* // extern const custom_type <prefix>Foo<data>[];
* // extern const custom_type *const <prefix>Foo<end>;
* // extern const unsigned int <prefix>Foo<size>;
* @endcode
*/
#define INCBIN_EXTERN(...) \
INCBIN_CONCATENATE(INCBIN_EXTERN_, INCBIN_VA_ARGC(__VA_ARGS__))(__VA_ARGS__)
#define INCBIN_EXTERN_1(NAME, ...) \
INCBIN_EXTERN_2(unsigned char, NAME)
#define INCBIN_EXTERN_2(TYPE, NAME) \
INCBIN_EXTERNAL const INCBIN_ALIGN TYPE \
INCBIN_CONCATENATE( \
INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
INCBIN_STYLE_IDENT(DATA))[]; \
INCBIN_EXTERNAL const INCBIN_ALIGN TYPE *const \
INCBIN_CONCATENATE( \
INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
INCBIN_STYLE_IDENT(END)); \
INCBIN_EXTERNAL const unsigned int \
INCBIN_CONCATENATE( \
INCBIN_CONCATENATE(INCBIN_PREFIX, NAME), \
INCBIN_STYLE_IDENT(SIZE))
/**
* @brief Externally reference textual data included in another translation unit.
*
* Produces three external symbols that reference the textual data included in
* another translation unit.
*
* The symbol names are a concatenation of `INCBIN_PREFIX' before *NAME*; with
* "Data", as well as "End" and "Size" after. An example is provided below.
*
* @param NAME The name given for the textual data
*
* @code
* INCBIN_EXTERN(Foo);
*
* // Now you have the following symbols:
* // extern const char <prefix>Foo<data>[];
* // extern const char *const <prefix>Foo<end>;
* // extern const unsigned int <prefix>Foo<size>;
* @endcode
*/
#define INCTXT_EXTERN(NAME) \
INCBIN_EXTERN_2(char, NAME)
/**
* @brief Include a binary file into the current translation unit.
*
* Includes a binary file into the current translation unit, producing three symbols
* for objects that encode the data and size respectively.
*
* The symbol names are a concatenation of `INCBIN_PREFIX' before *NAME*; with
* "Data", as well as "End" and "Size" after. An example is provided below.
*
* @param TYPE Optional array type. Omitting this picks a default of `unsigned char`.
* @param NAME The name to associate with this binary data (as an identifier.)
* @param FILENAME The file to include (as a string literal.)
*
* @code
* INCBIN(Icon, "icon.png");
*
* // Now you have the following symbols:
* // const unsigned char <prefix>Icon<data>[];
* // const unsigned char *const <prefix>Icon<end>;
* // const unsigned int <prefix>Icon<size>;
* @endcode
*
* You may specify a custom optional data type as well as the first argument.
* These macros are specialized by arity.
* @code
* INCBIN(custom_type, Icon, "icon.png");
*
* // Now you have the following symbols:
* // const custom_type <prefix>Icon<data>[];
* // const custom_type *const <prefix>Icon<end>;
* // const unsigned int <prefix>Icon<size>;
* @endcode
*
* @warning This must be used in global scope
* @warning The identifiers may be different if INCBIN_STYLE is not default
*
* To externally reference the data included by this in another translation unit
* please @see INCBIN_EXTERN.
*/
#ifdef _MSC_VER
# define INCBIN(NAME, FILENAME) \
INCBIN_EXTERN(NAME)
#else
# define INCBIN(...) \
INCBIN_CONCATENATE(INCBIN_, INCBIN_VA_ARGC(__VA_ARGS__))(__VA_ARGS__)
# if defined(__GNUC__)
# define INCBIN_1(...) _Pragma("GCC error \"Single argument INCBIN not allowed\"")
# elif defined(__clang__)
# define INCBIN_1(...) _Pragma("clang error \"Single argument INCBIN not allowed\"")
# else
# define INCBIN_1(...) /* Cannot do anything here */
# endif
# define INCBIN_2(NAME, FILENAME) \
INCBIN_3(unsigned char, NAME, FILENAME)
# define INCBIN_3(TYPE, NAME, FILENAME) INCBIN_COMMON(TYPE, NAME, FILENAME, /* No terminator for binary data */)
# define INCBIN_COMMON(TYPE, NAME, FILENAME, TERMINATOR) \
__asm__(INCBIN_SECTION \
INCBIN_GLOBAL_LABELS(NAME, DATA) \
INCBIN_ALIGN_HOST \
INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(DATA) ":\n" \
INCBIN_MACRO " \"" FILENAME "\"\n" \
TERMINATOR \
INCBIN_GLOBAL_LABELS(NAME, END) \
INCBIN_ALIGN_BYTE \
INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(END) ":\n" \
INCBIN_BYTE "1\n" \
INCBIN_GLOBAL_LABELS(NAME, SIZE) \
INCBIN_ALIGN_HOST \
INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(SIZE) ":\n" \
INCBIN_INT INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(END) " - " \
INCBIN_MANGLE INCBIN_STRINGIZE(INCBIN_PREFIX) #NAME INCBIN_STYLE_STRING(DATA) "\n" \
INCBIN_ALIGN_HOST \
".text\n" \
); \
INCBIN_EXTERN(TYPE, NAME)
#endif
/**
* @brief Include a textual file into the current translation unit.
*
* This behaves the same as INCBIN except it produces char compatible arrays
* and implicitly adds a null-terminator byte, thus the size of data included
* by this is one byte larger than that of INCBIN.
*
* Includes a textual file into the current translation unit, producing three
* symbols for objects that encode the data and size respectively.
*
* The symbol names are a concatenation of `INCBIN_PREFIX' before *NAME*; with
* "Data", as well as "End" and "Size" after. An example is provided below.
*
* @param NAME The name to associate with this binary data (as an identifier.)
* @param FILENAME The file to include (as a string literal.)
*
* @code
* INCTXT(Readme, "readme.txt");
*
* // Now you have the following symbols:
* // const char <prefix>Readme<data>[];
* // const char *const <prefix>Readme<end>;
* // const unsigned int <prefix>Readme<size>;
* @endcode
*
* @warning This must be used in global scope
* @warning The identifiers may be different if INCBIN_STYLE is not default
*
* To externally reference the data included by this in another translation unit
* please @see INCBIN_EXTERN.
*/
#if defined(_MSC_VER)
# define INCTXT(NAME, FILENAME) \
INCBIN_EXTERN(NAME)
#else
# define INCTXT(NAME, FILENAME) \
INCBIN_COMMON(char, NAME, FILENAME, INCBIN_BYTE "0\n")
#endif
#endif
Binary file not shown.
+17 -53
View File
@@ -4,26 +4,24 @@
#include <cmath> #include <cmath>
#include <cstdlib> #include <cstdlib>
#include "nnue.h"
namespace rigby::eval { namespace rigby::eval {
namespace { namespace {
constexpr int MATE = 30000; constexpr int MATE = 30000;
constexpr int QS_MAX_PLY = 32; constexpr int QS_MAX_PLY = 32;
constexpr float Q_SCALE = 300.0f; // The network is trained so that sigmoid(cp / 400) is the expected score, so
// Q = 2 * sigmoid(cp / 400) - 1 = tanh(cp / 800).
constexpr float Q_SCALE = 2.0f * float(nnue::SCALE);
constexpr int MG_VALUE[6] = {90, 320, 335, 480, 980, 0};
constexpr int EG_VALUE[6] = {110, 290, 305, 520, 940, 0};
constexpr int SEE_VALUE[6] = {100, 300, 310, 500, 900, 0}; constexpr int SEE_VALUE[6] = {100, 300, 310, 500, 900, 0};
constexpr int PHASE_WEIGHT[6] = {0, 1, 1, 2, 4, 0};
// Material folded into piece-square tables, indexed [piece][square]. // Positional piece-square bonuses, white's view, used by the policy.
int mg_table[12][64];
int eg_table[12][64];
// Positional part only (no material), white's view, used by the policy.
int mg_pst[6][64]; int mg_pst[6][64];
void pst_for(int type, int sq, int& mg, int& eg) { int pst_mg(int type, int sq) {
const int f = file_of(sq); const int f = file_of(sq);
const int r = rank_of(sq); const int r = rank_of(sq);
const int center = std::abs(2 * f - 7) + std::abs(2 * r - 7); // 2..14 const int center = std::abs(2 * f - 7) + std::abs(2 * r - 7); // 2..14
@@ -31,29 +29,17 @@ void pst_for(int type, int sq, int& mg, int& eg) {
switch (type) { switch (type) {
case PAWN: case PAWN:
mg = (r >= 1 && r <= 6) ? (r - 1) * 6 + (central_file ? (r - 1) * 4 : 0) : 0; return (r >= 1 && r <= 6) ? (r - 1) * 6 + (central_file ? (r - 1) * 4 : 0) : 0;
eg = (r >= 1 && r <= 6) ? (r - 1) * 14 : 0;
break;
case KNIGHT: case KNIGHT:
mg = 24 - center * 4; return 24 - center * 4;
eg = 18 - center * 3;
break;
case BISHOP: case BISHOP:
mg = 12 - center * 2; return 12 - center * 2;
eg = 10 - center * 2;
break;
case ROOK: case ROOK:
mg = (r == 6 ? 20 : 0) + (central_file ? 6 : 0); return (r == 6 ? 20 : 0) + (central_file ? 6 : 0);
eg = r == 6 ? 15 : 0;
break;
case QUEEN: case QUEEN:
mg = 6 - center; return 6 - center;
eg = 20 - center * 2; default: // KING: stay sheltered
break; return -std::min(r, 3) * 25 + ((f <= 2 || f >= 6) ? 15 : -15);
default: // KING: shelter in the middlegame, centralise in the endgame
mg = -std::min(r, 3) * 25 + ((f <= 2 || f >= 6) ? 15 : -15);
eg = 30 - center * 4;
break;
} }
} }
@@ -64,35 +50,13 @@ int victim_type(const Position& pos, Move m) { return m.is_en_passant() ? PAWN :
void init() { void init() {
for (int type = PAWN; type <= KING; type++) { for (int type = PAWN; type <= KING; type++) {
for (int sq = 0; sq < 64; sq++) { for (int sq = 0; sq < 64; sq++) {
int mg, eg; mg_pst[type][sq] = pst_mg(type, sq);
pst_for(type, sq, mg, eg);
mg_pst[type][sq] = mg;
mg_table[make_piece(WHITE, type)][sq] = MG_VALUE[type] + mg;
eg_table[make_piece(WHITE, type)][sq] = EG_VALUE[type] + eg;
mg_table[make_piece(BLACK, type)][sq ^ 56] = -(MG_VALUE[type] + mg);
eg_table[make_piece(BLACK, type)][sq ^ 56] = -(EG_VALUE[type] + eg);
} }
} }
nnue::init();
} }
int static_eval(const Position& pos) { int static_eval(const Position& pos) { return nnue::evaluate(pos); }
int mg = 0, eg = 0, phase = 0;
u64 occ = pos.occupancy();
while (occ) {
const int sq = pop_lsb(occ);
const int piece = pos.piece_on(sq);
mg += mg_table[piece][sq];
eg += eg_table[piece][sq];
phase += PHASE_WEIGHT[piece_type(piece)];
}
phase = std::min(phase, 24);
int score = (mg * phase + eg * (24 - phase)) / 24;
if (popcount(pos.pieces_of(WHITE, BISHOP)) >= 2) score += 30;
if (popcount(pos.pieces_of(BLACK, BISHOP)) >= 2) score -= 30;
return (pos.stm == WHITE ? score : -score) + 10;
}
int quiescence(const Position& pos, int alpha, int beta, int ply) { int quiescence(const Position& pos, int alpha, int beta, int ply) {
const bool in_check = pos.in_check(); const bool in_check = pos.in_check();
+3 -3
View File
@@ -4,12 +4,12 @@
namespace rigby::eval { namespace rigby::eval {
// Stand-in evaluation until the network arrives. Everything here is replaced by // Value: the network trained on Lc0 data, behind a capture-only quiescence
// the value and policy heads of the net trained on Lc0 data. // search. Policy: move heuristics until a policy network exists.
void init(); void init();
// Static evaluation in centipawns, from the side to move's view. // Static evaluation (the value network) in centipawns, side to move's view.
int static_eval(const Position& pos); int static_eval(const Position& pos);
// Capture-only search on top of the static evaluation, side to move's view. // Capture-only search on top of the static evaluation, side to move's view.
+85
View File
@@ -0,0 +1,85 @@
#include "nnue.h"
#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include "incbin.h"
#ifndef EVALFILE
#error "EVALFILE must name the network file (the Makefile sets it)"
#endif
INCBIN(RigbyNet, EVALFILE);
namespace rigby::nnue {
namespace {
// Layout of bullet's quantised.bin, padded by bullet to a multiple of 64 bytes.
struct alignas(64) Network {
i16 l0w[768][HIDDEN]; // feature-major: one HIDDEN-wide column per input
i16 l0b[HIDDEN];
i16 l1w[2 * HIDDEN]; // side to move's half first
i16 l1b;
};
Network net;
// Input index from one side's point of view: its own pieces first, and the
// board flipped vertically for black (bullet's Chess768).
inline int feature(int perspective, int piece, int sq) {
const int theirs = piece_color(piece) != perspective;
const int rel_sq = perspective == WHITE ? sq : sq ^ 56;
return 384 * theirs + 64 * piece_type(piece) + rel_sq;
}
inline i64 screlu(i16 x) {
const i64 y = std::clamp<i64>(x, 0, QA);
return y * y;
}
} // namespace
void init() {
if (gRigbyNetSize < sizeof(Network)) {
std::fprintf(stderr, "network %s is %u bytes, expected at least %u\n", EVALFILE, unsigned(gRigbyNetSize),
unsigned(sizeof(Network)));
std::exit(1);
}
std::memcpy(&net, gRigbyNetData, sizeof(Network));
}
int evaluate(const Position& pos) {
alignas(64) i16 us[HIDDEN];
alignas(64) i16 them[HIDDEN];
std::memcpy(us, net.l0b, sizeof(us));
std::memcpy(them, net.l0b, sizeof(them));
const int stm = pos.stm;
u64 occ = pos.occupancy();
while (occ) {
const int sq = pop_lsb(occ);
const int piece = pos.piece_on(sq);
const i16* w_us = net.l0w[feature(stm, piece, sq)];
const i16* w_them = net.l0w[feature(stm ^ 1, piece, sq)];
for (int i = 0; i < HIDDEN; i++) {
us[i] = i16(us[i] + w_us[i]);
them[i] = i16(them[i] + w_them[i]);
}
}
// 256 products of up to QA^2 * |w| overflow 32 bits in the worst case.
i64 out = 0;
for (int i = 0; i < HIDDEN; i++) out += screlu(us[i]) * net.l1w[i];
for (int i = 0; i < HIDDEN; i++) out += screlu(them[i]) * net.l1w[HIDDEN + i];
out /= QA;
out += net.l1b;
out *= SCALE;
out /= i64(QA) * QB;
return int(out);
}
} // namespace rigby::nnue
+21
View File
@@ -0,0 +1,21 @@
#pragma once
#include "position.h"
namespace rigby::nnue {
// Value network trained with bullet on Lc0 data (see train/README.md):
// (768 -> HIDDEN)x2 -> 1, SCReLU, dual perspective, quantised i16.
constexpr int HIDDEN = 128;
constexpr int SCALE = 400;
constexpr int QA = 255;
constexpr int QB = 64;
// Checks and loads the embedded network. Exits with a message if it does not fit.
void init();
// Evaluation in centipawns from the side to move's view, on the network's scale:
// sigmoid(cp / SCALE) is the expected score.
int evaluate(const Position& pos);
} // namespace rigby::nnue
+1
View File
@@ -11,6 +11,7 @@ using u32 = std::uint32_t;
using u16 = std::uint16_t; using u16 = std::uint16_t;
using u8 = std::uint8_t; using u8 = std::uint8_t;
using i64 = std::int64_t; using i64 = std::int64_t;
using i16 = std::int16_t;
constexpr std::string_view START_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"; constexpr std::string_view START_FEN = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1";
+20
View File
@@ -1,6 +1,7 @@
#include "uci.h" #include "uci.h"
#include <algorithm> #include <algorithm>
#include <cstdio>
#include <chrono> #include <chrono>
#include <iostream> #include <iostream>
#include <memory> #include <memory>
@@ -229,6 +230,25 @@ void uci_loop() {
} else if (cmd == "eval") { } else if (cmd == "eval") {
send("static " + std::to_string(eval::static_eval(e.pos)) + " cp, qsearch " + send("static " + std::to_string(eval::static_eval(e.pos)) + " cp, qsearch " +
std::to_string(eval::quiescence(e.pos, -30000, 30000, 0)) + " cp (side to move)"); std::to_string(eval::quiescence(e.pos, -30000, 30000, 0)) + " cp (side to move)");
} else if (cmd == "evalfens") {
// Same positions as the trainer's --check, to compare inference
static constexpr const char* FENS[] = {
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR b KQkq - 0 1",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R b KQkq - 0 1",
"6k1/5pp1/1p2p2p/1Pq1Pn2/2P2P2/6P1/4Q1BP/6K1 w - - 1 30",
"8/8/3k4/2p1p3/2P1P3/3K4/8/8 w - - 0 1",
"4k3/8/8/8/8/8/8/R3K3 w - - 0 1",
"4k3/8/8/8/8/8/8/R3K3 b - - 0 1",
};
for (const char* fen : FENS) {
Position pos;
pos.set_fen(fen);
char line[160];
std::snprintf(line, sizeof(line), "%6d cp %s", eval::static_eval(pos), fen);
send(line);
}
} else if (cmd == "perft") { } else if (cmd == "perft") {
int depth = 5; int depth = 5;
is >> depth; is >> depth;
+19 -2
View File
@@ -38,8 +38,25 @@ Inputs (bullet's `Chess768`): `64 * piece + square`, with pieces relative to the
accumulator's side (own pawn = 0 ... own king = 5, their pawn = 6 ... their king = 11) accumulator's side (own pawn = 0 ... own king = 5, their pawn = 6 ... their king = 11)
and squares flipped vertically for black. The side to move's accumulator comes first. and squares flipped vertically for black. The side to move's accumulator comes first.
Output: `((sum screlu(acc) * w) / QA + b) * 400 / (QA * QB)` in centipawns, side to Output: `((sum screlu(acc) * w) / QA + b) * 400 / (QA * QB)` in centipawns, side to
move. The engine should map it to Q with the same 400 scale: move. The engine maps it to Q with the same 400 scale:
`q = 2 * sigmoid(cp / 400) - 1` (engine inference is not written yet). `q = 2 * sigmoid(cp / 400) - 1 = tanh(cp / 800)` (`src/nnue.cpp`, `src/eval.cpp`).
### Checking the engine's inference
```
cargo run --release -- --check checkpoints/<id>-<superbatch>
```
prints bullet's own (float) evaluation of fixed positions; the engine's `evalfens`
command prints the same positions with the quantised network. Expect agreement
within a few centipawns (quantisation); a wrong feature mapping shows up as
differences of hundreds.
### Networks
| File | Data | Superbatches | Final loss |
| --- | --- | --- | --- |
| `networks/rigby-value-v1.bin` | test80 2024-02 | 40 (10 min) | 0.0220 |
### Data ### Data
+34 -1
View File
@@ -6,6 +6,11 @@
//! //!
//! Usage: //! Usage:
//! cargo run --release -- [--data <file.binpack>]... [--superbatches N] [--id NAME] //! cargo run --release -- [--data <file.binpack>]... [--superbatches N] [--id NAME]
//! cargo run --release -- --check checkpoints/<id>-<superbatch>
//!
//! `--check` loads a checkpoint and prints the network's evaluation (centipawns,
//! side to move) of a few fixed positions, as a reference for the engine's own
//! inference (Rigby's `evalfens` command prints the same list).
//! //!
//! The network is written to checkpoints/<id>-<superbatch>/quantised.bin every //! The network is written to checkpoints/<id>-<superbatch>/quantised.bin every
//! SAVE_RATE superbatches and at the end. Inference in Rigby has to use the same //! SAVE_RATE superbatches and at the end. Inference in Rigby has to use the same
@@ -46,14 +51,28 @@ fn filter(entry: &TrainingDataEntry) -> bool {
&& entry.pos.piece_at(entry.mv.to()).piece_type() == PieceType::None && entry.pos.piece_at(entry.mv.to()).piece_type() == PieceType::None
} }
/// Positions for `--check`; keep in sync with Rigby's `evalfens` command.
const CHECK_FENS: [&str; 8] = [
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR b KQkq - 0 1",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 1",
"r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R b KQkq - 0 1",
"6k1/5pp1/1p2p2p/1Pq1Pn2/2P2P2/6P1/4Q1BP/6K1 w - - 1 30",
"8/8/3k4/2p1p3/2P1P3/3K4/8/8 w - - 0 1",
"4k3/8/8/8/8/8/8/R3K3 w - - 0 1",
"4k3/8/8/8/8/8/8/R3K3 b - - 0 1",
];
struct Args { struct Args {
data: Vec<String>, data: Vec<String>,
superbatches: usize, superbatches: usize,
id: String, id: String,
check: Option<String>,
} }
fn parse_args() -> Args { fn parse_args() -> Args {
let mut args = Args { data: Vec::new(), superbatches: DEFAULT_SUPERBATCHES, id: "rigby-value".to_string() }; let mut args =
Args { data: Vec::new(), superbatches: DEFAULT_SUPERBATCHES, id: "rigby-value".to_string(), check: None };
let mut it = std::env::args().skip(1); let mut it = std::env::args().skip(1);
while let Some(arg) = it.next() { while let Some(arg) = it.next() {
match arg.as_str() { match arg.as_str() {
@@ -62,9 +81,13 @@ fn parse_args() -> Args {
args.superbatches = it.next().expect("--superbatches needs a number").parse().expect("not a number") args.superbatches = it.next().expect("--superbatches needs a number").parse().expect("not a number")
} }
"--id" => args.id = it.next().expect("--id needs a name"), "--id" => args.id = it.next().expect("--id needs a name"),
"--check" => args.check = Some(it.next().expect("--check needs a checkpoint directory")),
other => panic!("unknown argument: {other}"), other => panic!("unknown argument: {other}"),
} }
} }
if args.check.is_some() {
return args;
}
if args.data.is_empty() { if args.data.is_empty() {
args.data.push(DEFAULT_DATA.to_string()); args.data.push(DEFAULT_DATA.to_string());
} }
@@ -97,6 +120,16 @@ fn main() {
l1.forward(stm_hidden.concat(ntm_hidden)) l1.forward(stm_hidden.concat(ntm_hidden))
}); });
if let Some(checkpoint) = &args.check {
trainer.load_from_checkpoint(checkpoint);
for fen in CHECK_FENS {
// bulletformat's text form: <fen> | <score> | <result>
let raw = trainer.eval(&format!("{fen} | 0 | 0.5"));
println!("{:6.0} cp {fen}", raw * SCALE as f32);
}
return;
}
let schedule = TrainingSchedule { let schedule = TrainingSchedule {
net_id: args.id.clone(), net_id: args.id.clone(),
eval_scale: SCALE as f32, eval_scale: SCALE as f32,