Compare commits
4
Commits
9643c7b0a5
...
c4f65b2632
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c4f65b2632 | ||
|
|
05fd552e0b | ||
|
|
15258f952a | ||
|
|
1c9d2beec3 |
No files matched your search
@@ -1,5 +1,7 @@
|
|||||||
# Rigby - MCTS chess engine
|
# Rigby - MCTS chess engine
|
||||||
# OpenBench calls: make EXE=<name> [EVALFILE=<net>] [CXX=<compiler>]
|
# OpenBench calls: make EXE=<name> [EVALFILE=<net>] [CXX=<compiler>]
|
||||||
|
# POLICYFILE=<net> picks the built-in policy network; POLICYFILE= builds none
|
||||||
|
# (move heuristics).
|
||||||
|
|
||||||
SRC_DIR := src
|
SRC_DIR := src
|
||||||
OBJ_DIR := obj
|
OBJ_DIR := obj
|
||||||
@@ -7,6 +9,8 @@ OBJ_DIR := obj
|
|||||||
EXE ?= Rigby
|
EXE ?= Rigby
|
||||||
# The value network embedded into the binary
|
# The value network embedded into the binary
|
||||||
EVALFILE ?= networks/rigby-value-v1.bin
|
EVALFILE ?= networks/rigby-value-v1.bin
|
||||||
|
# The policy network embedded into the binary; empty means move heuristics
|
||||||
|
POLICYFILE ?= networks/rigby-policy-v1.bin
|
||||||
CXX ?= clang++
|
CXX ?= clang++
|
||||||
ifeq ($(origin CXX),default)
|
ifeq ($(origin CXX),default)
|
||||||
CXX := clang++
|
CXX := clang++
|
||||||
@@ -57,6 +61,9 @@ else
|
|||||||
endif
|
endif
|
||||||
|
|
||||||
CXXFLAGS += -DEVALFILE=\"$(EVALFILE)\"
|
CXXFLAGS += -DEVALFILE=\"$(EVALFILE)\"
|
||||||
|
ifneq ($(POLICYFILE),)
|
||||||
|
CXXFLAGS += -DPOLICYFILE=\"$(POLICYFILE)\"
|
||||||
|
endif
|
||||||
|
|
||||||
CXXFLAGS += $(ARCH_FLAGS)
|
CXXFLAGS += $(ARCH_FLAGS)
|
||||||
LDFLAGS += $(ARCH_FLAGS)
|
LDFLAGS += $(ARCH_FLAGS)
|
||||||
@@ -78,6 +85,9 @@ $(OBJ_DIR):
|
|||||||
|
|
||||||
# Rebuild the network's translation unit when the network changes
|
# Rebuild the network's translation unit when the network changes
|
||||||
$(OBJ_DIR)/nnue.o: $(EVALFILE)
|
$(OBJ_DIR)/nnue.o: $(EVALFILE)
|
||||||
|
ifneq ($(POLICYFILE),)
|
||||||
|
$(OBJ_DIR)/policy.o: $(POLICYFILE)
|
||||||
|
endif
|
||||||
|
|
||||||
-include $(DEPS)
|
-include $(DEPS)
|
||||||
|
|
||||||
|
|||||||
@@ -18,8 +18,11 @@ Every change is validated with SPRT on OpenBench.
|
|||||||
two-fold repetition, 50-move and insufficient-material draws inside the tree.
|
two-fold repetition, 50-move and insufficient-material draws inside the tree.
|
||||||
- Value: a `(768 -> 128)x2 -> 1` network trained with bullet on Lc0 data
|
- Value: a `(768 -> 128)x2 -> 1` network trained with bullet on Lc0 data
|
||||||
(`networks/rigby-value-v1.bin`, embedded at build time; see `train/README.md`),
|
(`networks/rigby-value-v1.bin`, embedded at build time; see `train/README.md`),
|
||||||
behind a capture-only quiescence search. Policy: move heuristics (captures,
|
behind a capture-only quiescence search.
|
||||||
promotions, checks, pawn threats) until a policy network exists.
|
- Policy: a `3072 -> 1024 -> 3920` network trained on Lc0 visit distributions
|
||||||
|
(`networks/rigby-policy-v1.bin`, embedded at build time; see `train/README.md`).
|
||||||
|
Built without one (`POLICYFILE=`), move heuristics (captures, promotions,
|
||||||
|
checks, pawn threats).
|
||||||
- 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.
|
||||||
- When the arena is full, the least visited parts of the tree are cut back to
|
- When the arena is full, the least visited parts of the tree are cut back to
|
||||||
@@ -38,7 +41,8 @@ make EXE=Rigby-dev
|
|||||||
make EVALFILE=path/to/quantised.bin
|
make EVALFILE=path/to/quantised.bin
|
||||||
```
|
```
|
||||||
|
|
||||||
`EVALFILE` defaults to `networks/rigby-value-v1.bin`.
|
`EVALFILE` defaults to `networks/rigby-value-v1.bin`. `POLICYFILE` defaults to
|
||||||
|
`networks/rigby-policy-v1.bin`; `POLICYFILE=` builds the move heuristics instead.
|
||||||
|
|
||||||
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 and after every collection (legal moves, visit counts) and aborts on the first
|
reuse and after every collection (legal moves, visit counts) and aborts on the first
|
||||||
@@ -60,6 +64,7 @@ Extra commands:
|
|||||||
| `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 |
|
||||||
| `perftfile <epd> [maxdepth]` | Perft of every `<fen> ;D1 <n> ;D2 <n> ...` line of a file (e.g. a Chess960 suite) |
|
| `perftfile <epd> [maxdepth]` | Perft of every `<fen> ;D1 <n> ;D2 <n> ...` line of a file (e.g. a Chess960 suite) |
|
||||||
|
| `policyfens` | Policy network priors of fixed positions, to compare with the trainer's `--check` |
|
||||||
| `bench [playouts]` | Fixed playout search over the bench positions |
|
| `bench [playouts]` | Fixed playout search over the bench positions |
|
||||||
|
|
||||||
`go depth N` limits the mean playout depth. `nodes` in `info` lines are playouts.
|
`go depth N` limits the mean playout depth. `nodes` in `info` lines are playouts.
|
||||||
@@ -87,6 +92,7 @@ terminal).
|
|||||||
| FPUReduction | 30 | First-play urgency reduction x100. |
|
| FPUReduction | 30 | First-play urgency reduction x100. |
|
||||||
| PolicyTemp | 100 | Policy softmax temperature x100. |
|
| PolicyTemp | 100 | Policy softmax temperature x100. |
|
||||||
| UCI_Chess960 | false | Write and read castling as the king taking its rook (`e1h1`). |
|
| UCI_Chess960 | false | Write and read castling as the king taking its rook (`e1h1`). |
|
||||||
|
| PolicyFile | `<empty>` | Policy network file to use instead of the built-in one. |
|
||||||
|
|
||||||
## Bench
|
## Bench
|
||||||
|
|
||||||
|
|||||||
Binary file not shown.
@@ -6,6 +6,7 @@
|
|||||||
#include <cstdlib>
|
#include <cstdlib>
|
||||||
|
|
||||||
#include "nnue.h"
|
#include "nnue.h"
|
||||||
|
#include "policy.h"
|
||||||
|
|
||||||
namespace rigby::eval {
|
namespace rigby::eval {
|
||||||
|
|
||||||
@@ -113,6 +114,7 @@ void init() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
nnue::init();
|
nnue::init();
|
||||||
|
rigby::policy::init();
|
||||||
}
|
}
|
||||||
|
|
||||||
int static_eval(const Position& pos) { return nnue::evaluate(pos); }
|
int static_eval(const Position& pos) { return nnue::evaluate(pos); }
|
||||||
@@ -200,6 +202,24 @@ int quiescence(const Position& pos, int alpha, int beta, int ply) {
|
|||||||
float value(const Position& pos) { return cp_to_q(quiescence(pos, -MATE, MATE, 0)); }
|
float value(const Position& pos) { return cp_to_q(quiescence(pos, -MATE, MATE, 0)); }
|
||||||
|
|
||||||
void policy(const Position& pos, const MoveList& moves, float temperature, const float* bias, float* out) {
|
void policy(const Position& pos, const MoveList& moves, float temperature, const float* bias, float* out) {
|
||||||
|
if (rigby::policy::loaded()) {
|
||||||
|
// The network's logits, shifted by the search's bias.
|
||||||
|
rigby::policy::logits(pos, moves, out);
|
||||||
|
const float inv_temp = 1.0f / std::max(temperature, 0.01f);
|
||||||
|
float max_logit = -1e30f;
|
||||||
|
for (int i = 0; i < moves.size(); i++) {
|
||||||
|
out[i] = (out[i] + (bias ? bias[i] : 0.0f)) * inv_temp;
|
||||||
|
max_logit = std::max(max_logit, out[i]);
|
||||||
|
}
|
||||||
|
float total = 0.0f;
|
||||||
|
for (int i = 0; i < moves.size(); i++) {
|
||||||
|
out[i] = std::exp(out[i] - max_logit);
|
||||||
|
total += out[i];
|
||||||
|
}
|
||||||
|
for (int i = 0; i < moves.size(); i++) out[i] /= total;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
const int us = pos.stm;
|
const int us = pos.stm;
|
||||||
const int them = us ^ 1;
|
const int them = us ^ 1;
|
||||||
const u64 occ = pos.occupancy();
|
const u64 occ = pos.occupancy();
|
||||||
|
|||||||
+3
-2
@@ -5,7 +5,8 @@
|
|||||||
namespace rigby::eval {
|
namespace rigby::eval {
|
||||||
|
|
||||||
// Value: the network trained on Lc0 data, behind a capture-only quiescence
|
// Value: the network trained on Lc0 data, behind a capture-only quiescence
|
||||||
// search. Policy: move heuristics until a policy network exists.
|
// search. Policy: the policy network when one is loaded (see policy.h),
|
||||||
|
// otherwise move heuristics.
|
||||||
|
|
||||||
void init();
|
void init();
|
||||||
|
|
||||||
@@ -23,7 +24,7 @@ int quiescence(const Position& pos, int alpha, int beta, int ply);
|
|||||||
float value(const Position& pos);
|
float value(const Position& pos);
|
||||||
|
|
||||||
// Writes softmax-normalised priors for `moves` into `out`. `bias`, when not
|
// Writes softmax-normalised priors for `moves` into `out`. `bias`, when not
|
||||||
// null, is added to each move's logit before the softmax.
|
// null, is added to each move's logit before the softmax (and the temperature).
|
||||||
void policy(const Position& pos, const MoveList& moves, float temperature, const float* bias, float* out);
|
void policy(const Position& pos, const MoveList& moves, float temperature, const float* bias, float* out);
|
||||||
|
|
||||||
// Conversion between centipawns and Q in [-1, 1]. One scale for both directions,
|
// Conversion between centipawns and Q in [-1, 1]. One scale for both directions,
|
||||||
|
|||||||
+196
@@ -0,0 +1,196 @@
|
|||||||
|
#include "policy.h"
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <array>
|
||||||
|
#include <bit>
|
||||||
|
#include <cstdio>
|
||||||
|
#include <fstream>
|
||||||
|
#include <iterator>
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
#ifdef POLICYFILE
|
||||||
|
#include "incbin.h"
|
||||||
|
INCBIN(RigbyPolicy, POLICYFILE);
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace rigby::policy {
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
|
||||||
|
constexpr int Q = 128;
|
||||||
|
|
||||||
|
// Weights as the trainer writes them (montytrain's save_quantised): l0w is
|
||||||
|
// feature-major ([input][hidden]), l1w move-major ([output][hidden / 2]).
|
||||||
|
struct Network {
|
||||||
|
int hidden = 0;
|
||||||
|
std::vector<i8> l0w, l0b, l1w, l1b;
|
||||||
|
};
|
||||||
|
|
||||||
|
Network net;
|
||||||
|
|
||||||
|
// --- Output index (train/policy/src/inputs.rs map_move_to_index) ---
|
||||||
|
|
||||||
|
// Squares a piece of each type could ever move to from a square, on an empty
|
||||||
|
// board, from white's side (pawns: one step forward or diagonally forward).
|
||||||
|
struct Tables {
|
||||||
|
u64 destinations[64][6];
|
||||||
|
int offsets[6][65];
|
||||||
|
};
|
||||||
|
|
||||||
|
const Tables& tables() {
|
||||||
|
static const Tables t = [] {
|
||||||
|
Tables t{};
|
||||||
|
for (int sq = 0; sq < 64; sq++) {
|
||||||
|
const u64 b = bb(sq);
|
||||||
|
t.destinations[sq][PAWN] = ((b & ~FILE_A_BB) << 7) | (b << 8) | ((b & ~FILE_H_BB) << 9);
|
||||||
|
t.destinations[sq][KNIGHT] = attacks::knight[sq];
|
||||||
|
t.destinations[sq][BISHOP] = attacks::bishop(sq, 0);
|
||||||
|
t.destinations[sq][ROOK] = attacks::rook(sq, 0);
|
||||||
|
t.destinations[sq][QUEEN] = attacks::queen(sq, 0);
|
||||||
|
t.destinations[sq][KING] = attacks::king[sq];
|
||||||
|
}
|
||||||
|
int current = 0;
|
||||||
|
for (int pc = 0; pc < 6; pc++) {
|
||||||
|
for (int sq = 0; sq < 64; sq++) {
|
||||||
|
t.offsets[pc][sq] = current;
|
||||||
|
current += popcount(t.destinations[sq][pc]);
|
||||||
|
}
|
||||||
|
t.offsets[pc][64] = current;
|
||||||
|
}
|
||||||
|
return t;
|
||||||
|
}();
|
||||||
|
return t;
|
||||||
|
}
|
||||||
|
|
||||||
|
constexpr int PROMO_STRIDE = 22;
|
||||||
|
|
||||||
|
// Squares attacked by `side`, sliders seeing through the other side's king.
|
||||||
|
u64 threats_by(const Position& pos, int side) {
|
||||||
|
const u64 occ = pos.occupancy() ^ pos.pieces_of(side ^ 1, KING);
|
||||||
|
u64 threats = 0;
|
||||||
|
u64 b = pos.pieces_of(side, ROOK) | pos.pieces_of(side, QUEEN);
|
||||||
|
while (b) threats |= attacks::rook(pop_lsb(b), occ);
|
||||||
|
b = pos.pieces_of(side, BISHOP) | pos.pieces_of(side, QUEEN);
|
||||||
|
while (b) threats |= attacks::bishop(pop_lsb(b), occ);
|
||||||
|
b = pos.pieces_of(side, KNIGHT);
|
||||||
|
while (b) threats |= attacks::knight[pop_lsb(b)];
|
||||||
|
threats |= attacks::king[pos.king_square(side)];
|
||||||
|
b = pos.pieces_of(side, PAWN);
|
||||||
|
while (b) threats |= attacks::pawn[side][pop_lsb(b)];
|
||||||
|
return threats;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool set(std::vector<i8> data) {
|
||||||
|
// size = INPUTS * h + h + (h / 2) * OUTPUTS + OUTPUTS
|
||||||
|
const size_t per_hidden = INPUTS + 1 + OUTPUTS / 2;
|
||||||
|
if (data.size() <= OUTPUTS || (data.size() - OUTPUTS) % per_hidden) return false;
|
||||||
|
const int h = int((data.size() - OUTPUTS) / per_hidden);
|
||||||
|
if (h % 2) return false;
|
||||||
|
|
||||||
|
Network n;
|
||||||
|
n.hidden = h;
|
||||||
|
auto it = data.begin();
|
||||||
|
const auto take = [&](std::vector<i8>& v, size_t count) {
|
||||||
|
v.assign(it, it + std::ptrdiff_t(count));
|
||||||
|
it += std::ptrdiff_t(count);
|
||||||
|
};
|
||||||
|
take(n.l0w, size_t(INPUTS) * h);
|
||||||
|
take(n.l0b, h);
|
||||||
|
take(n.l1w, size_t(OUTPUTS) * (h / 2));
|
||||||
|
take(n.l1b, OUTPUTS);
|
||||||
|
net = std::move(n);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
bool load_builtin() {
|
||||||
|
#ifdef POLICYFILE
|
||||||
|
const auto* p = reinterpret_cast<const i8*>(gRigbyPolicyData);
|
||||||
|
return set(std::vector<i8>(p, p + gRigbyPolicySize));
|
||||||
|
#else
|
||||||
|
net = Network{};
|
||||||
|
return true;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
void init() {
|
||||||
|
tables();
|
||||||
|
if (!load_builtin()) {
|
||||||
|
std::fprintf(stderr, "built-in policy network has the wrong size\n");
|
||||||
|
net = Network{};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
bool load(const std::string& path) {
|
||||||
|
if (path.empty() || path == "<empty>") return load_builtin();
|
||||||
|
std::ifstream in(path, std::ios::binary);
|
||||||
|
if (!in) return false;
|
||||||
|
std::vector<char> raw((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
|
||||||
|
return set(std::vector<i8>(raw.begin(), raw.end()));
|
||||||
|
}
|
||||||
|
|
||||||
|
bool loaded() { return net.hidden > 0; }
|
||||||
|
|
||||||
|
int hidden() { return net.hidden; }
|
||||||
|
|
||||||
|
int move_index(const Position& pos, Move m) {
|
||||||
|
const Tables& t = tables();
|
||||||
|
const int hm = file_of(pos.king_square(pos.stm)) > 3 ? 7 : 0;
|
||||||
|
const int flip = hm ^ (pos.stm == BLACK ? 56 : 0);
|
||||||
|
const int src = m.from() ^ flip;
|
||||||
|
const int dst = m.to() ^ flip;
|
||||||
|
const int specials = t.offsets[KING][64];
|
||||||
|
|
||||||
|
if (m.is_promotion())
|
||||||
|
return specials + PROMO_STRIDE * (m.promo_type() - KNIGHT) + 2 * file_of(src) + file_of(dst);
|
||||||
|
if (m.is_castle()) return specials + 4 * PROMO_STRIDE + ((m.flag() == Move::KING_CASTLE) ^ (hm == 0));
|
||||||
|
if (m.flag() == Move::DOUBLE_PUSH) return specials + 4 * PROMO_STRIDE + 2 + file_of(src);
|
||||||
|
const int pc = piece_type(pos.piece_on(m.from()));
|
||||||
|
const u64 below = t.destinations[src][pc] & (bb(dst) - 1);
|
||||||
|
return t.offsets[pc][src] + popcount(below);
|
||||||
|
}
|
||||||
|
|
||||||
|
void logits(const Position& pos, const MoveList& moves, float* out) {
|
||||||
|
const int h = net.hidden;
|
||||||
|
const int half = h / 2;
|
||||||
|
const int us = pos.stm;
|
||||||
|
const int flip = (us == BLACK ? 56 : 0) ^ (file_of(pos.king_square(us)) > 3 ? 7 : 0);
|
||||||
|
const u64 threats = threats_by(pos, us ^ 1);
|
||||||
|
const u64 defences = threats_by(pos, us);
|
||||||
|
|
||||||
|
// Hidden layer: bias plus one column per active input.
|
||||||
|
static thread_local std::vector<i16> acc;
|
||||||
|
static thread_local std::vector<i16> act;
|
||||||
|
acc.resize(size_t(h));
|
||||||
|
act.resize(size_t(half));
|
||||||
|
for (int i = 0; i < h; i++) acc[i] = net.l0b[i];
|
||||||
|
|
||||||
|
u64 occ = pos.occupancy();
|
||||||
|
while (occ) {
|
||||||
|
const int sq = pop_lsb(occ);
|
||||||
|
const int piece = pos.piece_on(sq);
|
||||||
|
int feature = 384 * (piece_color(piece) != us) + 64 * piece_type(piece) + (sq ^ flip);
|
||||||
|
if (threats & bb(sq)) feature += 768;
|
||||||
|
if (defences & bb(sq)) feature += 1536;
|
||||||
|
const i8* w = &net.l0w[size_t(feature) * h];
|
||||||
|
for (int i = 0; i < h; i++) acc[i] = i16(acc[i] + w[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// CReLU on both halves, multiplied pairwise: values up to Q * Q.
|
||||||
|
for (int i = 0; i < half; i++) {
|
||||||
|
const int a = std::clamp<int>(acc[i], 0, Q);
|
||||||
|
const int b = std::clamp<int>(acc[i + half], 0, Q);
|
||||||
|
act[i] = i16(a * b);
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int m = 0; m < moves.size(); m++) {
|
||||||
|
const int idx = move_index(pos, moves[m]);
|
||||||
|
const i8* w = &net.l1w[size_t(idx) * half];
|
||||||
|
int sum = 0;
|
||||||
|
for (int i = 0; i < half; i++) sum += int(act[i]) * int(w[i]);
|
||||||
|
out[m] = float(sum) / float(Q * Q * Q) + float(net.l1b[idx]) / float(Q);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace rigby::policy
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
#include "position.h"
|
||||||
|
|
||||||
|
namespace rigby::policy {
|
||||||
|
|
||||||
|
// Policy network trained on Lc0 visit distributions (train/policy):
|
||||||
|
// 3072 threat inputs -> HIDDEN, CReLU, pairwise product (HIDDEN / 2), then one
|
||||||
|
// output row per move, i8 weights quantised by 128. HIDDEN is read from the
|
||||||
|
// file's size, so any trained width loads.
|
||||||
|
constexpr int INPUTS = 3072;
|
||||||
|
constexpr int OUTPUTS = 3920;
|
||||||
|
|
||||||
|
// Loads the network built into the binary (Makefile POLICYFILE), if there is one.
|
||||||
|
void init();
|
||||||
|
|
||||||
|
// Loads a network file, replacing the current one; an empty path goes back to
|
||||||
|
// the built-in network (or none). False, keeping the old one, if the file does
|
||||||
|
// not have the size of a network.
|
||||||
|
bool load(const std::string& path);
|
||||||
|
|
||||||
|
bool loaded();
|
||||||
|
int hidden();
|
||||||
|
|
||||||
|
// Raw logits of `moves` in `pos` (before any temperature). Requires loaded().
|
||||||
|
void logits(const Position& pos, const MoveList& moves, float* out);
|
||||||
|
|
||||||
|
// The output row of a move, as the trainer maps it (exposed for tests).
|
||||||
|
int move_index(const Position& pos, Move m);
|
||||||
|
|
||||||
|
} // namespace rigby::policy
|
||||||
@@ -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 i8 = std::int8_t;
|
||||||
using i16 = std::int16_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";
|
||||||
|
|||||||
+43
@@ -13,6 +13,7 @@
|
|||||||
#include "eval.h"
|
#include "eval.h"
|
||||||
#include "mcts.h"
|
#include "mcts.h"
|
||||||
#include "perft.h"
|
#include "perft.h"
|
||||||
|
#include "policy.h"
|
||||||
#include "position.h"
|
#include "position.h"
|
||||||
#include "pretty.h"
|
#include "pretty.h"
|
||||||
#include "uci_io.h"
|
#include "uci_io.h"
|
||||||
@@ -54,6 +55,8 @@ void print_id() {
|
|||||||
send("option name Threads type spin default 1 min 1 max 1");
|
send("option name Threads type spin default 1 min 1 max 1");
|
||||||
send("option name MoveOverhead type spin default 20 min 0 max 5000");
|
send("option name MoveOverhead type spin default 20 min 0 max 5000");
|
||||||
send("option name UCI_Chess960 type check default false");
|
send("option name UCI_Chess960 type check default false");
|
||||||
|
// A policy network file to use instead of the built-in one (or the move heuristics).
|
||||||
|
send("option name PolicyFile type string default <empty>");
|
||||||
// Search constants, exposed as integers (x100) so SPSA can tune them.
|
// Search constants, exposed as integers (x100) so SPSA can tune them.
|
||||||
send("option name CPuct type spin default 160 min 1 max 1000");
|
send("option name CPuct type spin default 160 min 1 max 1000");
|
||||||
send("option name RootCPuct type spin default 233 min 1 max 1000");
|
send("option name RootCPuct type spin default 233 min 1 max 1000");
|
||||||
@@ -75,6 +78,12 @@ void set_option(Engine& e, std::istringstream& is) {
|
|||||||
chess960 = value == "true";
|
chess960 = value == "true";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (lname == "policyfile") {
|
||||||
|
if (!policy::load(value)) send("info string cannot load policy network " + value);
|
||||||
|
else if (policy::loaded()) send("info string policy network " + std::to_string(policy::hidden()) + " hidden");
|
||||||
|
else send("info string no policy network, using move heuristics");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
int v = 0;
|
int v = 0;
|
||||||
try {
|
try {
|
||||||
@@ -269,6 +278,40 @@ void uci_loop() {
|
|||||||
std::snprintf(line, sizeof(line), "%6d cp %s", eval::static_eval(pos), fen);
|
std::snprintf(line, sizeof(line), "%6d cp %s", eval::static_eval(pos), fen);
|
||||||
send(line);
|
send(line);
|
||||||
}
|
}
|
||||||
|
} else if (cmd == "policyfens") {
|
||||||
|
// Same positions as the policy 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/4P3/8/PPPP1PPP/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/2P2k2/8/8/8/8/5K2/8 w - - 0 1",
|
||||||
|
};
|
||||||
|
if (!policy::loaded()) {
|
||||||
|
send("info string no policy network loaded");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
for (const char* fen : FENS) {
|
||||||
|
Position pos;
|
||||||
|
pos.set_fen(fen);
|
||||||
|
MoveList moves;
|
||||||
|
generate_legal(pos, moves);
|
||||||
|
float priors[256];
|
||||||
|
eval::policy(pos, moves, 1.0f, nullptr, priors);
|
||||||
|
std::vector<std::pair<float, std::string>> lines;
|
||||||
|
for (int i = 0; i < moves.size(); i++) lines.push_back({priors[i], pos.uci(moves[i])});
|
||||||
|
std::sort(lines.begin(), lines.end(), [](const auto& a, const auto& b) {
|
||||||
|
return a.first != b.first ? a.first > b.first : a.second < b.second;
|
||||||
|
});
|
||||||
|
send("");
|
||||||
|
send(fen);
|
||||||
|
for (const auto& [p, uci] : lines) {
|
||||||
|
char line[64];
|
||||||
|
std::snprintf(line, sizeof(line), " %-6s %6.2f%%", uci.c_str(), p * 100.0f);
|
||||||
|
send(line);
|
||||||
|
}
|
||||||
|
}
|
||||||
} else if (cmd == "perft") {
|
} else if (cmd == "perft") {
|
||||||
int depth = 5;
|
int depth = 5;
|
||||||
is >> depth;
|
is >> depth;
|
||||||
|
|||||||
+103
@@ -76,3 +76,106 @@ Data lives in `train/data/` and is not committed.
|
|||||||
runtime with NVRTC, no nvcc needed).
|
runtime with NVRTC, no nvcc needed).
|
||||||
3. `git clone https://github.com/jw1912/bullet` next to this repo.
|
3. `git clone https://github.com/jw1912/bullet` next to this repo.
|
||||||
4. `pip install zstandard` and a binpack from linrock's datasets in `train/data/`.
|
4. `pip install zstandard` and a binpack from linrock's datasets in `train/data/`.
|
||||||
|
|
||||||
|
## Policy network (`policy/`)
|
||||||
|
|
||||||
|
`3072 -> HIDDEN -> CReLU -> pairwise product (HIDDEN / 2) -> one row per move`,
|
||||||
|
softmax over the legal moves, trained on Lc0's visit distributions. The trainer is
|
||||||
|
montytrain's policy trainer (the one Monty, Vine and Jackal use; it adds two CUDA
|
||||||
|
operations to a pinned bullet revision), with Rigby's inputs and outputs and an Lc0
|
||||||
|
converter.
|
||||||
|
|
||||||
|
### Data
|
||||||
|
|
||||||
|
```
|
||||||
|
powershell -ExecutionPolicy Bypass -File C:\Users\rektd\repos\Rigby\train\policy\fetch.ps1 -From 20261025 -To 20261115
|
||||||
|
```
|
||||||
|
|
||||||
|
Downloads the hourly tars of an Lc0 run from
|
||||||
|
[storage.lczero.org/files/training_data](https://storage.lczero.org/files/training_data/)
|
||||||
|
(default `test91`, the active run in November 2026; test80 stopped in August 2025),
|
||||||
|
one day at a time: each day is converted to `data/lc0/monty/<run>-<day>.binpack` and
|
||||||
|
its tars are deleted. Days already converted are skipped, so an interrupted run can
|
||||||
|
be restarted. Finally every day file is shuffled into `data/lc0/policy.binpack`.
|
||||||
|
One hourly tar (~73 MB) holds ~350k positions, which take ~12 MB converted; about
|
||||||
|
three weeks of test91 (~40 GB of tars, ~190M positions) is plenty for a
|
||||||
|
10-superbatch run. The server limits each connection to ~2.3 MB/s (what a browser
|
||||||
|
gets) but not their number, so fetch.ps1 downloads 32 tars at a time across days
|
||||||
|
(`-Parallel`): 72 MB/s measured, about 10 minutes for three weeks.
|
||||||
|
|
||||||
|
Tars downloaded by hand can be converted directly:
|
||||||
|
|
||||||
|
```
|
||||||
|
target\release\lc02monty.exe ..\data\lc0\monty\mine.binpack <tar or folder of tars>... [--delete]
|
||||||
|
target\release\interleave.exe ..\data\lc0\policy.binpack ..\data\lc0\monty
|
||||||
|
```
|
||||||
|
|
||||||
|
`lc02monty` (`src/lc0.rs`) reads V6 records (classical input format), rebuilds each
|
||||||
|
game from its first position and the played moves, and checks every record: the
|
||||||
|
pieces must match and the moves Lc0 gave a probability must be exactly the legal
|
||||||
|
moves. A game is cut at the first record that fails (`LC0_DEBUG=1` prints why); on
|
||||||
|
test91 data nothing fails. Lc0 writes castling as the king taking its rook; Chess960
|
||||||
|
games (about 4%) are kept, the castling rooks taken as the outermost on each side.
|
||||||
|
Stored per position: the played move, best Q and the visit fractions of every legal
|
||||||
|
move (montyformat scales them to 0..255).
|
||||||
|
|
||||||
|
### Run
|
||||||
|
|
||||||
|
```
|
||||||
|
powershell -ExecutionPolicy Bypass -File C:\Users\rektd\repos\Rigby\train\policy\train.ps1
|
||||||
|
```
|
||||||
|
|
||||||
|
Default: 1024 hidden, 10 superbatches of 100M positions, about 17 minutes on the
|
||||||
|
RTX 3070 (~1M positions/s; 2048 hidden runs at ~400k/s). AdamW, weights clipped to
|
||||||
|
±0.99, LR 1e-3 decaying exponentially to 1e-5. Arguments:
|
||||||
|
|
||||||
|
| Argument | Default | Meaning |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| `--superbatches N` | 10 | Training length |
|
||||||
|
| `--hidden N` | 1024 | Hidden layer width (even) |
|
||||||
|
| `--id NAME` | `rigby-policy` | Checkpoint name |
|
||||||
|
| `--data FILE` | `../data/lc0/policy.binpack` | montyformat file |
|
||||||
|
| `--buffer-mb N` | 4096 | Shuffle buffer |
|
||||||
|
| `--batches N` | 6104 | Batches of 16384 per superbatch (smaller for test runs) |
|
||||||
|
|
||||||
|
Output: `policy/checkpoints/<id>-<superbatch>/quantised.bin` every 5 superbatches.
|
||||||
|
Try it in the engine with `setoption name PolicyFile value <path>`, or build it in
|
||||||
|
with `make POLICYFILE=<path>`.
|
||||||
|
|
||||||
|
### Network format
|
||||||
|
|
||||||
|
`quantised.bin`, `i8`, every weight times 128, no header (the engine works out
|
||||||
|
HIDDEN from the size: `3072 * H + H + (H / 2) * 3920 + 3920` bytes):
|
||||||
|
|
||||||
|
| Part | Shape |
|
||||||
|
| --- | --- |
|
||||||
|
| `l0w` | 3072 x H, feature-major |
|
||||||
|
| `l0b` | H |
|
||||||
|
| `l1w` | 3920 x H/2, move-major |
|
||||||
|
| `l1b` | 3920 |
|
||||||
|
|
||||||
|
Inputs, relative to the side to move (`src/inputs.rs`, `src/policy.cpp`): squares
|
||||||
|
flipped vertically for black and horizontally when its king is on files e-h;
|
||||||
|
`384 * theirs + 64 * piece + square`, plus 768 if the opponent attacks the square
|
||||||
|
and 1536 if the side to move defends it (attacks of sliders see through the other
|
||||||
|
side's king). Outputs: one row per (piece, from, to) reachable on an empty board,
|
||||||
|
then 4 x 22 promotions, 2 castling rows and 8 double pushes, in the same flipped
|
||||||
|
frame. Hidden: `clamp(acc[i], 0, 1) * clamp(acc[i + H/2], 0, 1)`.
|
||||||
|
|
||||||
|
### Checking the engine's inference
|
||||||
|
|
||||||
|
`train.ps1 --check checkpoints\<id>-<superbatch> --hidden <H>` prints the trainer's
|
||||||
|
(float) policy of fixed positions; the engine's `policyfens` command prints the
|
||||||
|
same with the quantised network. They agree to a few tenths of a percent, a few
|
||||||
|
percent on very sharp distributions (rigby-policy-v1, 1.e4 e5: 80.2% vs 75.3%).
|
||||||
|
|
||||||
|
### Networks
|
||||||
|
|
||||||
|
| File | Data | Hidden | Superbatches | Final loss |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| `networks/rigby-policy-v1.bin` | test91 2026-10-25 .. 11-15 (171M positions) | 1024 | 10 (10 min) | 2.296 |
|
||||||
|
|
||||||
|
### Setup
|
||||||
|
|
||||||
|
As for the value trainer, plus: the pinned bullet revision's `cudarc` does not know
|
||||||
|
CUDA 13.3, so `env.ps1` sets `CUDARC_CUDA_VERSION=13000` (13.3 is compatible).
|
||||||
Generated
+556
@@ -0,0 +1,556 @@
|
|||||||
|
# This file is automatically @generated by Cargo.
|
||||||
|
# It is not intended for manual editing.
|
||||||
|
version = 4
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "acyclib"
|
||||||
|
version = "0.3.0"
|
||||||
|
source = "git+https://github.com/jw1912/bullet?rev=73618a4359ec44b48ae64ba63f49c247e7d200b9#73618a4359ec44b48ae64ba63f49c247e7d200b9"
|
||||||
|
dependencies = [
|
||||||
|
"parking_lot",
|
||||||
|
"rand",
|
||||||
|
"rand_distr",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "adler2"
|
||||||
|
version = "2.0.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "autocfg"
|
||||||
|
version = "1.5.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bitflags"
|
||||||
|
version = "2.9.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2261d10cca569e4643e526d8dc2e62e433cc8aba21ab764233731f8d369bf394"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "bullet_cuda_backend"
|
||||||
|
version = "0.1.0"
|
||||||
|
source = "git+https://github.com/jw1912/bullet?rev=73618a4359ec44b48ae64ba63f49c247e7d200b9#73618a4359ec44b48ae64ba63f49c247e7d200b9"
|
||||||
|
dependencies = [
|
||||||
|
"acyclib",
|
||||||
|
"cudarc",
|
||||||
|
"parking_lot",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cfg-if"
|
||||||
|
version = "1.0.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2fd1289c04a9ea8cb22300a459a72a385d7c73d3259e2ed7dcb2af674838cfa9"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "crc32fast"
|
||||||
|
version = "1.5.5"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "cudarc"
|
||||||
|
version = "0.17.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "72ba848ae5c6f3cb36e71eab5f268763e3fabcabe3f7bc683e16f7fa3d46281e"
|
||||||
|
dependencies = [
|
||||||
|
"libloading",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "errno"
|
||||||
|
version = "0.3.15"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "filetime"
|
||||||
|
version = "0.2.29"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"libc",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "flate2"
|
||||||
|
version = "1.1.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4"
|
||||||
|
dependencies = [
|
||||||
|
"crc32fast",
|
||||||
|
"miniz_oxide",
|
||||||
|
"zlib-rs",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "getrandom"
|
||||||
|
version = "0.3.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "26145e563e54f2cadc477553f1ec5ee650b00862f0a58bcd12cbdc5f0ea2d2f4"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"libc",
|
||||||
|
"r-efi",
|
||||||
|
"wasi",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "libc"
|
||||||
|
version = "0.2.175"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6a82ae493e598baaea5209805c49bbf2ea7de956d50d7da0da1164f9c6d28543"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "libloading"
|
||||||
|
version = "0.8.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "07033963ba89ebaf1584d767badaa2e8fcec21aedea6b8c0346d487d49c28667"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"windows-targets 0.53.3",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "libm"
|
||||||
|
version = "0.2.15"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f9fbbcab51052fe104eb5e5d351cf728d30a5be1fe14d9be8a3b097481fb97de"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "linux-raw-sys"
|
||||||
|
version = "0.11.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "df1d3c3b53da64cf5760482273a98e575c651a67eec7f77df96b5b642de8f039"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "lock_api"
|
||||||
|
version = "0.4.13"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "96936507f153605bddfcda068dd804796c84324ed2510809e5b2a624c81da765"
|
||||||
|
dependencies = [
|
||||||
|
"autocfg",
|
||||||
|
"scopeguard",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "miniz_oxide"
|
||||||
|
version = "0.9.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c"
|
||||||
|
dependencies = [
|
||||||
|
"adler2",
|
||||||
|
"simd-adler32",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "montyformat"
|
||||||
|
version = "0.9.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "4caf9c718f831a8568f030576e6a6e6aa487ed5f8732ddb0ba79e9a3ea0421ca"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "num-traits"
|
||||||
|
version = "0.2.19"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
||||||
|
dependencies = [
|
||||||
|
"autocfg",
|
||||||
|
"libm",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "parking_lot"
|
||||||
|
version = "0.12.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "70d58bf43669b5795d1576d0641cfb6fbb2057bf629506267a92807158584a13"
|
||||||
|
dependencies = [
|
||||||
|
"lock_api",
|
||||||
|
"parking_lot_core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "parking_lot_core"
|
||||||
|
version = "0.9.11"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "bc838d2a56b5b1a6c25f55575dfc605fabb63bb2365f6c2353ef9159aa69e4a5"
|
||||||
|
dependencies = [
|
||||||
|
"cfg-if",
|
||||||
|
"libc",
|
||||||
|
"redox_syscall",
|
||||||
|
"smallvec",
|
||||||
|
"windows-targets 0.52.6",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "ppv-lite86"
|
||||||
|
version = "0.2.21"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
||||||
|
dependencies = [
|
||||||
|
"zerocopy",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "proc-macro2"
|
||||||
|
version = "1.0.101"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "89ae43fd86e4158d6db51ad8e2b80f313af9cc74f5c0e03ccb87de09998732de"
|
||||||
|
dependencies = [
|
||||||
|
"unicode-ident",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "quote"
|
||||||
|
version = "1.0.40"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "r-efi"
|
||||||
|
version = "5.3.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rand"
|
||||||
|
version = "0.9.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
|
||||||
|
dependencies = [
|
||||||
|
"rand_chacha",
|
||||||
|
"rand_core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rand_chacha"
|
||||||
|
version = "0.9.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
||||||
|
dependencies = [
|
||||||
|
"ppv-lite86",
|
||||||
|
"rand_core",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rand_core"
|
||||||
|
version = "0.9.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38"
|
||||||
|
dependencies = [
|
||||||
|
"getrandom",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rand_distr"
|
||||||
|
version = "0.5.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "6a8615d50dcf34fa31f7ab52692afec947c4dd0ab803cc87cb3b0b4570ff7463"
|
||||||
|
dependencies = [
|
||||||
|
"num-traits",
|
||||||
|
"rand",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "redox_syscall"
|
||||||
|
version = "0.5.17"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5407465600fb0548f1442edf71dd20683c6ed326200ace4b1ef0763521bb3b77"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rigby-policy"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"acyclib",
|
||||||
|
"bullet_cuda_backend",
|
||||||
|
"flate2",
|
||||||
|
"montyformat",
|
||||||
|
"tar",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "rustix"
|
||||||
|
version = "1.1.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "cd15f8a2c5551a84d56efdc1cd049089e409ac19a3072d5037a17fd70719ff3e"
|
||||||
|
dependencies = [
|
||||||
|
"bitflags",
|
||||||
|
"errno",
|
||||||
|
"libc",
|
||||||
|
"linux-raw-sys",
|
||||||
|
"windows-sys",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "scopeguard"
|
||||||
|
version = "1.2.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "simd-adler32"
|
||||||
|
version = "0.3.10"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "smallvec"
|
||||||
|
version = "1.15.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "67b1b7a3b5fe4f1376887184045fcf45c69e92af734b7aaddc05fb777b6fbd03"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "syn"
|
||||||
|
version = "2.0.106"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ede7c438028d4436d71104916910f5bb611972c5cfd7f89b8300a8186e6fada6"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"unicode-ident",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "tar"
|
||||||
|
version = "0.4.46"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840"
|
||||||
|
dependencies = [
|
||||||
|
"filetime",
|
||||||
|
"libc",
|
||||||
|
"xattr",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "unicode-ident"
|
||||||
|
version = "1.0.19"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f63a545481291138910575129486daeaf8ac54aee4387fe7906919f7830c7d9d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wasi"
|
||||||
|
version = "0.14.7+wasi-0.2.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "883478de20367e224c0090af9cf5f9fa85bed63a95c1abf3afc5c083ebc06e8c"
|
||||||
|
dependencies = [
|
||||||
|
"wasip2",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wasip2"
|
||||||
|
version = "1.0.1+wasi-0.2.4"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7"
|
||||||
|
dependencies = [
|
||||||
|
"wit-bindgen",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-link"
|
||||||
|
version = "0.1.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-link"
|
||||||
|
version = "0.2.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-sys"
|
||||||
|
version = "0.61.2"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
||||||
|
dependencies = [
|
||||||
|
"windows-link 0.2.1",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-targets"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
|
||||||
|
dependencies = [
|
||||||
|
"windows_aarch64_gnullvm 0.52.6",
|
||||||
|
"windows_aarch64_msvc 0.52.6",
|
||||||
|
"windows_i686_gnu 0.52.6",
|
||||||
|
"windows_i686_gnullvm 0.52.6",
|
||||||
|
"windows_i686_msvc 0.52.6",
|
||||||
|
"windows_x86_64_gnu 0.52.6",
|
||||||
|
"windows_x86_64_gnullvm 0.52.6",
|
||||||
|
"windows_x86_64_msvc 0.52.6",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows-targets"
|
||||||
|
version = "0.53.3"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "d5fe6031c4041849d7c496a8ded650796e7b6ecc19df1a431c1a363342e5dc91"
|
||||||
|
dependencies = [
|
||||||
|
"windows-link 0.1.3",
|
||||||
|
"windows_aarch64_gnullvm 0.53.0",
|
||||||
|
"windows_aarch64_msvc 0.53.0",
|
||||||
|
"windows_i686_gnu 0.53.0",
|
||||||
|
"windows_i686_gnullvm 0.53.0",
|
||||||
|
"windows_i686_msvc 0.53.0",
|
||||||
|
"windows_x86_64_gnu 0.53.0",
|
||||||
|
"windows_x86_64_gnullvm 0.53.0",
|
||||||
|
"windows_x86_64_msvc 0.53.0",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_aarch64_gnullvm"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_aarch64_gnullvm"
|
||||||
|
version = "0.53.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "86b8d5f90ddd19cb4a147a5fa63ca848db3df085e25fee3cc10b39b6eebae764"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_aarch64_msvc"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_aarch64_msvc"
|
||||||
|
version = "0.53.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c7651a1f62a11b8cbd5e0d42526e55f2c99886c77e007179efff86c2b137e66c"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_i686_gnu"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_i686_gnu"
|
||||||
|
version = "0.53.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "c1dc67659d35f387f5f6c479dc4e28f1d4bb90ddd1a5d3da2e5d97b42d6272c3"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_i686_gnullvm"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_i686_gnullvm"
|
||||||
|
version = "0.53.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "9ce6ccbdedbf6d6354471319e781c0dfef054c81fbc7cf83f338a4296c0cae11"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_i686_msvc"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_i686_msvc"
|
||||||
|
version = "0.53.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "581fee95406bb13382d2f65cd4a908ca7b1e4c2f1917f143ba16efe98a589b5d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_x86_64_gnu"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_x86_64_gnu"
|
||||||
|
version = "0.53.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "2e55b5ac9ea33f2fc1716d1742db15574fd6fc8dadc51caab1c16a3d3b4190ba"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_x86_64_gnullvm"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_x86_64_gnullvm"
|
||||||
|
version = "0.53.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0a6e035dd0599267ce1ee132e51c27dd29437f63325753051e71dd9e42406c57"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_x86_64_msvc"
|
||||||
|
version = "0.52.6"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "windows_x86_64_msvc"
|
||||||
|
version = "0.53.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "271414315aff87387382ec3d271b52d7ae78726f5d44ac98b4f4030c91880486"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "wit-bindgen"
|
||||||
|
version = "0.46.0"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "xattr"
|
||||||
|
version = "1.6.1"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156"
|
||||||
|
dependencies = [
|
||||||
|
"libc",
|
||||||
|
"rustix",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zerocopy"
|
||||||
|
version = "0.8.27"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "0894878a5fa3edfd6da3f88c4805f4c8558e2b996227a3d864f47fe11e38282c"
|
||||||
|
dependencies = [
|
||||||
|
"zerocopy-derive",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zerocopy-derive"
|
||||||
|
version = "0.8.27"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "88d2b8d9c68ad2b9e4340d7832716a4d21a22a1154777ad56ea55c51a9cf3831"
|
||||||
|
dependencies = [
|
||||||
|
"proc-macro2",
|
||||||
|
"quote",
|
||||||
|
"syn",
|
||||||
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "zlib-rs"
|
||||||
|
version = "0.6.8"
|
||||||
|
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||||
|
checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
[package]
|
||||||
|
name = "rigby-policy"
|
||||||
|
version = "0.1.0"
|
||||||
|
edition = "2021"
|
||||||
|
publish = false
|
||||||
|
default-run = "rigby-policy"
|
||||||
|
|
||||||
|
# Trains Rigby's policy network on Lc0 self-play data.
|
||||||
|
# Based on montytrain's policy trainer (github.com/TomaszJaworski777/montytrain,
|
||||||
|
# the trainer Monty, Vine and Jackal use), which builds on a pinned bullet
|
||||||
|
# revision with two custom CUDA operations.
|
||||||
|
[dependencies]
|
||||||
|
acyclib = { package = "acyclib", git = 'https://github.com/jw1912/bullet', rev = "73618a4359ec44b48ae64ba63f49c247e7d200b9" }
|
||||||
|
bullet_cuda_backend = { package = "bullet_cuda_backend", git = 'https://github.com/jw1912/bullet', rev = "73618a4359ec44b48ae64ba63f49c247e7d200b9" }
|
||||||
|
montyformat = "0.9.2"
|
||||||
|
flate2 = "1"
|
||||||
|
tar = "0.4"
|
||||||
|
|
||||||
|
[profile.release]
|
||||||
|
lto = true
|
||||||
|
codegen-units = 1
|
||||||
|
panic = "abort"
|
||||||
@@ -0,0 +1,6 @@
|
|||||||
|
# Shared by fetch.ps1 and train.ps1: CUDA and cargo on the PATH.
|
||||||
|
# The pinned bullet revision's cudarc only knows CUDA up to 13.0; 13.3 is
|
||||||
|
# ABI-compatible, so it is told to build for 13.0.
|
||||||
|
$env:CUDA_PATH = 'C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v13.3'
|
||||||
|
$env:CUDARC_CUDA_VERSION = '13000'
|
||||||
|
$env:PATH = "$env:USERPROFILE\.cargo\bin;$env:CUDA_PATH\bin\x64;$env:CUDA_PATH\bin;$env:PATH"
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
# Downloads Lc0 self-play data and converts it to montyformat for the policy trainer.
|
||||||
|
# powershell -ExecutionPolicy Bypass -File C:\Users\rektd\repos\Rigby\train\policy\fetch.ps1
|
||||||
|
# ... fetch.ps1 -From 20261025 -To 20261115 -Run test91 -Parallel 32
|
||||||
|
# Default: the last three weeks of test91 (about 40 GB of tars, 190M positions).
|
||||||
|
#
|
||||||
|
# The server limits each connection to about 2.3 MB/s but not their number
|
||||||
|
# (32 connections: ~72 MB/s), so tars are downloaded -Parallel at a time, in
|
||||||
|
# batches of whole days (about two tars per connection) into data\lc0\staging.
|
||||||
|
# Each day of a batch is then converted into data\lc0\monty\<run>-<day>.binpack
|
||||||
|
# and its tars deleted, so the disk only holds one batch of tars. Days already
|
||||||
|
# converted are skipped, so an interrupted run can simply be started again. At
|
||||||
|
# the end every day file is shuffled into data\lc0\policy.binpack, which is
|
||||||
|
# what train.ps1 reads.
|
||||||
|
param(
|
||||||
|
[string] $From = (Get-Date).AddDays(-21).ToString('yyyyMMdd'),
|
||||||
|
[string] $To = (Get-Date -Format 'yyyyMMdd'),
|
||||||
|
[string] $Run = 'test91',
|
||||||
|
[int] $Parallel = 32,
|
||||||
|
[switch] $NoInterleave
|
||||||
|
)
|
||||||
|
|
||||||
|
# Native tools report through exit codes; 'Stop' would turn cargo's progress
|
||||||
|
# output on stderr into errors under Windows PowerShell.
|
||||||
|
$ErrorActionPreference = 'Continue'
|
||||||
|
Set-Location $PSScriptRoot
|
||||||
|
|
||||||
|
. .\env.ps1
|
||||||
|
cargo build --release --bins
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw 'build failed' }
|
||||||
|
|
||||||
|
$base = "https://storage.lczero.org/files/training_data/$Run/"
|
||||||
|
$data = (Resolve-Path '..\data').Path
|
||||||
|
$monty = Join-Path $data 'lc0\monty'
|
||||||
|
$staging = Join-Path $data 'lc0\staging'
|
||||||
|
New-Item -ItemType Directory -Force $monty, $staging | Out-Null
|
||||||
|
|
||||||
|
# The directory listing: name, date and size of every hourly tar. Empty tars
|
||||||
|
# (10240 bytes) are hours without games.
|
||||||
|
Write-Host "Listing $base ..."
|
||||||
|
$html = (Invoke-WebRequest -UseBasicParsing $base).Content
|
||||||
|
$tars = [regex]::Matches($html, '>(training-[^<]+-(\d{8})-\d{4}\.tar)</a>\s+\S+\s+\S+\s+(\d+)') |
|
||||||
|
ForEach-Object { [pscustomobject]@{ Name = $_.Groups[1].Value; Day = $_.Groups[2].Value; Size = [long]$_.Groups[3].Value } } |
|
||||||
|
Where-Object { $_.Day -ge $From -and $_.Day -le $To -and $_.Size -gt 10240 }
|
||||||
|
$days = $tars | Group-Object Day | Sort-Object Name
|
||||||
|
$totalGb = ($tars | Measure-Object Size -Sum).Sum / 1e9
|
||||||
|
Write-Host ("{0} tars over {1} days, {2:N1} GB to download" -f $tars.Count, $days.Count, $totalGb)
|
||||||
|
|
||||||
|
$pending = @($days | Where-Object { -not (Test-Path (Join-Path $monty "$Run-$($_.Name).binpack")) })
|
||||||
|
$done = $days.Count - $pending.Count
|
||||||
|
if ($done) { Write-Host "$done days already converted" }
|
||||||
|
|
||||||
|
while ($pending.Count) {
|
||||||
|
# Whole days until the batch has about two tars per connection.
|
||||||
|
$batch = @()
|
||||||
|
$count = 0
|
||||||
|
while ($pending.Count -and ($batch.Count -eq 0 -or $count -lt 2 * $Parallel)) {
|
||||||
|
$batch += $pending[0]
|
||||||
|
$count += $pending[0].Count
|
||||||
|
$pending = @($pending | Select-Object -Skip 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
if (Test-Path $staging) { Remove-Item -Recurse -Force $staging }
|
||||||
|
New-Item -ItemType Directory -Force $staging | Out-Null
|
||||||
|
$config = Join-Path $staging 'curl.txt'
|
||||||
|
# Forward slashes: curl reads backslashes in a config file as escapes.
|
||||||
|
$lines = foreach ($day in $batch) {
|
||||||
|
$dir = Join-Path $staging $day.Name
|
||||||
|
New-Item -ItemType Directory -Force $dir | Out-Null
|
||||||
|
foreach ($tar in $day.Group) {
|
||||||
|
"url = `"$base$($tar.Name)`"`noutput = `"$((Join-Path $dir $tar.Name) -replace '\\', '/')`""
|
||||||
|
}
|
||||||
|
}
|
||||||
|
$lines | Set-Content -Encoding ascii $config
|
||||||
|
$gb = ($batch.Group | Measure-Object Size -Sum).Sum / 1e9
|
||||||
|
$start = Get-Date
|
||||||
|
Write-Host ("{0}..{1}: downloading {2} tars ({3:N2} GB)" -f $batch[0].Name, $batch[-1].Name, $count, $gb)
|
||||||
|
curl.exe -sSf --retry 5 -Z --parallel-max $Parallel -K $config
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "download failed for $($batch[0].Name)..$($batch[-1].Name)" }
|
||||||
|
$secs = ((Get-Date) - $start).TotalSeconds
|
||||||
|
Write-Host (" {0:N0} MB/s" -f ($gb * 1000 / [math]::Max($secs, 1)))
|
||||||
|
|
||||||
|
foreach ($day in $batch) {
|
||||||
|
$out = Join-Path $monty "$Run-$($day.Name).binpack"
|
||||||
|
& .\target\release\lc02monty.exe "$out.part" (Join-Path $staging $day.Name) --delete | Select-Object -Last 9
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw "conversion failed for $($day.Name)" }
|
||||||
|
Move-Item -Force "$out.part" $out
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (Test-Path $staging) { Remove-Item -Recurse -Force $staging }
|
||||||
|
|
||||||
|
if (-not $NoInterleave) {
|
||||||
|
$policy = Join-Path $data 'lc0\policy.binpack'
|
||||||
|
Write-Host "Shuffling the day files into $policy ..."
|
||||||
|
& .\target\release\interleave.exe "$policy.part" $monty
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw 'interleave failed' }
|
||||||
|
Move-Item -Force "$policy.part" $policy
|
||||||
|
Write-Host ("Done: {0:N1} GB in {1}" -f ((Get-Item $policy).Length / 1e9), $policy)
|
||||||
|
}
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
use_small_heuristics = "Max"
|
||||||
|
single_line_if_else_max_width = 100
|
||||||
|
max_width = 120
|
||||||
@@ -0,0 +1,111 @@
|
|||||||
|
//! Shuffles montyformat files into one, game by game, picking each next game
|
||||||
|
//! from a file chosen in proportion to the bytes it has left.
|
||||||
|
//!
|
||||||
|
//! interleave <out.binpack> <file or directory of .binpack files>...
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
fs::{self, File},
|
||||||
|
io::{BufReader, BufWriter, Write},
|
||||||
|
};
|
||||||
|
|
||||||
|
use montyformat::{FastDeserialise, MontyFormat};
|
||||||
|
|
||||||
|
fn main() -> std::io::Result<()> {
|
||||||
|
let mut args = std::env::args().skip(1);
|
||||||
|
let output = args.next().expect("usage: interleave <out> <file|dir>...");
|
||||||
|
let mut inputs: Vec<String> = Vec::new();
|
||||||
|
for arg in args {
|
||||||
|
let path = std::path::Path::new(&arg);
|
||||||
|
if path.is_dir() {
|
||||||
|
let mut files: Vec<String> = fs::read_dir(path)?
|
||||||
|
.filter_map(|e| e.ok().map(|e| e.path()))
|
||||||
|
.filter(|p| p.is_file() && p.extension().and_then(|e| e.to_str()) == Some("binpack"))
|
||||||
|
.map(|p| p.to_string_lossy().into_owned())
|
||||||
|
.collect();
|
||||||
|
files.sort();
|
||||||
|
inputs.extend(files);
|
||||||
|
} else {
|
||||||
|
inputs.push(arg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(!inputs.is_empty(), "no input files");
|
||||||
|
assert!(!inputs.contains(&output), "the output must not be one of the inputs");
|
||||||
|
|
||||||
|
println!("Writing to {output:#?}");
|
||||||
|
println!("Reading from:\n{inputs:#?}");
|
||||||
|
let mut streams = Vec::new();
|
||||||
|
let mut total = 0;
|
||||||
|
|
||||||
|
let target = File::create(&output)?;
|
||||||
|
let mut writer = BufWriter::new(target);
|
||||||
|
|
||||||
|
for path in &inputs {
|
||||||
|
let file = File::open(path)?;
|
||||||
|
|
||||||
|
let count = file.metadata()?.len();
|
||||||
|
|
||||||
|
if count > 0 {
|
||||||
|
streams.push((count, BufReader::new(file)));
|
||||||
|
total += count;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut remaining = total;
|
||||||
|
let mut rng = RandU64::default();
|
||||||
|
|
||||||
|
const INTERVAL: u64 = 1024 * 1024 * 256;
|
||||||
|
let mut prev = remaining / INTERVAL;
|
||||||
|
|
||||||
|
let mut buffer = Vec::new();
|
||||||
|
|
||||||
|
while remaining > 0 {
|
||||||
|
let mut spot = rng.rand() % remaining;
|
||||||
|
let mut idx = 0;
|
||||||
|
while streams[idx].0 < spot {
|
||||||
|
spot -= streams[idx].0;
|
||||||
|
idx += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
let (count, reader) = &mut streams[idx];
|
||||||
|
|
||||||
|
MontyFormat::deserialise_fast_into_buffer(reader, &mut buffer)?;
|
||||||
|
writer.write_all(&buffer)?;
|
||||||
|
|
||||||
|
let size = buffer.len() as u64;
|
||||||
|
|
||||||
|
remaining -= size;
|
||||||
|
*count -= size;
|
||||||
|
if *count == 0 {
|
||||||
|
streams.swap_remove(idx);
|
||||||
|
}
|
||||||
|
|
||||||
|
if remaining / INTERVAL < prev {
|
||||||
|
prev = remaining / INTERVAL;
|
||||||
|
let written = total - remaining;
|
||||||
|
print!("Written {written}/{total} Bytes ({:.2}%)\r", written as f64 / total as f64 * 100.0);
|
||||||
|
let _ = std::io::stdout().flush();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
struct RandU64(u64);
|
||||||
|
|
||||||
|
impl Default for RandU64 {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self(
|
||||||
|
(std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).expect("valid").as_nanos()
|
||||||
|
& 0xFFFF_FFFF_FFFF_FFFF) as u64,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RandU64 {
|
||||||
|
fn rand(&mut self) -> u64 {
|
||||||
|
self.0 ^= self.0 << 13;
|
||||||
|
self.0 ^= self.0 >> 7;
|
||||||
|
self.0 ^= self.0 << 17;
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,132 @@
|
|||||||
|
//! Converts Lc0 V6 training data tars into one montyformat file.
|
||||||
|
//!
|
||||||
|
//! lc02monty <out.binpack> <tar or directory of tars>... [--threads N] [--delete]
|
||||||
|
//!
|
||||||
|
//! Games are appended to the output, so a run can be repeated with new tars.
|
||||||
|
//! `--delete` removes each tar once its games are written (for streaming
|
||||||
|
//! large downloads through a small disk).
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
fs::{File, OpenOptions},
|
||||||
|
io::{BufWriter, Read, Write},
|
||||||
|
path::PathBuf,
|
||||||
|
sync::{mpsc, Arc, Mutex},
|
||||||
|
};
|
||||||
|
|
||||||
|
use flate2::read::GzDecoder;
|
||||||
|
use rigby_policy::lc0::{convert_game, PolicyMap, Stats};
|
||||||
|
|
||||||
|
fn convert_tar(path: &PathBuf, map: &PolicyMap) -> std::io::Result<(Vec<u8>, Stats)> {
|
||||||
|
let mut stats = Stats::default();
|
||||||
|
let mut out = Vec::new();
|
||||||
|
let mut archive = tar::Archive::new(File::open(path)?);
|
||||||
|
let mut raw = Vec::new();
|
||||||
|
let mut buf = Vec::new();
|
||||||
|
for entry in archive.entries()? {
|
||||||
|
let mut entry = entry?;
|
||||||
|
if !entry.path()?.to_string_lossy().ends_with(".gz") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
raw.clear();
|
||||||
|
entry.read_to_end(&mut raw)?;
|
||||||
|
let mut data = Vec::new();
|
||||||
|
if GzDecoder::new(&raw[..]).read_to_end(&mut data).is_err() {
|
||||||
|
stats.bad_format += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(game) = convert_game(&data, map, &mut stats) {
|
||||||
|
buf.clear();
|
||||||
|
game.serialise_into_buffer(&mut buf)?;
|
||||||
|
out.extend_from_slice(&buf);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok((out, stats))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let mut args = std::env::args().skip(1);
|
||||||
|
let out_path = args.next().expect("usage: lc02monty <out> <tar|dir>... [--threads N] [--delete]");
|
||||||
|
let mut inputs = Vec::new();
|
||||||
|
let mut threads = std::thread::available_parallelism().map(|n| n.get()).unwrap_or(4);
|
||||||
|
let mut delete = false;
|
||||||
|
while let Some(arg) = args.next() {
|
||||||
|
match arg.as_str() {
|
||||||
|
"--threads" => threads = args.next().expect("--threads needs a number").parse().expect("not a number"),
|
||||||
|
"--delete" => delete = true,
|
||||||
|
path => {
|
||||||
|
let p = PathBuf::from(path);
|
||||||
|
if p.is_dir() {
|
||||||
|
let mut tars: Vec<PathBuf> = std::fs::read_dir(&p)
|
||||||
|
.expect("cannot read directory")
|
||||||
|
.filter_map(|e| e.ok().map(|e| e.path()))
|
||||||
|
.filter(|p| p.extension().is_some_and(|e| e == "tar"))
|
||||||
|
.collect();
|
||||||
|
tars.sort();
|
||||||
|
inputs.extend(tars);
|
||||||
|
} else {
|
||||||
|
inputs.push(p);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(!inputs.is_empty(), "no input tars");
|
||||||
|
|
||||||
|
let total_tars = inputs.len();
|
||||||
|
let queue = Arc::new(Mutex::new(inputs.into_iter()));
|
||||||
|
let map = Arc::new(PolicyMap::default());
|
||||||
|
let (sender, receiver) = mpsc::sync_channel::<(PathBuf, std::io::Result<(Vec<u8>, Stats)>)>(threads);
|
||||||
|
|
||||||
|
for _ in 0..threads {
|
||||||
|
let queue = queue.clone();
|
||||||
|
let map = map.clone();
|
||||||
|
let sender = sender.clone();
|
||||||
|
std::thread::spawn(move || loop {
|
||||||
|
let Some(path) = queue.lock().unwrap().next() else { break };
|
||||||
|
let result = convert_tar(&path, &map);
|
||||||
|
if sender.send((path, result)).is_err() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
drop(sender);
|
||||||
|
|
||||||
|
let file = OpenOptions::new().create(true).append(true).open(&out_path).expect("cannot open output");
|
||||||
|
let mut writer = BufWriter::with_capacity(1 << 24, file);
|
||||||
|
let mut total = Stats::default();
|
||||||
|
let mut done = 0;
|
||||||
|
let mut bytes = 0u64;
|
||||||
|
|
||||||
|
for (path, result) in receiver {
|
||||||
|
done += 1;
|
||||||
|
match result {
|
||||||
|
Ok((data, stats)) => {
|
||||||
|
writer.write_all(&data).expect("write failed");
|
||||||
|
bytes += data.len() as u64;
|
||||||
|
total.add(&stats);
|
||||||
|
if delete {
|
||||||
|
writer.flush().expect("flush failed");
|
||||||
|
let _ = std::fs::remove_file(&path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => eprintln!("skipping {}: {e}", path.display()),
|
||||||
|
}
|
||||||
|
println!(
|
||||||
|
"[{done}/{total_tars}] {} games, {} positions, {:.1} MB written",
|
||||||
|
total.games,
|
||||||
|
total.positions,
|
||||||
|
bytes as f64 / 1e6
|
||||||
|
);
|
||||||
|
}
|
||||||
|
writer.flush().expect("flush failed");
|
||||||
|
|
||||||
|
let kept = total.positions as f64;
|
||||||
|
let dropped = total.dropped_records as f64;
|
||||||
|
println!("games kept : {}", total.games);
|
||||||
|
println!("positions kept : {}", total.positions);
|
||||||
|
println!("records dropped : {} ({:.3}%)", total.dropped_records, 100.0 * dropped / (kept + dropped).max(1.0));
|
||||||
|
println!(" bad format : {} games", total.bad_format);
|
||||||
|
println!(" bad start : {} games", total.bad_start);
|
||||||
|
println!(" board mismatch : {} cuts", total.cut_board);
|
||||||
|
println!(" move mismatch : {} cuts", total.cut_moves);
|
||||||
|
println!(" played not found: {} cuts", total.cut_played);
|
||||||
|
}
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
pub mod loader;
|
||||||
|
pub mod reader;
|
||||||
|
|
||||||
|
pub use loader::MontyDataLoader;
|
||||||
@@ -0,0 +1,126 @@
|
|||||||
|
use acyclib::{
|
||||||
|
device::tensor::Shape,
|
||||||
|
trainer::{
|
||||||
|
dataloader::{DataLoader, HostDenseMatrix, HostMatrix, HostSparseMatrix, PreparedBatchHost},
|
||||||
|
DataLoadingError,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use montyformat::chess::Move;
|
||||||
|
|
||||||
|
use super::reader::{DataReader, DecompressedData};
|
||||||
|
use crate::inputs::{self, INPUT_SIZE, MAX_ACTIVE_BASE, MAX_MOVES, NUM_MOVES_INDICES};
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct MontyDataLoader {
|
||||||
|
reader: DataReader,
|
||||||
|
threads: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl MontyDataLoader {
|
||||||
|
pub fn new(path: &str, buffer_size_mb: usize, reader_threads: usize, loader_threads: usize) -> Self {
|
||||||
|
Self { reader: DataReader::new(path, buffer_size_mb, reader_threads), threads: loader_threads }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DataLoader for MontyDataLoader {
|
||||||
|
type Error = DataLoadingError;
|
||||||
|
|
||||||
|
fn map_batches<F: FnMut(PreparedBatchHost) -> bool>(self, batch_size: usize, mut f: F) -> Result<(), Self::Error> {
|
||||||
|
self.reader.map_batches(batch_size, |batch| f(prepare(batch, self.threads)));
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn prepare(data: &[DecompressedData], threads: usize) -> PreparedBatchHost {
|
||||||
|
let batch_size = data.len();
|
||||||
|
let chunk_size = batch_size.div_ceil(threads);
|
||||||
|
|
||||||
|
let mut inputs = vec![0; MAX_ACTIVE_BASE * batch_size];
|
||||||
|
let mut moves = vec![0; MAX_MOVES * batch_size];
|
||||||
|
let mut dist = vec![0.0; MAX_MOVES * batch_size];
|
||||||
|
|
||||||
|
std::thread::scope(|s| {
|
||||||
|
for (((data_chunk, input_chunk), moves_chunk), dist_chunk) in data
|
||||||
|
.chunks(chunk_size)
|
||||||
|
.zip(inputs.chunks_mut(MAX_ACTIVE_BASE * chunk_size))
|
||||||
|
.zip(moves.chunks_mut(MAX_MOVES * chunk_size))
|
||||||
|
.zip(dist.chunks_mut(MAX_MOVES * chunk_size))
|
||||||
|
{
|
||||||
|
s.spawn(move || {
|
||||||
|
for (i, point) in data_chunk.iter().enumerate() {
|
||||||
|
let input_offset = MAX_ACTIVE_BASE * i;
|
||||||
|
let moves_offset = MAX_MOVES * i;
|
||||||
|
|
||||||
|
let mut j = 0;
|
||||||
|
inputs::map_base_inputs(&point.pos, |feat| {
|
||||||
|
assert!(feat < INPUT_SIZE);
|
||||||
|
input_chunk[input_offset + j] = feat as i32;
|
||||||
|
j += 1;
|
||||||
|
});
|
||||||
|
|
||||||
|
for k in j..MAX_ACTIVE_BASE {
|
||||||
|
input_chunk[input_offset + k] = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
assert!(j <= MAX_ACTIVE_BASE, "More inputs provided than the specified maximum!");
|
||||||
|
|
||||||
|
let mut total = 0;
|
||||||
|
let mut distinct = 0;
|
||||||
|
|
||||||
|
let pos = &point.pos;
|
||||||
|
|
||||||
|
for &(mov, visits) in &point.moves[..point.num] {
|
||||||
|
total += visits;
|
||||||
|
|
||||||
|
let mov = Move::from(mov);
|
||||||
|
moves_chunk[moves_offset + distinct] = inputs::map_move_to_index(pos, mov) as i32;
|
||||||
|
dist_chunk[moves_offset + distinct] = f32::from(visits);
|
||||||
|
distinct += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
for k in distinct..MAX_MOVES {
|
||||||
|
moves_chunk[moves_offset + k] = -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
let total = f32::from(total);
|
||||||
|
|
||||||
|
for idx in 0..distinct {
|
||||||
|
dist_chunk[moves_offset + idx] /= total;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut prep = PreparedBatchHost { batch_size, inputs: Default::default() };
|
||||||
|
|
||||||
|
unsafe {
|
||||||
|
prep.inputs.insert(
|
||||||
|
"inputs".to_string(),
|
||||||
|
HostMatrix::Sparse(HostSparseMatrix::new(
|
||||||
|
inputs,
|
||||||
|
Some(batch_size),
|
||||||
|
Shape::new(INPUT_SIZE, 1),
|
||||||
|
MAX_ACTIVE_BASE,
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
|
||||||
|
prep.inputs.insert(
|
||||||
|
"moves".to_string(),
|
||||||
|
HostMatrix::Sparse(HostSparseMatrix::new(
|
||||||
|
moves,
|
||||||
|
Some(batch_size),
|
||||||
|
Shape::new(NUM_MOVES_INDICES, 1),
|
||||||
|
MAX_MOVES,
|
||||||
|
)),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
prep.inputs.insert(
|
||||||
|
"targets".to_string(),
|
||||||
|
HostMatrix::Dense(HostDenseMatrix::new(dist, Some(batch_size), Shape::new(MAX_MOVES, 1))),
|
||||||
|
);
|
||||||
|
|
||||||
|
prep
|
||||||
|
}
|
||||||
@@ -0,0 +1,266 @@
|
|||||||
|
use std::{
|
||||||
|
fs::File,
|
||||||
|
io::{BufReader, Cursor, Read},
|
||||||
|
sync::mpsc,
|
||||||
|
time::{SystemTime, UNIX_EPOCH},
|
||||||
|
};
|
||||||
|
|
||||||
|
use montyformat::{
|
||||||
|
chess::{Castling, Move, Position},
|
||||||
|
FastDeserialise, MontyFormat,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::inputs::MAX_MOVES;
|
||||||
|
|
||||||
|
#[derive(Clone, Copy)]
|
||||||
|
pub struct DecompressedData {
|
||||||
|
pub pos: Position,
|
||||||
|
pub castling: Castling,
|
||||||
|
pub moves: [(u16, u16); MAX_MOVES],
|
||||||
|
pub num: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct DataReader {
|
||||||
|
file_path: String,
|
||||||
|
buffer_size: usize,
|
||||||
|
threads: usize,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DataReader {
|
||||||
|
pub fn new(path: &str, buffer_size_mb: usize, threads: usize) -> Self {
|
||||||
|
Self {
|
||||||
|
file_path: path.to_string(),
|
||||||
|
buffer_size: buffer_size_mb * 1024 * 1024 / std::mem::size_of::<DecompressedData>() / 2,
|
||||||
|
threads,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl DataReader {
|
||||||
|
pub fn map_batches<F: FnMut(&[DecompressedData]) -> bool>(&self, batch_size: usize, mut f: F) {
|
||||||
|
let file_path = self.file_path.clone();
|
||||||
|
let buffer_size = self.buffer_size;
|
||||||
|
let threads = self.threads;
|
||||||
|
let games_per_thread = 2048;
|
||||||
|
|
||||||
|
let (game_sender, game_receiver) = mpsc::sync_channel::<Vec<u8>>(32);
|
||||||
|
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let mut buffer = Vec::new();
|
||||||
|
|
||||||
|
'dataloading: loop {
|
||||||
|
let mut reader = BufReader::new(File::open(file_path.as_str()).unwrap());
|
||||||
|
|
||||||
|
while let Ok(()) = MontyFormat::deserialise_fast_into_buffer(&mut reader, &mut buffer) {
|
||||||
|
if game_sender.send(buffer.clone()).is_err() {
|
||||||
|
break 'dataloading;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let (mini_sender, mini_receiver) = mpsc::sync_channel::<Vec<DecompressedData>>(threads);
|
||||||
|
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let mut buffer = Vec::new();
|
||||||
|
|
||||||
|
while let Ok(game_bytes) = game_receiver.recv() {
|
||||||
|
buffer.push(game_bytes);
|
||||||
|
if buffer.len() == games_per_thread * threads {
|
||||||
|
if std::thread::scope(|s| {
|
||||||
|
let mut handles = Vec::with_capacity(threads);
|
||||||
|
|
||||||
|
for chunk in buffer.chunks(games_per_thread) {
|
||||||
|
let this_sender = mini_sender.clone();
|
||||||
|
let handle = s.spawn(move || {
|
||||||
|
let mut buf = Vec::with_capacity(160 * games_per_thread);
|
||||||
|
|
||||||
|
for game_bytes in chunk {
|
||||||
|
parse_into_buffer(game_bytes, &mut buf);
|
||||||
|
}
|
||||||
|
|
||||||
|
this_sender.send(buf).is_err()
|
||||||
|
});
|
||||||
|
|
||||||
|
handles.push(handle);
|
||||||
|
}
|
||||||
|
|
||||||
|
handles.into_iter().any(|x| x.join().unwrap())
|
||||||
|
}) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer.clear();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let (buffer_sender, buffer_receiver) = mpsc::sync_channel::<Vec<DecompressedData>>(0);
|
||||||
|
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
let mut shuffle_buffer = Vec::new();
|
||||||
|
shuffle_buffer.reserve_exact(buffer_size);
|
||||||
|
|
||||||
|
while let Ok(buffer) = mini_receiver.recv() {
|
||||||
|
if shuffle_buffer.len() + buffer.len() < shuffle_buffer.capacity() {
|
||||||
|
shuffle_buffer.extend_from_slice(&buffer);
|
||||||
|
} else {
|
||||||
|
let diff = shuffle_buffer.capacity() - shuffle_buffer.len();
|
||||||
|
shuffle_buffer.extend_from_slice(&buffer[..diff]);
|
||||||
|
|
||||||
|
if buffer_sender.send(shuffle_buffer).is_err() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
shuffle_buffer = Vec::new();
|
||||||
|
shuffle_buffer.reserve_exact(buffer_size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let (shuffled_sender, shuffled_receiver) = mpsc::sync_channel::<Vec<DecompressedData>>(0);
|
||||||
|
|
||||||
|
std::thread::spawn(move || {
|
||||||
|
while let Ok(mut inputs) = buffer_receiver.recv() {
|
||||||
|
shuffle(&mut inputs);
|
||||||
|
|
||||||
|
if shuffled_sender.send(inputs).is_err() {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
'dataloading: while let Ok(inputs) = shuffled_receiver.recv() {
|
||||||
|
for batch in inputs.chunks(batch_size) {
|
||||||
|
if f(batch) {
|
||||||
|
break 'dataloading;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
drop(shuffled_receiver);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn shuffle(data: &mut [DecompressedData]) {
|
||||||
|
let mut rng = Rand::with_seed();
|
||||||
|
|
||||||
|
for i in (0..data.len()).rev() {
|
||||||
|
let idx = rng.rng() as usize % (i + 1);
|
||||||
|
data.swap(idx, i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! read_into_primitive {
|
||||||
|
($reader:expr, $t:ty) => {{
|
||||||
|
let mut buf = [0u8; std::mem::size_of::<$t>()];
|
||||||
|
$reader.read_exact(&mut buf).unwrap();
|
||||||
|
<$t>::from_le_bytes(buf)
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_into_buffer(game: &[u8], buffer: &mut Vec<DecompressedData>) {
|
||||||
|
let mut reader = Cursor::new(game);
|
||||||
|
|
||||||
|
let mut qbbs = [0u64; 4];
|
||||||
|
for bb in &mut qbbs {
|
||||||
|
*bb = read_into_primitive!(reader, u64);
|
||||||
|
}
|
||||||
|
|
||||||
|
let stm = read_into_primitive!(reader, u8);
|
||||||
|
let enp_sq = read_into_primitive!(reader, u8);
|
||||||
|
let rights = read_into_primitive!(reader, u8);
|
||||||
|
let halfm = read_into_primitive!(reader, u8);
|
||||||
|
let fullm = read_into_primitive!(reader, u16);
|
||||||
|
|
||||||
|
let mut bbs = [0; 8];
|
||||||
|
|
||||||
|
let blc = qbbs[0];
|
||||||
|
let rqk = qbbs[1];
|
||||||
|
let nbk = qbbs[2];
|
||||||
|
let pbq = qbbs[3];
|
||||||
|
|
||||||
|
let occ = rqk | nbk | pbq;
|
||||||
|
let pnb = occ ^ qbbs[1];
|
||||||
|
let prq = occ ^ qbbs[2];
|
||||||
|
let nrk = occ ^ qbbs[3];
|
||||||
|
|
||||||
|
bbs[0] = occ ^ blc;
|
||||||
|
bbs[1] = blc;
|
||||||
|
bbs[2] = pnb & prq;
|
||||||
|
bbs[3] = pnb & nrk;
|
||||||
|
bbs[4] = pnb & nbk & pbq;
|
||||||
|
bbs[5] = prq & nrk;
|
||||||
|
bbs[6] = pbq & prq & rqk;
|
||||||
|
bbs[7] = nbk & rqk;
|
||||||
|
|
||||||
|
let mut pos = Position::from_raw(bbs, stm > 0, enp_sq, rights, halfm, fullm);
|
||||||
|
|
||||||
|
let mut rook_files = [[0; 2]; 2];
|
||||||
|
for side in &mut rook_files {
|
||||||
|
for rook in side {
|
||||||
|
*rook = read_into_primitive!(reader, u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let castling = Castling::from_raw(&pos, rook_files);
|
||||||
|
|
||||||
|
let _result = read_into_primitive!(reader, u8) as f32 / 2.0;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
let best_move = Move::from(read_into_primitive!(reader, u16));
|
||||||
|
|
||||||
|
if best_move == Move::NULL {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
let _score = f32::from(read_into_primitive!(reader, u16)) / f32::from(u16::MAX);
|
||||||
|
|
||||||
|
let num_moves = usize::from(read_into_primitive!(reader, u8));
|
||||||
|
|
||||||
|
if num_moves > 1 && num_moves <= MAX_MOVES {
|
||||||
|
let mut policy_data = DecompressedData { pos, castling, moves: [(0, 0); MAX_MOVES], num: num_moves };
|
||||||
|
|
||||||
|
let mut count = 0;
|
||||||
|
pos.map_legal_moves(&castling, |mov| {
|
||||||
|
policy_data.moves[count].0 = mov.into();
|
||||||
|
count += 1;
|
||||||
|
});
|
||||||
|
|
||||||
|
assert_eq!(count, num_moves);
|
||||||
|
|
||||||
|
policy_data.moves[..num_moves].sort_by_key(|x| x.0);
|
||||||
|
|
||||||
|
for entry in &mut policy_data.moves[..num_moves] {
|
||||||
|
entry.1 = u16::from(read_into_primitive!(reader, u8));
|
||||||
|
}
|
||||||
|
|
||||||
|
buffer.push(policy_data);
|
||||||
|
} else {
|
||||||
|
for _ in 0..num_moves {
|
||||||
|
let _ = read_into_primitive!(reader, u8);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pos.make(best_move, &castling);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub struct Rand(u64);
|
||||||
|
|
||||||
|
impl Rand {
|
||||||
|
pub fn with_seed() -> Self {
|
||||||
|
let seed = SystemTime::now().duration_since(UNIX_EPOCH).expect("Guaranteed increasing.").as_micros() as u64
|
||||||
|
& 0xFFFF_FFFF;
|
||||||
|
|
||||||
|
Self(seed)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn rng(&mut self) -> u64 {
|
||||||
|
self.0 ^= self.0 << 13;
|
||||||
|
self.0 ^= self.0 >> 7;
|
||||||
|
self.0 ^= self.0 << 17;
|
||||||
|
self.0
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,198 @@
|
|||||||
|
//! Policy network inputs and outputs. Rigby's C++ inference (src/policy.cpp)
|
||||||
|
//! must map positions and moves exactly the same way.
|
||||||
|
//!
|
||||||
|
//! Inputs (3072): 768 piece-square features relative to the side to move
|
||||||
|
//! (own pieces 0..384, theirs 384..768, `64 * piece + square`), offset by 768
|
||||||
|
//! when the square is attacked by the opponent and by 1536 when it is defended
|
||||||
|
//! by the side to move. Squares are flipped vertically for black and
|
||||||
|
//! horizontally when the side to move's king is on files e-h.
|
||||||
|
//!
|
||||||
|
//! Outputs (NUM_MOVES_INDICES): one row per (piece, from, to) a piece could
|
||||||
|
//! ever move along, plus promotions, castling and double pawn pushes, in the
|
||||||
|
//! same oriented frame. Unlike Monty there is no SEE split.
|
||||||
|
|
||||||
|
use montyformat::chess::{Flag, Move, Piece, Position, Side};
|
||||||
|
|
||||||
|
pub const MAX_MOVES: usize = 64;
|
||||||
|
pub const INPUT_SIZE: usize = 768 * 4;
|
||||||
|
pub const MAX_ACTIVE_BASE: usize = 32;
|
||||||
|
pub const NUM_MOVES_INDICES: usize = FROM_TO;
|
||||||
|
|
||||||
|
const FROM_TO: usize = OFFSETS[5][64] + PROMOS + 2 + 8;
|
||||||
|
|
||||||
|
pub fn map_move_to_index(pos: &Position, mov: Move) -> usize {
|
||||||
|
let hm = if pos.king_index() % 8 > 3 { 7 } else { 0 };
|
||||||
|
let flip = hm ^ if pos.stm() == Side::BLACK { 56 } else { 0 };
|
||||||
|
|
||||||
|
let src = usize::from(mov.src() ^ flip);
|
||||||
|
let dst = usize::from(mov.to() ^ flip);
|
||||||
|
|
||||||
|
if mov.is_promo() {
|
||||||
|
let ffile = src % 8;
|
||||||
|
let tfile = dst % 8;
|
||||||
|
let promo_id = 2 * ffile + tfile;
|
||||||
|
|
||||||
|
OFFSETS[5][64] + (PROMOS / 4) * (mov.promo_pc() - Piece::KNIGHT) + promo_id
|
||||||
|
} else if mov.flag() == Flag::QS || mov.flag() == Flag::KS {
|
||||||
|
let is_ks = usize::from(mov.flag() == Flag::KS);
|
||||||
|
let is_hm = usize::from(hm == 0);
|
||||||
|
OFFSETS[5][64] + PROMOS + (is_ks ^ is_hm)
|
||||||
|
} else if mov.flag() == Flag::DBL {
|
||||||
|
OFFSETS[5][64] + PROMOS + 2 + (src % 8)
|
||||||
|
} else {
|
||||||
|
let pc = pos.get_pc(1 << mov.src()) - 2;
|
||||||
|
let below = DESTINATIONS[src][pc] & ((1 << dst) - 1);
|
||||||
|
|
||||||
|
OFFSETS[pc][src] + below.count_ones() as usize
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn map_base_inputs<F: FnMut(usize)>(pos: &Position, mut f: F) {
|
||||||
|
let vert = if pos.stm() == Side::BLACK { 56 } else { 0 };
|
||||||
|
let hori = if pos.king_index() % 8 > 3 { 7 } else { 0 };
|
||||||
|
let flip = vert ^ hori;
|
||||||
|
|
||||||
|
let threats = pos.threats_by(pos.stm() ^ 1);
|
||||||
|
let defences = pos.threats_by(pos.stm());
|
||||||
|
|
||||||
|
for piece in Piece::PAWN..=Piece::KING {
|
||||||
|
let pc = 64 * (piece - 2);
|
||||||
|
|
||||||
|
let mut our_bb = pos.piece(piece) & pos.piece(pos.stm());
|
||||||
|
let mut opp_bb = pos.piece(piece) & pos.piece(pos.stm() ^ 1);
|
||||||
|
|
||||||
|
while our_bb > 0 {
|
||||||
|
let sq = our_bb.trailing_zeros() as usize;
|
||||||
|
let mut feat = pc + (sq ^ flip);
|
||||||
|
|
||||||
|
let bit = 1 << sq;
|
||||||
|
if threats & bit > 0 {
|
||||||
|
feat += 768;
|
||||||
|
}
|
||||||
|
|
||||||
|
if defences & bit > 0 {
|
||||||
|
feat += 768 * 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
f(feat);
|
||||||
|
|
||||||
|
our_bb &= our_bb - 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
while opp_bb > 0 {
|
||||||
|
let sq = opp_bb.trailing_zeros() as usize;
|
||||||
|
let mut feat = 384 + pc + (sq ^ flip);
|
||||||
|
|
||||||
|
let bit = 1 << sq;
|
||||||
|
if threats & bit > 0 {
|
||||||
|
feat += 768;
|
||||||
|
}
|
||||||
|
|
||||||
|
if defences & bit > 0 {
|
||||||
|
feat += 768 * 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
f(feat);
|
||||||
|
|
||||||
|
opp_bb &= opp_bb - 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
pub const PROMOS: usize = 4 * 22;
|
||||||
|
|
||||||
|
macro_rules! init {
|
||||||
|
(|$sq:ident, $size:literal | $($rest:tt)+) => {{
|
||||||
|
let mut $sq = 0;
|
||||||
|
let mut res = [{$($rest)+}; $size];
|
||||||
|
while $sq < $size {
|
||||||
|
res[$sq] = {$($rest)+};
|
||||||
|
$sq += 1;
|
||||||
|
}
|
||||||
|
res
|
||||||
|
}};
|
||||||
|
}
|
||||||
|
|
||||||
|
const OFFSETS: [[usize; 65]; 6] = {
|
||||||
|
let mut offsets = [[0; 65]; 6];
|
||||||
|
|
||||||
|
let mut curr = 0;
|
||||||
|
|
||||||
|
let mut pc = 0;
|
||||||
|
while pc < 6 {
|
||||||
|
let mut sq = 0;
|
||||||
|
|
||||||
|
while sq < 64 {
|
||||||
|
offsets[pc][sq] = curr;
|
||||||
|
curr += DESTINATIONS[sq][pc].count_ones() as usize;
|
||||||
|
sq += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
offsets[pc][64] = curr;
|
||||||
|
|
||||||
|
pc += 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
offsets
|
||||||
|
};
|
||||||
|
|
||||||
|
const DESTINATIONS: [[u64; 6]; 64] = init!(|sq, 64| [PAWN[sq], KNIGHT[sq], bishop(sq), rook(sq), queen(sq), KING[sq]]);
|
||||||
|
|
||||||
|
const A: u64 = 0x0101_0101_0101_0101;
|
||||||
|
const H: u64 = A << 7;
|
||||||
|
|
||||||
|
const DIAGS: [u64; 15] = [
|
||||||
|
0x0100_0000_0000_0000,
|
||||||
|
0x0201_0000_0000_0000,
|
||||||
|
0x0402_0100_0000_0000,
|
||||||
|
0x0804_0201_0000_0000,
|
||||||
|
0x1008_0402_0100_0000,
|
||||||
|
0x2010_0804_0201_0000,
|
||||||
|
0x4020_1008_0402_0100,
|
||||||
|
0x8040_2010_0804_0201,
|
||||||
|
0x0080_4020_1008_0402,
|
||||||
|
0x0000_8040_2010_0804,
|
||||||
|
0x0000_0080_4020_1008,
|
||||||
|
0x0000_0000_8040_2010,
|
||||||
|
0x0000_0000_0080_4020,
|
||||||
|
0x0000_0000_0000_8040,
|
||||||
|
0x0000_0000_0000_0080,
|
||||||
|
];
|
||||||
|
|
||||||
|
const PAWN: [u64; 64] = init!(|sq, 64| {
|
||||||
|
let bit = 1 << sq;
|
||||||
|
((bit & !A) << 7) | (bit << 8) | ((bit & !H) << 9)
|
||||||
|
});
|
||||||
|
|
||||||
|
const KNIGHT: [u64; 64] = init!(|sq, 64| {
|
||||||
|
let n = 1 << sq;
|
||||||
|
let h1 = ((n >> 1) & 0x7f7f_7f7f_7f7f_7f7f) | ((n << 1) & 0xfefe_fefe_fefe_fefe);
|
||||||
|
let h2 = ((n >> 2) & 0x3f3f_3f3f_3f3f_3f3f) | ((n << 2) & 0xfcfc_fcfc_fcfc_fcfc);
|
||||||
|
(h1 << 16) | (h1 >> 16) | (h2 << 8) | (h2 >> 8)
|
||||||
|
});
|
||||||
|
|
||||||
|
const fn bishop(sq: usize) -> u64 {
|
||||||
|
let rank = sq / 8;
|
||||||
|
let file = sq % 8;
|
||||||
|
|
||||||
|
DIAGS[file + rank].swap_bytes() ^ DIAGS[7 + file - rank]
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn rook(sq: usize) -> u64 {
|
||||||
|
let rank = sq / 8;
|
||||||
|
let file = sq % 8;
|
||||||
|
|
||||||
|
(0xFF << (rank * 8)) ^ (A << file)
|
||||||
|
}
|
||||||
|
|
||||||
|
const fn queen(sq: usize) -> u64 {
|
||||||
|
bishop(sq) | rook(sq)
|
||||||
|
}
|
||||||
|
|
||||||
|
const KING: [u64; 64] = init!(|sq, 64| {
|
||||||
|
let mut k = 1 << sq;
|
||||||
|
k |= (k << 8) | (k >> 8);
|
||||||
|
k |= ((k & !A) >> 1) | ((k & !H) << 1);
|
||||||
|
k ^ (1 << sq)
|
||||||
|
});
|
||||||
@@ -0,0 +1,323 @@
|
|||||||
|
//! Lc0 V6 training data (one gzipped file of 8356-byte records per game,
|
||||||
|
//! packed in hourly tar files) converted to montyformat games.
|
||||||
|
//!
|
||||||
|
//! Each record holds the position as input planes, the search's visit
|
||||||
|
//! fractions over Lc0's 1858 policy outputs (-1 for illegal moves) and the
|
||||||
|
//! move that was played. A game is rebuilt from its first record and the
|
||||||
|
//! played moves, and every record is checked against the rebuilt position:
|
||||||
|
//! the pieces must match and the moves Lc0 gave a probability must be exactly
|
||||||
|
//! the legal moves. A game is cut at the first record that fails; with the
|
||||||
|
//! LC0_DEBUG environment variable set, the reason is printed to stderr.
|
||||||
|
|
||||||
|
use montyformat::{
|
||||||
|
chess::{Castling, Flag, Move, Piece, Position, Right, Side},
|
||||||
|
MontyFormat, SearchData,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::lc0_policy::POLICY_INDEX;
|
||||||
|
|
||||||
|
pub const RECORD_SIZE: usize = 8356;
|
||||||
|
|
||||||
|
const OFF_PROBS: usize = 8;
|
||||||
|
const OFF_PLANES: usize = 7440;
|
||||||
|
const OFF_CASTLING: usize = 8272;
|
||||||
|
const OFF_STM: usize = 8276;
|
||||||
|
const OFF_RULE50: usize = 8277;
|
||||||
|
const OFF_BEST_Q: usize = 8284;
|
||||||
|
const OFF_RESULT_Q: usize = 8308;
|
||||||
|
const OFF_PLAYED_IDX: usize = 8344;
|
||||||
|
|
||||||
|
/// Why records were dropped, and how much was kept.
|
||||||
|
#[derive(Default, Clone, Copy, Debug)]
|
||||||
|
pub struct Stats {
|
||||||
|
pub games: u64,
|
||||||
|
pub positions: u64,
|
||||||
|
pub bad_format: u64,
|
||||||
|
pub bad_start: u64,
|
||||||
|
pub cut_board: u64,
|
||||||
|
pub cut_moves: u64,
|
||||||
|
pub cut_played: u64,
|
||||||
|
pub dropped_records: u64,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Stats {
|
||||||
|
pub fn add(&mut self, o: &Stats) {
|
||||||
|
self.games += o.games;
|
||||||
|
self.positions += o.positions;
|
||||||
|
self.bad_format += o.bad_format;
|
||||||
|
self.bad_start += o.bad_start;
|
||||||
|
self.cut_board += o.cut_board;
|
||||||
|
self.cut_moves += o.cut_moves;
|
||||||
|
self.cut_played += o.cut_played;
|
||||||
|
self.dropped_records += o.dropped_records;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// (from, to, promotion piece or 0) -> Lc0 policy index, in the side to
|
||||||
|
/// move's frame. Knight promotions are the plain move.
|
||||||
|
pub struct PolicyMap {
|
||||||
|
index: Vec<i16>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn key(from: usize, to: usize, promo: usize) -> usize {
|
||||||
|
(from * 64 + to) * 8 + promo
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for PolicyMap {
|
||||||
|
fn default() -> Self {
|
||||||
|
let mut index = vec![-1i16; 64 * 64 * 8];
|
||||||
|
for (i, uci) in POLICY_INDEX.iter().enumerate() {
|
||||||
|
let b = uci.as_bytes();
|
||||||
|
let sq = |f: u8, r: u8| usize::from(r - b'1') * 8 + usize::from(f - b'a');
|
||||||
|
let from = sq(b[0], b[1]);
|
||||||
|
let to = sq(b[2], b[3]);
|
||||||
|
let promo = match b.get(4) {
|
||||||
|
None => 0,
|
||||||
|
Some(b'q') => Piece::QUEEN,
|
||||||
|
Some(b'r') => Piece::ROOK,
|
||||||
|
Some(b'b') => Piece::BISHOP,
|
||||||
|
Some(_) => unreachable!(),
|
||||||
|
};
|
||||||
|
index[key(from, to, promo)] = i as i16;
|
||||||
|
}
|
||||||
|
Self { index }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PolicyMap {
|
||||||
|
/// Lc0 index of a montyformat move. Lc0 encodes castling as the king
|
||||||
|
/// taking its own rook (e1h1 / e1a1, or wherever the rook is in Chess960).
|
||||||
|
pub fn index(&self, pos: &Position, castling: &Castling, mov: Move) -> Option<usize> {
|
||||||
|
let flip = if pos.stm() == Side::BLACK { 56 } else { 0 };
|
||||||
|
let from = usize::from(mov.src()) ^ flip;
|
||||||
|
let to = match mov.flag() {
|
||||||
|
Flag::KS => usize::from(castling.rook_file(pos.stm(), 1)),
|
||||||
|
Flag::QS => usize::from(castling.rook_file(pos.stm(), 0)),
|
||||||
|
_ => usize::from(mov.to()) ^ flip,
|
||||||
|
};
|
||||||
|
let promo = if mov.is_promo() && mov.promo_pc() != Piece::KNIGHT { mov.promo_pc() } else { 0 };
|
||||||
|
let idx = self.index[key(from, to, promo)];
|
||||||
|
(idx >= 0).then_some(idx as usize)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn f32_at(r: &[u8], off: usize) -> f32 {
|
||||||
|
f32::from_le_bytes(r[off..off + 4].try_into().unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn u16_at(r: &[u8], off: usize) -> u16 {
|
||||||
|
u16::from_le_bytes(r[off..off + 2].try_into().unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn u32_at(r: &[u8], off: usize) -> u32 {
|
||||||
|
u32::from_le_bytes(r[off..off + 4].try_into().unwrap())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bit i of the result is square i (a1 = 0) on the real board.
|
||||||
|
fn plane(r: &[u8], idx: usize, black: bool) -> u64 {
|
||||||
|
let off = OFF_PLANES + 8 * idx;
|
||||||
|
let stored = u64::from_le_bytes(r[off..off + 8].try_into().unwrap());
|
||||||
|
// Lc0 stores each plane with the bits of every byte reversed (a file
|
||||||
|
// mirror), and from the side to move's point of view.
|
||||||
|
let mut bytes = stored.to_le_bytes();
|
||||||
|
for b in &mut bytes {
|
||||||
|
*b = b.reverse_bits();
|
||||||
|
}
|
||||||
|
let oriented = u64::from_le_bytes(bytes);
|
||||||
|
if black {
|
||||||
|
oriented.swap_bytes()
|
||||||
|
} else {
|
||||||
|
oriented
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The current position's pieces: [white, black, pawn, knight, bishop, rook, queen, king].
|
||||||
|
fn board(r: &[u8]) -> ([u64; 8], bool) {
|
||||||
|
let black = r[OFF_STM] != 0;
|
||||||
|
let (us, them) = if black { (Side::BLACK, Side::WHITE) } else { (Side::WHITE, Side::BLACK) };
|
||||||
|
let mut bbs = [0u64; 8];
|
||||||
|
for pc in 0..6 {
|
||||||
|
let ours = plane(r, pc, black);
|
||||||
|
let theirs = plane(r, 6 + pc, black);
|
||||||
|
bbs[us] |= ours;
|
||||||
|
bbs[them] |= theirs;
|
||||||
|
bbs[Piece::PAWN + pc] = ours | theirs;
|
||||||
|
}
|
||||||
|
(bbs, black)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn rights(r: &[u8], black: bool) -> u8 {
|
||||||
|
let c = &r[OFF_CASTLING..OFF_CASTLING + 4]; // us_ooo, us_oo, them_ooo, them_oo
|
||||||
|
let (us_q, us_k, them_q, them_k) = if black {
|
||||||
|
(Right::BQS, Right::BKS, Right::WQS, Right::WKS)
|
||||||
|
} else {
|
||||||
|
(Right::WQS, Right::WKS, Right::BQS, Right::BKS)
|
||||||
|
};
|
||||||
|
let mut rights = 0;
|
||||||
|
for (flag, right) in c.iter().zip([us_q, us_k, them_q, them_k]) {
|
||||||
|
if *flag != 0 {
|
||||||
|
rights |= right;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
rights
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Castling rook files ([side][queenside, kingside]) for the given rights.
|
||||||
|
/// Lc0's classical input format only stores which rights exist, so each one
|
||||||
|
/// takes the outermost rook on its side of the king, as X-FEN does; the move
|
||||||
|
/// check catches a wrong guess. None when a right has no king or rook for it.
|
||||||
|
fn rook_files(bbs: &[u64; 8], rights: u8) -> Option<[[u8; 2]; 2]> {
|
||||||
|
let mut files = [[0, 7]; 2];
|
||||||
|
for (side, rank, qs, ks) in [(Side::WHITE, 0, Right::WQS, Right::WKS), (Side::BLACK, 7, Right::BQS, Right::BKS)] {
|
||||||
|
if rights & (qs | ks) == 0 {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
let back = |piece: usize| ((bbs[side] & bbs[piece]) >> (8 * rank)) as u8;
|
||||||
|
let king = back(Piece::KING);
|
||||||
|
if king == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let kfile = king.trailing_zeros() as u8;
|
||||||
|
let rooks = back(Piece::ROOK);
|
||||||
|
let below = rooks & ((1u8 << kfile) - 1);
|
||||||
|
let above = rooks & !((2u16 << kfile) - 1) as u8;
|
||||||
|
if rights & qs != 0 {
|
||||||
|
if below == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
files[side][0] = below.trailing_zeros() as u8;
|
||||||
|
}
|
||||||
|
if rights & ks != 0 {
|
||||||
|
if above == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
files[side][1] = 7 - above.leading_zeros() as u8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(files)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Legal moves paired with their Lc0 probability, or None when the set of
|
||||||
|
/// legal moves differs from the moves Lc0 gave a probability.
|
||||||
|
fn match_moves(pos: &Position, castling: &Castling, r: &[u8], map: &PolicyMap) -> Option<Vec<(Move, f32)>> {
|
||||||
|
let mut legal = Vec::with_capacity(64);
|
||||||
|
let mut ok = true;
|
||||||
|
pos.map_legal_moves(castling, |mov| match map.index(pos, castling, mov) {
|
||||||
|
Some(idx) => legal.push((mov, f32_at(r, OFF_PROBS + 4 * idx))),
|
||||||
|
None => ok = false,
|
||||||
|
});
|
||||||
|
if !ok || legal.iter().any(|&(_, p)| p < 0.0) {
|
||||||
|
if std::env::var("LC0_DEBUG").is_ok() {
|
||||||
|
let bad: Vec<String> =
|
||||||
|
legal.iter().filter(|&&(_, p)| p < 0.0).map(|&(m, _)| m.to_uci(castling)).collect();
|
||||||
|
eprintln!("{} ok={ok} negative: {:?}", pos.as_fen(), bad);
|
||||||
|
}
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let with_prob = (0..1858).filter(|&i| f32_at(r, OFF_PROBS + 4 * i) >= 0.0).count();
|
||||||
|
if with_prob != legal.len() && std::env::var("LC0_DEBUG").is_ok() {
|
||||||
|
let ours: Vec<usize> = legal.iter().filter_map(|&(m, _)| map.index(pos, castling, m)).collect();
|
||||||
|
let extra: Vec<&str> = (0..1858)
|
||||||
|
.filter(|&i| f32_at(r, OFF_PROBS + 4 * i) >= 0.0 && !ours.contains(&i))
|
||||||
|
.map(|i| POLICY_INDEX[i])
|
||||||
|
.collect();
|
||||||
|
eprintln!("{} lc0-only: {:?}", pos.as_fen(), extra);
|
||||||
|
}
|
||||||
|
(with_prob == legal.len()).then_some(legal)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// The game's first position. En passant is not stored, so each possible en
|
||||||
|
/// passant square is tried and the one whose legal moves match Lc0's is kept.
|
||||||
|
fn start_position(r: &[u8], map: &PolicyMap) -> Option<(Position, Castling)> {
|
||||||
|
let (bbs, black) = board(r);
|
||||||
|
let rights = rights(r, black);
|
||||||
|
let files = rook_files(&bbs, rights)?;
|
||||||
|
let halfm = r[OFF_RULE50];
|
||||||
|
|
||||||
|
let mut candidates = vec![0u8];
|
||||||
|
// A pawn of the side not to move that may just have made a double push.
|
||||||
|
let (them, rank_from, rank_to) = if black { (Side::WHITE, 1, 3) } else { (Side::BLACK, 6, 4) };
|
||||||
|
let occ = bbs[0] | bbs[1];
|
||||||
|
let mut pawns = bbs[them] & bbs[Piece::PAWN] & (0xFFu64 << (8 * rank_to));
|
||||||
|
while pawns != 0 {
|
||||||
|
let sq = pawns.trailing_zeros() as u8;
|
||||||
|
pawns &= pawns - 1;
|
||||||
|
let file = sq % 8;
|
||||||
|
let mid = (rank_from + rank_to) / 2 * 8 + file;
|
||||||
|
let from = rank_from * 8 + file;
|
||||||
|
if occ & ((1u64 << mid) | (1u64 << from)) == 0 {
|
||||||
|
candidates.push(mid);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for enp in candidates {
|
||||||
|
#[allow(deprecated)]
|
||||||
|
let pos = Position::from_raw(bbs, black, enp, rights, halfm, 1);
|
||||||
|
let castling = Castling::from_raw(&pos, files);
|
||||||
|
if match_moves(&pos, &castling, r, map).is_some() {
|
||||||
|
return Some((pos, castling));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Converts one game (the decompressed contents of one .gz file).
|
||||||
|
pub fn convert_game(data: &[u8], map: &PolicyMap, stats: &mut Stats) -> Option<MontyFormat> {
|
||||||
|
if data.len() < RECORD_SIZE || data.len() % RECORD_SIZE != 0 {
|
||||||
|
stats.bad_format += 1;
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let records: Vec<&[u8]> = data.chunks_exact(RECORD_SIZE).collect();
|
||||||
|
if records.iter().any(|r| u32_at(r, 0) != 6 || u32_at(r, 4) != 1) {
|
||||||
|
stats.bad_format += 1;
|
||||||
|
stats.dropped_records += records.len() as u64;
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some((startpos, castling)) = start_position(records[0], map) else {
|
||||||
|
stats.bad_start += 1;
|
||||||
|
stats.dropped_records += records.len() as u64;
|
||||||
|
return None;
|
||||||
|
};
|
||||||
|
|
||||||
|
let mut game = MontyFormat::new(startpos, castling);
|
||||||
|
// Lc0's result is from the side to move's point of view; montyformat's
|
||||||
|
// from white's.
|
||||||
|
let result_q = f32_at(records[0], OFF_RESULT_Q).clamp(-1.0, 1.0);
|
||||||
|
let white_q = if startpos.stm() == Side::BLACK { -result_q } else { result_q };
|
||||||
|
game.result = (white_q + 1.0) / 2.0;
|
||||||
|
|
||||||
|
let mut pos = startpos;
|
||||||
|
for (i, r) in records.iter().enumerate() {
|
||||||
|
let (bbs, black) = board(r);
|
||||||
|
if bbs != pos.bbs() || black != (pos.stm() == Side::BLACK) {
|
||||||
|
stats.cut_board += 1;
|
||||||
|
stats.dropped_records += (records.len() - i) as u64;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
let Some(moves) = match_moves(&pos, &castling, r, map) else {
|
||||||
|
stats.cut_moves += 1;
|
||||||
|
stats.dropped_records += (records.len() - i) as u64;
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
let played_idx = usize::from(u16_at(r, OFF_PLAYED_IDX));
|
||||||
|
let Some(played) = moves.iter().map(|&(m, _)| m).find(|&m| map.index(&pos, &castling, m) == Some(played_idx)) else {
|
||||||
|
stats.cut_played += 1;
|
||||||
|
stats.dropped_records += (records.len() - i) as u64;
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
|
||||||
|
let dist: Vec<(Move, u32)> = moves.iter().map(|&(m, p)| (m, (p * 1_000_000.0).round() as u32)).collect();
|
||||||
|
let score = ((f32_at(r, OFF_BEST_Q).clamp(-1.0, 1.0) + 1.0) / 2.0).clamp(0.0, 1.0);
|
||||||
|
game.push(SearchData::new(played, score, Some(dist)));
|
||||||
|
stats.positions += 1;
|
||||||
|
|
||||||
|
pos.make(played, &castling);
|
||||||
|
}
|
||||||
|
|
||||||
|
if game.moves.is_empty() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
stats.games += 1;
|
||||||
|
Some(game)
|
||||||
|
}
|
||||||
@@ -0,0 +1,192 @@
|
|||||||
|
//! Lc0's 1858 policy outputs (lczero-training tf/policy_index.py), as UCI
|
||||||
|
//! moves from the side to move's point of view (black's moves flipped
|
||||||
|
//! vertically). A promotion without a suffix is a knight promotion.
|
||||||
|
|
||||||
|
pub const POLICY_INDEX: [&str; 1858] = [
|
||||||
|
"a1b1", "a1c1", "a1d1", "a1e1", "a1f1", "a1g1", "a1h1", "a1a2", "a1b2", "a1c2",
|
||||||
|
"a1a3", "a1b3", "a1c3", "a1a4", "a1d4", "a1a5", "a1e5", "a1a6", "a1f6", "a1a7",
|
||||||
|
"a1g7", "a1a8", "a1h8", "b1a1", "b1c1", "b1d1", "b1e1", "b1f1", "b1g1", "b1h1",
|
||||||
|
"b1a2", "b1b2", "b1c2", "b1d2", "b1a3", "b1b3", "b1c3", "b1d3", "b1b4", "b1e4",
|
||||||
|
"b1b5", "b1f5", "b1b6", "b1g6", "b1b7", "b1h7", "b1b8", "c1a1", "c1b1", "c1d1",
|
||||||
|
"c1e1", "c1f1", "c1g1", "c1h1", "c1a2", "c1b2", "c1c2", "c1d2", "c1e2", "c1a3",
|
||||||
|
"c1b3", "c1c3", "c1d3", "c1e3", "c1c4", "c1f4", "c1c5", "c1g5", "c1c6", "c1h6",
|
||||||
|
"c1c7", "c1c8", "d1a1", "d1b1", "d1c1", "d1e1", "d1f1", "d1g1", "d1h1", "d1b2",
|
||||||
|
"d1c2", "d1d2", "d1e2", "d1f2", "d1b3", "d1c3", "d1d3", "d1e3", "d1f3", "d1a4",
|
||||||
|
"d1d4", "d1g4", "d1d5", "d1h5", "d1d6", "d1d7", "d1d8", "e1a1", "e1b1", "e1c1",
|
||||||
|
"e1d1", "e1f1", "e1g1", "e1h1", "e1c2", "e1d2", "e1e2", "e1f2", "e1g2", "e1c3",
|
||||||
|
"e1d3", "e1e3", "e1f3", "e1g3", "e1b4", "e1e4", "e1h4", "e1a5", "e1e5", "e1e6",
|
||||||
|
"e1e7", "e1e8", "f1a1", "f1b1", "f1c1", "f1d1", "f1e1", "f1g1", "f1h1", "f1d2",
|
||||||
|
"f1e2", "f1f2", "f1g2", "f1h2", "f1d3", "f1e3", "f1f3", "f1g3", "f1h3", "f1c4",
|
||||||
|
"f1f4", "f1b5", "f1f5", "f1a6", "f1f6", "f1f7", "f1f8", "g1a1", "g1b1", "g1c1",
|
||||||
|
"g1d1", "g1e1", "g1f1", "g1h1", "g1e2", "g1f2", "g1g2", "g1h2", "g1e3", "g1f3",
|
||||||
|
"g1g3", "g1h3", "g1d4", "g1g4", "g1c5", "g1g5", "g1b6", "g1g6", "g1a7", "g1g7",
|
||||||
|
"g1g8", "h1a1", "h1b1", "h1c1", "h1d1", "h1e1", "h1f1", "h1g1", "h1f2", "h1g2",
|
||||||
|
"h1h2", "h1f3", "h1g3", "h1h3", "h1e4", "h1h4", "h1d5", "h1h5", "h1c6", "h1h6",
|
||||||
|
"h1b7", "h1h7", "h1a8", "h1h8", "a2a1", "a2b1", "a2c1", "a2b2", "a2c2", "a2d2",
|
||||||
|
"a2e2", "a2f2", "a2g2", "a2h2", "a2a3", "a2b3", "a2c3", "a2a4", "a2b4", "a2c4",
|
||||||
|
"a2a5", "a2d5", "a2a6", "a2e6", "a2a7", "a2f7", "a2a8", "a2g8", "b2a1", "b2b1",
|
||||||
|
"b2c1", "b2d1", "b2a2", "b2c2", "b2d2", "b2e2", "b2f2", "b2g2", "b2h2", "b2a3",
|
||||||
|
"b2b3", "b2c3", "b2d3", "b2a4", "b2b4", "b2c4", "b2d4", "b2b5", "b2e5", "b2b6",
|
||||||
|
"b2f6", "b2b7", "b2g7", "b2b8", "b2h8", "c2a1", "c2b1", "c2c1", "c2d1", "c2e1",
|
||||||
|
"c2a2", "c2b2", "c2d2", "c2e2", "c2f2", "c2g2", "c2h2", "c2a3", "c2b3", "c2c3",
|
||||||
|
"c2d3", "c2e3", "c2a4", "c2b4", "c2c4", "c2d4", "c2e4", "c2c5", "c2f5", "c2c6",
|
||||||
|
"c2g6", "c2c7", "c2h7", "c2c8", "d2b1", "d2c1", "d2d1", "d2e1", "d2f1", "d2a2",
|
||||||
|
"d2b2", "d2c2", "d2e2", "d2f2", "d2g2", "d2h2", "d2b3", "d2c3", "d2d3", "d2e3",
|
||||||
|
"d2f3", "d2b4", "d2c4", "d2d4", "d2e4", "d2f4", "d2a5", "d2d5", "d2g5", "d2d6",
|
||||||
|
"d2h6", "d2d7", "d2d8", "e2c1", "e2d1", "e2e1", "e2f1", "e2g1", "e2a2", "e2b2",
|
||||||
|
"e2c2", "e2d2", "e2f2", "e2g2", "e2h2", "e2c3", "e2d3", "e2e3", "e2f3", "e2g3",
|
||||||
|
"e2c4", "e2d4", "e2e4", "e2f4", "e2g4", "e2b5", "e2e5", "e2h5", "e2a6", "e2e6",
|
||||||
|
"e2e7", "e2e8", "f2d1", "f2e1", "f2f1", "f2g1", "f2h1", "f2a2", "f2b2", "f2c2",
|
||||||
|
"f2d2", "f2e2", "f2g2", "f2h2", "f2d3", "f2e3", "f2f3", "f2g3", "f2h3", "f2d4",
|
||||||
|
"f2e4", "f2f4", "f2g4", "f2h4", "f2c5", "f2f5", "f2b6", "f2f6", "f2a7", "f2f7",
|
||||||
|
"f2f8", "g2e1", "g2f1", "g2g1", "g2h1", "g2a2", "g2b2", "g2c2", "g2d2", "g2e2",
|
||||||
|
"g2f2", "g2h2", "g2e3", "g2f3", "g2g3", "g2h3", "g2e4", "g2f4", "g2g4", "g2h4",
|
||||||
|
"g2d5", "g2g5", "g2c6", "g2g6", "g2b7", "g2g7", "g2a8", "g2g8", "h2f1", "h2g1",
|
||||||
|
"h2h1", "h2a2", "h2b2", "h2c2", "h2d2", "h2e2", "h2f2", "h2g2", "h2f3", "h2g3",
|
||||||
|
"h2h3", "h2f4", "h2g4", "h2h4", "h2e5", "h2h5", "h2d6", "h2h6", "h2c7", "h2h7",
|
||||||
|
"h2b8", "h2h8", "a3a1", "a3b1", "a3c1", "a3a2", "a3b2", "a3c2", "a3b3", "a3c3",
|
||||||
|
"a3d3", "a3e3", "a3f3", "a3g3", "a3h3", "a3a4", "a3b4", "a3c4", "a3a5", "a3b5",
|
||||||
|
"a3c5", "a3a6", "a3d6", "a3a7", "a3e7", "a3a8", "a3f8", "b3a1", "b3b1", "b3c1",
|
||||||
|
"b3d1", "b3a2", "b3b2", "b3c2", "b3d2", "b3a3", "b3c3", "b3d3", "b3e3", "b3f3",
|
||||||
|
"b3g3", "b3h3", "b3a4", "b3b4", "b3c4", "b3d4", "b3a5", "b3b5", "b3c5", "b3d5",
|
||||||
|
"b3b6", "b3e6", "b3b7", "b3f7", "b3b8", "b3g8", "c3a1", "c3b1", "c3c1", "c3d1",
|
||||||
|
"c3e1", "c3a2", "c3b2", "c3c2", "c3d2", "c3e2", "c3a3", "c3b3", "c3d3", "c3e3",
|
||||||
|
"c3f3", "c3g3", "c3h3", "c3a4", "c3b4", "c3c4", "c3d4", "c3e4", "c3a5", "c3b5",
|
||||||
|
"c3c5", "c3d5", "c3e5", "c3c6", "c3f6", "c3c7", "c3g7", "c3c8", "c3h8", "d3b1",
|
||||||
|
"d3c1", "d3d1", "d3e1", "d3f1", "d3b2", "d3c2", "d3d2", "d3e2", "d3f2", "d3a3",
|
||||||
|
"d3b3", "d3c3", "d3e3", "d3f3", "d3g3", "d3h3", "d3b4", "d3c4", "d3d4", "d3e4",
|
||||||
|
"d3f4", "d3b5", "d3c5", "d3d5", "d3e5", "d3f5", "d3a6", "d3d6", "d3g6", "d3d7",
|
||||||
|
"d3h7", "d3d8", "e3c1", "e3d1", "e3e1", "e3f1", "e3g1", "e3c2", "e3d2", "e3e2",
|
||||||
|
"e3f2", "e3g2", "e3a3", "e3b3", "e3c3", "e3d3", "e3f3", "e3g3", "e3h3", "e3c4",
|
||||||
|
"e3d4", "e3e4", "e3f4", "e3g4", "e3c5", "e3d5", "e3e5", "e3f5", "e3g5", "e3b6",
|
||||||
|
"e3e6", "e3h6", "e3a7", "e3e7", "e3e8", "f3d1", "f3e1", "f3f1", "f3g1", "f3h1",
|
||||||
|
"f3d2", "f3e2", "f3f2", "f3g2", "f3h2", "f3a3", "f3b3", "f3c3", "f3d3", "f3e3",
|
||||||
|
"f3g3", "f3h3", "f3d4", "f3e4", "f3f4", "f3g4", "f3h4", "f3d5", "f3e5", "f3f5",
|
||||||
|
"f3g5", "f3h5", "f3c6", "f3f6", "f3b7", "f3f7", "f3a8", "f3f8", "g3e1", "g3f1",
|
||||||
|
"g3g1", "g3h1", "g3e2", "g3f2", "g3g2", "g3h2", "g3a3", "g3b3", "g3c3", "g3d3",
|
||||||
|
"g3e3", "g3f3", "g3h3", "g3e4", "g3f4", "g3g4", "g3h4", "g3e5", "g3f5", "g3g5",
|
||||||
|
"g3h5", "g3d6", "g3g6", "g3c7", "g3g7", "g3b8", "g3g8", "h3f1", "h3g1", "h3h1",
|
||||||
|
"h3f2", "h3g2", "h3h2", "h3a3", "h3b3", "h3c3", "h3d3", "h3e3", "h3f3", "h3g3",
|
||||||
|
"h3f4", "h3g4", "h3h4", "h3f5", "h3g5", "h3h5", "h3e6", "h3h6", "h3d7", "h3h7",
|
||||||
|
"h3c8", "h3h8", "a4a1", "a4d1", "a4a2", "a4b2", "a4c2", "a4a3", "a4b3", "a4c3",
|
||||||
|
"a4b4", "a4c4", "a4d4", "a4e4", "a4f4", "a4g4", "a4h4", "a4a5", "a4b5", "a4c5",
|
||||||
|
"a4a6", "a4b6", "a4c6", "a4a7", "a4d7", "a4a8", "a4e8", "b4b1", "b4e1", "b4a2",
|
||||||
|
"b4b2", "b4c2", "b4d2", "b4a3", "b4b3", "b4c3", "b4d3", "b4a4", "b4c4", "b4d4",
|
||||||
|
"b4e4", "b4f4", "b4g4", "b4h4", "b4a5", "b4b5", "b4c5", "b4d5", "b4a6", "b4b6",
|
||||||
|
"b4c6", "b4d6", "b4b7", "b4e7", "b4b8", "b4f8", "c4c1", "c4f1", "c4a2", "c4b2",
|
||||||
|
"c4c2", "c4d2", "c4e2", "c4a3", "c4b3", "c4c3", "c4d3", "c4e3", "c4a4", "c4b4",
|
||||||
|
"c4d4", "c4e4", "c4f4", "c4g4", "c4h4", "c4a5", "c4b5", "c4c5", "c4d5", "c4e5",
|
||||||
|
"c4a6", "c4b6", "c4c6", "c4d6", "c4e6", "c4c7", "c4f7", "c4c8", "c4g8", "d4a1",
|
||||||
|
"d4d1", "d4g1", "d4b2", "d4c2", "d4d2", "d4e2", "d4f2", "d4b3", "d4c3", "d4d3",
|
||||||
|
"d4e3", "d4f3", "d4a4", "d4b4", "d4c4", "d4e4", "d4f4", "d4g4", "d4h4", "d4b5",
|
||||||
|
"d4c5", "d4d5", "d4e5", "d4f5", "d4b6", "d4c6", "d4d6", "d4e6", "d4f6", "d4a7",
|
||||||
|
"d4d7", "d4g7", "d4d8", "d4h8", "e4b1", "e4e1", "e4h1", "e4c2", "e4d2", "e4e2",
|
||||||
|
"e4f2", "e4g2", "e4c3", "e4d3", "e4e3", "e4f3", "e4g3", "e4a4", "e4b4", "e4c4",
|
||||||
|
"e4d4", "e4f4", "e4g4", "e4h4", "e4c5", "e4d5", "e4e5", "e4f5", "e4g5", "e4c6",
|
||||||
|
"e4d6", "e4e6", "e4f6", "e4g6", "e4b7", "e4e7", "e4h7", "e4a8", "e4e8", "f4c1",
|
||||||
|
"f4f1", "f4d2", "f4e2", "f4f2", "f4g2", "f4h2", "f4d3", "f4e3", "f4f3", "f4g3",
|
||||||
|
"f4h3", "f4a4", "f4b4", "f4c4", "f4d4", "f4e4", "f4g4", "f4h4", "f4d5", "f4e5",
|
||||||
|
"f4f5", "f4g5", "f4h5", "f4d6", "f4e6", "f4f6", "f4g6", "f4h6", "f4c7", "f4f7",
|
||||||
|
"f4b8", "f4f8", "g4d1", "g4g1", "g4e2", "g4f2", "g4g2", "g4h2", "g4e3", "g4f3",
|
||||||
|
"g4g3", "g4h3", "g4a4", "g4b4", "g4c4", "g4d4", "g4e4", "g4f4", "g4h4", "g4e5",
|
||||||
|
"g4f5", "g4g5", "g4h5", "g4e6", "g4f6", "g4g6", "g4h6", "g4d7", "g4g7", "g4c8",
|
||||||
|
"g4g8", "h4e1", "h4h1", "h4f2", "h4g2", "h4h2", "h4f3", "h4g3", "h4h3", "h4a4",
|
||||||
|
"h4b4", "h4c4", "h4d4", "h4e4", "h4f4", "h4g4", "h4f5", "h4g5", "h4h5", "h4f6",
|
||||||
|
"h4g6", "h4h6", "h4e7", "h4h7", "h4d8", "h4h8", "a5a1", "a5e1", "a5a2", "a5d2",
|
||||||
|
"a5a3", "a5b3", "a5c3", "a5a4", "a5b4", "a5c4", "a5b5", "a5c5", "a5d5", "a5e5",
|
||||||
|
"a5f5", "a5g5", "a5h5", "a5a6", "a5b6", "a5c6", "a5a7", "a5b7", "a5c7", "a5a8",
|
||||||
|
"a5d8", "b5b1", "b5f1", "b5b2", "b5e2", "b5a3", "b5b3", "b5c3", "b5d3", "b5a4",
|
||||||
|
"b5b4", "b5c4", "b5d4", "b5a5", "b5c5", "b5d5", "b5e5", "b5f5", "b5g5", "b5h5",
|
||||||
|
"b5a6", "b5b6", "b5c6", "b5d6", "b5a7", "b5b7", "b5c7", "b5d7", "b5b8", "b5e8",
|
||||||
|
"c5c1", "c5g1", "c5c2", "c5f2", "c5a3", "c5b3", "c5c3", "c5d3", "c5e3", "c5a4",
|
||||||
|
"c5b4", "c5c4", "c5d4", "c5e4", "c5a5", "c5b5", "c5d5", "c5e5", "c5f5", "c5g5",
|
||||||
|
"c5h5", "c5a6", "c5b6", "c5c6", "c5d6", "c5e6", "c5a7", "c5b7", "c5c7", "c5d7",
|
||||||
|
"c5e7", "c5c8", "c5f8", "d5d1", "d5h1", "d5a2", "d5d2", "d5g2", "d5b3", "d5c3",
|
||||||
|
"d5d3", "d5e3", "d5f3", "d5b4", "d5c4", "d5d4", "d5e4", "d5f4", "d5a5", "d5b5",
|
||||||
|
"d5c5", "d5e5", "d5f5", "d5g5", "d5h5", "d5b6", "d5c6", "d5d6", "d5e6", "d5f6",
|
||||||
|
"d5b7", "d5c7", "d5d7", "d5e7", "d5f7", "d5a8", "d5d8", "d5g8", "e5a1", "e5e1",
|
||||||
|
"e5b2", "e5e2", "e5h2", "e5c3", "e5d3", "e5e3", "e5f3", "e5g3", "e5c4", "e5d4",
|
||||||
|
"e5e4", "e5f4", "e5g4", "e5a5", "e5b5", "e5c5", "e5d5", "e5f5", "e5g5", "e5h5",
|
||||||
|
"e5c6", "e5d6", "e5e6", "e5f6", "e5g6", "e5c7", "e5d7", "e5e7", "e5f7", "e5g7",
|
||||||
|
"e5b8", "e5e8", "e5h8", "f5b1", "f5f1", "f5c2", "f5f2", "f5d3", "f5e3", "f5f3",
|
||||||
|
"f5g3", "f5h3", "f5d4", "f5e4", "f5f4", "f5g4", "f5h4", "f5a5", "f5b5", "f5c5",
|
||||||
|
"f5d5", "f5e5", "f5g5", "f5h5", "f5d6", "f5e6", "f5f6", "f5g6", "f5h6", "f5d7",
|
||||||
|
"f5e7", "f5f7", "f5g7", "f5h7", "f5c8", "f5f8", "g5c1", "g5g1", "g5d2", "g5g2",
|
||||||
|
"g5e3", "g5f3", "g5g3", "g5h3", "g5e4", "g5f4", "g5g4", "g5h4", "g5a5", "g5b5",
|
||||||
|
"g5c5", "g5d5", "g5e5", "g5f5", "g5h5", "g5e6", "g5f6", "g5g6", "g5h6", "g5e7",
|
||||||
|
"g5f7", "g5g7", "g5h7", "g5d8", "g5g8", "h5d1", "h5h1", "h5e2", "h5h2", "h5f3",
|
||||||
|
"h5g3", "h5h3", "h5f4", "h5g4", "h5h4", "h5a5", "h5b5", "h5c5", "h5d5", "h5e5",
|
||||||
|
"h5f5", "h5g5", "h5f6", "h5g6", "h5h6", "h5f7", "h5g7", "h5h7", "h5e8", "h5h8",
|
||||||
|
"a6a1", "a6f1", "a6a2", "a6e2", "a6a3", "a6d3", "a6a4", "a6b4", "a6c4", "a6a5",
|
||||||
|
"a6b5", "a6c5", "a6b6", "a6c6", "a6d6", "a6e6", "a6f6", "a6g6", "a6h6", "a6a7",
|
||||||
|
"a6b7", "a6c7", "a6a8", "a6b8", "a6c8", "b6b1", "b6g1", "b6b2", "b6f2", "b6b3",
|
||||||
|
"b6e3", "b6a4", "b6b4", "b6c4", "b6d4", "b6a5", "b6b5", "b6c5", "b6d5", "b6a6",
|
||||||
|
"b6c6", "b6d6", "b6e6", "b6f6", "b6g6", "b6h6", "b6a7", "b6b7", "b6c7", "b6d7",
|
||||||
|
"b6a8", "b6b8", "b6c8", "b6d8", "c6c1", "c6h1", "c6c2", "c6g2", "c6c3", "c6f3",
|
||||||
|
"c6a4", "c6b4", "c6c4", "c6d4", "c6e4", "c6a5", "c6b5", "c6c5", "c6d5", "c6e5",
|
||||||
|
"c6a6", "c6b6", "c6d6", "c6e6", "c6f6", "c6g6", "c6h6", "c6a7", "c6b7", "c6c7",
|
||||||
|
"c6d7", "c6e7", "c6a8", "c6b8", "c6c8", "c6d8", "c6e8", "d6d1", "d6d2", "d6h2",
|
||||||
|
"d6a3", "d6d3", "d6g3", "d6b4", "d6c4", "d6d4", "d6e4", "d6f4", "d6b5", "d6c5",
|
||||||
|
"d6d5", "d6e5", "d6f5", "d6a6", "d6b6", "d6c6", "d6e6", "d6f6", "d6g6", "d6h6",
|
||||||
|
"d6b7", "d6c7", "d6d7", "d6e7", "d6f7", "d6b8", "d6c8", "d6d8", "d6e8", "d6f8",
|
||||||
|
"e6e1", "e6a2", "e6e2", "e6b3", "e6e3", "e6h3", "e6c4", "e6d4", "e6e4", "e6f4",
|
||||||
|
"e6g4", "e6c5", "e6d5", "e6e5", "e6f5", "e6g5", "e6a6", "e6b6", "e6c6", "e6d6",
|
||||||
|
"e6f6", "e6g6", "e6h6", "e6c7", "e6d7", "e6e7", "e6f7", "e6g7", "e6c8", "e6d8",
|
||||||
|
"e6e8", "e6f8", "e6g8", "f6a1", "f6f1", "f6b2", "f6f2", "f6c3", "f6f3", "f6d4",
|
||||||
|
"f6e4", "f6f4", "f6g4", "f6h4", "f6d5", "f6e5", "f6f5", "f6g5", "f6h5", "f6a6",
|
||||||
|
"f6b6", "f6c6", "f6d6", "f6e6", "f6g6", "f6h6", "f6d7", "f6e7", "f6f7", "f6g7",
|
||||||
|
"f6h7", "f6d8", "f6e8", "f6f8", "f6g8", "f6h8", "g6b1", "g6g1", "g6c2", "g6g2",
|
||||||
|
"g6d3", "g6g3", "g6e4", "g6f4", "g6g4", "g6h4", "g6e5", "g6f5", "g6g5", "g6h5",
|
||||||
|
"g6a6", "g6b6", "g6c6", "g6d6", "g6e6", "g6f6", "g6h6", "g6e7", "g6f7", "g6g7",
|
||||||
|
"g6h7", "g6e8", "g6f8", "g6g8", "g6h8", "h6c1", "h6h1", "h6d2", "h6h2", "h6e3",
|
||||||
|
"h6h3", "h6f4", "h6g4", "h6h4", "h6f5", "h6g5", "h6h5", "h6a6", "h6b6", "h6c6",
|
||||||
|
"h6d6", "h6e6", "h6f6", "h6g6", "h6f7", "h6g7", "h6h7", "h6f8", "h6g8", "h6h8",
|
||||||
|
"a7a1", "a7g1", "a7a2", "a7f2", "a7a3", "a7e3", "a7a4", "a7d4", "a7a5", "a7b5",
|
||||||
|
"a7c5", "a7a6", "a7b6", "a7c6", "a7b7", "a7c7", "a7d7", "a7e7", "a7f7", "a7g7",
|
||||||
|
"a7h7", "a7a8", "a7b8", "a7c8", "b7b1", "b7h1", "b7b2", "b7g2", "b7b3", "b7f3",
|
||||||
|
"b7b4", "b7e4", "b7a5", "b7b5", "b7c5", "b7d5", "b7a6", "b7b6", "b7c6", "b7d6",
|
||||||
|
"b7a7", "b7c7", "b7d7", "b7e7", "b7f7", "b7g7", "b7h7", "b7a8", "b7b8", "b7c8",
|
||||||
|
"b7d8", "c7c1", "c7c2", "c7h2", "c7c3", "c7g3", "c7c4", "c7f4", "c7a5", "c7b5",
|
||||||
|
"c7c5", "c7d5", "c7e5", "c7a6", "c7b6", "c7c6", "c7d6", "c7e6", "c7a7", "c7b7",
|
||||||
|
"c7d7", "c7e7", "c7f7", "c7g7", "c7h7", "c7a8", "c7b8", "c7c8", "c7d8", "c7e8",
|
||||||
|
"d7d1", "d7d2", "d7d3", "d7h3", "d7a4", "d7d4", "d7g4", "d7b5", "d7c5", "d7d5",
|
||||||
|
"d7e5", "d7f5", "d7b6", "d7c6", "d7d6", "d7e6", "d7f6", "d7a7", "d7b7", "d7c7",
|
||||||
|
"d7e7", "d7f7", "d7g7", "d7h7", "d7b8", "d7c8", "d7d8", "d7e8", "d7f8", "e7e1",
|
||||||
|
"e7e2", "e7a3", "e7e3", "e7b4", "e7e4", "e7h4", "e7c5", "e7d5", "e7e5", "e7f5",
|
||||||
|
"e7g5", "e7c6", "e7d6", "e7e6", "e7f6", "e7g6", "e7a7", "e7b7", "e7c7", "e7d7",
|
||||||
|
"e7f7", "e7g7", "e7h7", "e7c8", "e7d8", "e7e8", "e7f8", "e7g8", "f7f1", "f7a2",
|
||||||
|
"f7f2", "f7b3", "f7f3", "f7c4", "f7f4", "f7d5", "f7e5", "f7f5", "f7g5", "f7h5",
|
||||||
|
"f7d6", "f7e6", "f7f6", "f7g6", "f7h6", "f7a7", "f7b7", "f7c7", "f7d7", "f7e7",
|
||||||
|
"f7g7", "f7h7", "f7d8", "f7e8", "f7f8", "f7g8", "f7h8", "g7a1", "g7g1", "g7b2",
|
||||||
|
"g7g2", "g7c3", "g7g3", "g7d4", "g7g4", "g7e5", "g7f5", "g7g5", "g7h5", "g7e6",
|
||||||
|
"g7f6", "g7g6", "g7h6", "g7a7", "g7b7", "g7c7", "g7d7", "g7e7", "g7f7", "g7h7",
|
||||||
|
"g7e8", "g7f8", "g7g8", "g7h8", "h7b1", "h7h1", "h7c2", "h7h2", "h7d3", "h7h3",
|
||||||
|
"h7e4", "h7h4", "h7f5", "h7g5", "h7h5", "h7f6", "h7g6", "h7h6", "h7a7", "h7b7",
|
||||||
|
"h7c7", "h7d7", "h7e7", "h7f7", "h7g7", "h7f8", "h7g8", "h7h8", "a8a1", "a8h1",
|
||||||
|
"a8a2", "a8g2", "a8a3", "a8f3", "a8a4", "a8e4", "a8a5", "a8d5", "a8a6", "a8b6",
|
||||||
|
"a8c6", "a8a7", "a8b7", "a8c7", "a8b8", "a8c8", "a8d8", "a8e8", "a8f8", "a8g8",
|
||||||
|
"a8h8", "b8b1", "b8b2", "b8h2", "b8b3", "b8g3", "b8b4", "b8f4", "b8b5", "b8e5",
|
||||||
|
"b8a6", "b8b6", "b8c6", "b8d6", "b8a7", "b8b7", "b8c7", "b8d7", "b8a8", "b8c8",
|
||||||
|
"b8d8", "b8e8", "b8f8", "b8g8", "b8h8", "c8c1", "c8c2", "c8c3", "c8h3", "c8c4",
|
||||||
|
"c8g4", "c8c5", "c8f5", "c8a6", "c8b6", "c8c6", "c8d6", "c8e6", "c8a7", "c8b7",
|
||||||
|
"c8c7", "c8d7", "c8e7", "c8a8", "c8b8", "c8d8", "c8e8", "c8f8", "c8g8", "c8h8",
|
||||||
|
"d8d1", "d8d2", "d8d3", "d8d4", "d8h4", "d8a5", "d8d5", "d8g5", "d8b6", "d8c6",
|
||||||
|
"d8d6", "d8e6", "d8f6", "d8b7", "d8c7", "d8d7", "d8e7", "d8f7", "d8a8", "d8b8",
|
||||||
|
"d8c8", "d8e8", "d8f8", "d8g8", "d8h8", "e8e1", "e8e2", "e8e3", "e8a4", "e8e4",
|
||||||
|
"e8b5", "e8e5", "e8h5", "e8c6", "e8d6", "e8e6", "e8f6", "e8g6", "e8c7", "e8d7",
|
||||||
|
"e8e7", "e8f7", "e8g7", "e8a8", "e8b8", "e8c8", "e8d8", "e8f8", "e8g8", "e8h8",
|
||||||
|
"f8f1", "f8f2", "f8a3", "f8f3", "f8b4", "f8f4", "f8c5", "f8f5", "f8d6", "f8e6",
|
||||||
|
"f8f6", "f8g6", "f8h6", "f8d7", "f8e7", "f8f7", "f8g7", "f8h7", "f8a8", "f8b8",
|
||||||
|
"f8c8", "f8d8", "f8e8", "f8g8", "f8h8", "g8g1", "g8a2", "g8g2", "g8b3", "g8g3",
|
||||||
|
"g8c4", "g8g4", "g8d5", "g8g5", "g8e6", "g8f6", "g8g6", "g8h6", "g8e7", "g8f7",
|
||||||
|
"g8g7", "g8h7", "g8a8", "g8b8", "g8c8", "g8d8", "g8e8", "g8f8", "g8h8", "h8a1",
|
||||||
|
"h8h1", "h8b2", "h8h2", "h8c3", "h8h3", "h8d4", "h8h4", "h8e5", "h8h5", "h8f6",
|
||||||
|
"h8g6", "h8h6", "h8f7", "h8g7", "h8h7", "h8a8", "h8b8", "h8c8", "h8d8", "h8e8",
|
||||||
|
"h8f8", "h8g8", "a7a8q", "a7a8r", "a7a8b", "a7b8q", "a7b8r", "a7b8b", "b7a8q", "b7a8r",
|
||||||
|
"b7a8b", "b7b8q", "b7b8r", "b7b8b", "b7c8q", "b7c8r", "b7c8b", "c7b8q", "c7b8r", "c7b8b",
|
||||||
|
"c7c8q", "c7c8r", "c7c8b", "c7d8q", "c7d8r", "c7d8b", "d7c8q", "d7c8r", "d7c8b", "d7d8q",
|
||||||
|
"d7d8r", "d7d8b", "d7e8q", "d7e8r", "d7e8b", "e7d8q", "e7d8r", "e7d8b", "e7e8q", "e7e8r",
|
||||||
|
"e7e8b", "e7f8q", "e7f8r", "e7f8b", "f7e8q", "f7e8r", "f7e8b", "f7f8q", "f7f8r", "f7f8b",
|
||||||
|
"f7g8q", "f7g8r", "f7g8b", "g7f8q", "g7f8r", "g7f8b", "g7g8q", "g7g8r", "g7g8b", "g7h8q",
|
||||||
|
"g7h8r", "g7h8b", "h7g8q", "h7g8r", "h7g8b", "h7h8q", "h7h8r", "h7h8b",
|
||||||
|
];
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
pub mod data;
|
||||||
|
pub mod inputs;
|
||||||
|
pub mod lc0;
|
||||||
|
pub mod lc0_policy;
|
||||||
|
pub mod model;
|
||||||
@@ -0,0 +1,155 @@
|
|||||||
|
//! Rigby policy network trainer.
|
||||||
|
//!
|
||||||
|
//! Architecture: 3072 threat inputs -> HIDDEN -> CReLU -> pairwise multiply
|
||||||
|
//! (HIDDEN / 2) -> one output row per legal move, softmax over the legal moves.
|
||||||
|
//! Data: Lc0 self-play converted to montyformat by `lc02monty`, shuffled across
|
||||||
|
//! files by `interleave`. Target: Lc0's visit distribution.
|
||||||
|
//!
|
||||||
|
//! Usage:
|
||||||
|
//! rigby-policy [--data FILE] [--superbatches N] [--hidden N] [--id NAME] [--buffer-mb N] [--batches N]
|
||||||
|
//!
|
||||||
|
//! A superbatch is `--batches` batches of 16384 positions (default 6104, about
|
||||||
|
//! 100M positions); fewer batches make quick test runs.
|
||||||
|
//! rigby-policy --check checkpoints/<id>-<superbatch> [--hidden N]
|
||||||
|
//!
|
||||||
|
//! `--check` loads a checkpoint and prints the policy of a few fixed positions,
|
||||||
|
//! as a reference for the engine's inference (Rigby's `policyfens` command
|
||||||
|
//! prints the same list).
|
||||||
|
//!
|
||||||
|
//! checkpoints/<id>-<superbatch>/quantised.bin is written every SAVE_RATE
|
||||||
|
//! superbatches and at the end; README.md describes its layout.
|
||||||
|
|
||||||
|
use acyclib::{
|
||||||
|
device::Device,
|
||||||
|
trainer::{
|
||||||
|
optimiser::{
|
||||||
|
adam::{AdamW, AdamWParams},
|
||||||
|
Optimiser,
|
||||||
|
},
|
||||||
|
schedule::{TrainingSchedule, TrainingSteps},
|
||||||
|
Trainer,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use bullet_cuda_backend::CudaDevice;
|
||||||
|
|
||||||
|
use rigby_policy::{data::MontyDataLoader, model};
|
||||||
|
|
||||||
|
const DEFAULT_DATA: &str = "../data/lc0/policy.binpack";
|
||||||
|
const DEFAULT_SUPERBATCHES: usize = 10;
|
||||||
|
const DEFAULT_HIDDEN: usize = 1024;
|
||||||
|
const DEFAULT_BUFFER_MB: usize = 4096;
|
||||||
|
const SAVE_RATE: usize = 5;
|
||||||
|
const BATCH_SIZE: usize = 16_384;
|
||||||
|
const BATCHES_PER_SUPERBATCH: usize = 6104;
|
||||||
|
const INITIAL_LR: f32 = 0.001;
|
||||||
|
const FINAL_LR: f32 = 0.00001;
|
||||||
|
|
||||||
|
/// Positions for `--check`; keep in sync with Rigby's `policyfens` command.
|
||||||
|
pub const CHECK_FENS: [&str; 6] = [
|
||||||
|
"rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1",
|
||||||
|
"rnbqkbnr/pppppppp/8/8/4P3/8/PPPP1PPP/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/2P2k2/8/8/8/8/5K2/8 w - - 0 1",
|
||||||
|
];
|
||||||
|
|
||||||
|
struct Args {
|
||||||
|
data: String,
|
||||||
|
superbatches: usize,
|
||||||
|
hidden: usize,
|
||||||
|
id: String,
|
||||||
|
buffer_mb: usize,
|
||||||
|
batches: usize,
|
||||||
|
check: Option<String>,
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse_args() -> Args {
|
||||||
|
let mut args = Args {
|
||||||
|
data: DEFAULT_DATA.to_string(),
|
||||||
|
superbatches: DEFAULT_SUPERBATCHES,
|
||||||
|
hidden: DEFAULT_HIDDEN,
|
||||||
|
id: "rigby-policy".to_string(),
|
||||||
|
buffer_mb: DEFAULT_BUFFER_MB,
|
||||||
|
batches: BATCHES_PER_SUPERBATCH,
|
||||||
|
check: None,
|
||||||
|
};
|
||||||
|
let mut it = std::env::args().skip(1);
|
||||||
|
let number = |v: Option<String>, name: &str| -> usize {
|
||||||
|
v.unwrap_or_else(|| panic!("{name} needs a number")).parse().expect("not a number")
|
||||||
|
};
|
||||||
|
while let Some(arg) = it.next() {
|
||||||
|
match arg.as_str() {
|
||||||
|
"--data" => args.data = it.next().expect("--data needs a path"),
|
||||||
|
"--superbatches" => args.superbatches = number(it.next(), "--superbatches"),
|
||||||
|
"--hidden" => args.hidden = number(it.next(), "--hidden"),
|
||||||
|
"--buffer-mb" => args.buffer_mb = number(it.next(), "--buffer-mb"),
|
||||||
|
"--batches" => args.batches = number(it.next(), "--batches"),
|
||||||
|
"--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}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
assert!(args.hidden % 2 == 0, "--hidden must be even");
|
||||||
|
if args.check.is_none() {
|
||||||
|
assert!(std::path::Path::new(&args.data).exists(), "data file not found: {}", args.data);
|
||||||
|
}
|
||||||
|
args
|
||||||
|
}
|
||||||
|
|
||||||
|
fn main() {
|
||||||
|
let args = parse_args();
|
||||||
|
|
||||||
|
let device = CudaDevice::new(0).unwrap();
|
||||||
|
let (graph, node) = model::make(device, args.hidden);
|
||||||
|
|
||||||
|
let params = AdamWParams { decay: 0.01, beta1: 0.9, beta2: 0.999, min_weight: -0.99, max_weight: 0.99 };
|
||||||
|
let optimiser = Optimiser::<_, _, AdamW<_>>::new(graph, params).unwrap();
|
||||||
|
let mut trainer = Trainer { optimiser, state: () };
|
||||||
|
|
||||||
|
if let Some(checkpoint) = &args.check {
|
||||||
|
trainer.optimiser.load_from_checkpoint(&format!("{checkpoint}/optimiser_state")).unwrap();
|
||||||
|
for fen in CHECK_FENS {
|
||||||
|
model::eval(&mut trainer.optimiser.graph, node, fen);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let dataloader = MontyDataLoader::new(&args.data, args.buffer_mb, 4, 8);
|
||||||
|
|
||||||
|
let end_superbatch = args.superbatches;
|
||||||
|
let steps =
|
||||||
|
TrainingSteps { batch_size: BATCH_SIZE, batches_per_superbatch: args.batches, start_superbatch: 1, end_superbatch };
|
||||||
|
|
||||||
|
let schedule = TrainingSchedule {
|
||||||
|
steps,
|
||||||
|
log_rate: 64,
|
||||||
|
lr_schedule: Box::new(move |_, sb| {
|
||||||
|
if sb >= end_superbatch {
|
||||||
|
return FINAL_LR;
|
||||||
|
}
|
||||||
|
let lambda = sb as f32 / end_superbatch as f32;
|
||||||
|
INITIAL_LR * (FINAL_LR / INITIAL_LR).powf(lambda)
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
|
||||||
|
let id = args.id.clone();
|
||||||
|
trainer
|
||||||
|
.train_custom(
|
||||||
|
schedule,
|
||||||
|
dataloader,
|
||||||
|
|_, _, _, _| {},
|
||||||
|
|trainer, superbatch| {
|
||||||
|
if superbatch % SAVE_RATE == 0 || superbatch == end_superbatch {
|
||||||
|
let dir = format!("checkpoints/{id}-{superbatch}");
|
||||||
|
println!("Saving checkpoint {dir}");
|
||||||
|
std::fs::create_dir_all(format!("{dir}/optimiser_state")).unwrap();
|
||||||
|
trainer.optimiser.write_to_checkpoint(&format!("{dir}/optimiser_state")).unwrap();
|
||||||
|
model::save_quantised(&trainer.optimiser.graph, &format!("{dir}/quantised.bin")).unwrap();
|
||||||
|
}
|
||||||
|
},
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
model::eval(&mut trainer.optimiser.graph, node, CHECK_FENS[0]);
|
||||||
|
}
|
||||||
@@ -0,0 +1,92 @@
|
|||||||
|
mod loss;
|
||||||
|
mod select_affine;
|
||||||
|
|
||||||
|
use acyclib::{
|
||||||
|
device::tensor::Shape,
|
||||||
|
graph::{builder::GraphBuilder, Graph, GraphNodeId, GraphNodeIdTy},
|
||||||
|
trainer::dataloader::PreparedBatchDevice,
|
||||||
|
};
|
||||||
|
use bullet_cuda_backend::CudaDevice;
|
||||||
|
use montyformat::chess::{Castling, Move, Position};
|
||||||
|
|
||||||
|
use crate::{
|
||||||
|
data::{loader::prepare, reader::DecompressedData},
|
||||||
|
inputs::{INPUT_SIZE, MAX_ACTIVE_BASE, MAX_MOVES, NUM_MOVES_INDICES},
|
||||||
|
};
|
||||||
|
|
||||||
|
pub fn make(device: CudaDevice, hl: usize) -> (Graph<CudaDevice>, GraphNodeId) {
|
||||||
|
let builder = GraphBuilder::default();
|
||||||
|
|
||||||
|
let inputs = builder.new_sparse_input("inputs", Shape::new(INPUT_SIZE, 1), MAX_ACTIVE_BASE);
|
||||||
|
let targets = builder.new_dense_input("targets", Shape::new(MAX_MOVES, 1));
|
||||||
|
let moves = builder.new_sparse_input("moves", Shape::new(NUM_MOVES_INDICES, 1), MAX_MOVES);
|
||||||
|
|
||||||
|
let l0 = builder.new_affine("l0", INPUT_SIZE, hl);
|
||||||
|
let l1 = builder.new_affine("l1", hl / 2, NUM_MOVES_INDICES);
|
||||||
|
|
||||||
|
let hl = l0.forward(inputs).crelu().pairwise_mul();
|
||||||
|
|
||||||
|
let logits = builder.apply(select_affine::SelectAffine::new(l1, hl, moves));
|
||||||
|
|
||||||
|
let ones = builder.new_constant(Shape::new(1, MAX_MOVES), &[1.0; MAX_MOVES]);
|
||||||
|
let loss = builder.apply(loss::OptimisedSoftmaxCrossEntropy::new(logits, targets));
|
||||||
|
let _ = ones.matmul(loss);
|
||||||
|
|
||||||
|
let node = GraphNodeId::new(loss.annotated_node().idx, GraphNodeIdTy::Ancillary(0));
|
||||||
|
(builder.build(device), node)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn eval(graph: &mut Graph<CudaDevice>, node: GraphNodeId, fen: &str) {
|
||||||
|
let mut castling = Castling::default();
|
||||||
|
let pos = Position::parse_fen(fen, &mut castling);
|
||||||
|
|
||||||
|
let mut moves = [(0, 0); 64];
|
||||||
|
let mut num = 0;
|
||||||
|
|
||||||
|
pos.map_legal_moves(&castling, |mov| {
|
||||||
|
moves[num] = (u16::from(mov), 1);
|
||||||
|
num += 1;
|
||||||
|
});
|
||||||
|
|
||||||
|
let point = DecompressedData { pos, castling, moves, num };
|
||||||
|
|
||||||
|
let data = prepare(&[point], 1);
|
||||||
|
|
||||||
|
let mut on_device = PreparedBatchDevice::new(vec![graph.device()], &data).unwrap();
|
||||||
|
|
||||||
|
on_device.load_into_graph(graph).unwrap();
|
||||||
|
|
||||||
|
let _ = graph.forward().unwrap();
|
||||||
|
|
||||||
|
let dist = graph.get(node).unwrap().get_dense_vals().unwrap();
|
||||||
|
|
||||||
|
let mut out: Vec<(String, f32)> =
|
||||||
|
(0..num).map(|i| (Move::from(moves[i].0).to_uci(&castling), dist[i] * 100.0)).collect();
|
||||||
|
out.sort_by(|a, b| b.1.total_cmp(&a.1).then_with(|| a.0.cmp(&b.0)));
|
||||||
|
|
||||||
|
println!();
|
||||||
|
println!("{fen}");
|
||||||
|
for (uci, pct) in out {
|
||||||
|
println!(" {uci:<6} {pct:6.2}%");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn save_quantised(graph: &Graph<CudaDevice>, path: &str) -> std::io::Result<()> {
|
||||||
|
use std::io::Write;
|
||||||
|
|
||||||
|
let mut file = std::fs::File::create(path).unwrap();
|
||||||
|
|
||||||
|
let mut quant = Vec::new();
|
||||||
|
|
||||||
|
for id in ["l0w", "l0b", "l1w", "l1b"] {
|
||||||
|
let vals = graph.get_weights(id).get_dense_vals().unwrap();
|
||||||
|
|
||||||
|
for x in vals {
|
||||||
|
let q = (x * 128.0).round() as i8;
|
||||||
|
assert_eq!((x * 128.0).round(), f32::from(q));
|
||||||
|
quant.extend_from_slice(&q.to_le_bytes());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
file.write_all(&quant)
|
||||||
|
}
|
||||||
@@ -0,0 +1,105 @@
|
|||||||
|
use std::num::NonZeroUsize;
|
||||||
|
|
||||||
|
use acyclib::{
|
||||||
|
dag::NodeId,
|
||||||
|
device::{
|
||||||
|
function::{self, DeviceFunction},
|
||||||
|
tensor::Shape,
|
||||||
|
},
|
||||||
|
graph::{
|
||||||
|
builder::GraphBuilderNode,
|
||||||
|
ir::{
|
||||||
|
node::AnnotatedNode,
|
||||||
|
operation::{binary::SoftmaxCrossEntropy, GraphIROperationBase, GraphIROperationCompilable},
|
||||||
|
GraphIR, GraphIRError,
|
||||||
|
},
|
||||||
|
Graph, GraphNodeIdTy,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use bullet_cuda_backend::{
|
||||||
|
kernel::{Expr, Kernel, KernelArgs, KernelInput},
|
||||||
|
CudaDevice, CudaMarker,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::inputs::MAX_MOVES;
|
||||||
|
|
||||||
|
#[derive(Clone, Debug)]
|
||||||
|
pub struct OptimisedSoftmaxCrossEntropy(SoftmaxCrossEntropy);
|
||||||
|
|
||||||
|
impl OptimisedSoftmaxCrossEntropy {
|
||||||
|
pub fn new<'a>(logits: GraphBuilderNode<'a, CudaMarker>, targets: GraphBuilderNode<'a, CudaMarker>) -> Self {
|
||||||
|
Self(SoftmaxCrossEntropy { logits: logits.annotated_node(), targets: targets.annotated_node() })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GraphIROperationBase<CudaMarker> for OptimisedSoftmaxCrossEntropy {
|
||||||
|
fn nodes(&self) -> Vec<AnnotatedNode> {
|
||||||
|
GraphIROperationBase::<CudaMarker>::nodes(&self.0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn output_shape(&self, ir: &GraphIR<CudaMarker>) -> Result<Shape, GraphIRError> {
|
||||||
|
assert_eq!(self.0.logits.shape, Shape::new(MAX_MOVES, 1));
|
||||||
|
self.0.output_shape(ir)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn ancillary_buffers(
|
||||||
|
&self,
|
||||||
|
ir: &GraphIR<CudaMarker>,
|
||||||
|
) -> Result<Vec<(Shape, Option<NonZeroUsize>, bool)>, GraphIRError> {
|
||||||
|
self.0.ancillary_buffers(ir)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GraphIROperationCompilable<CudaMarker> for OptimisedSoftmaxCrossEntropy {
|
||||||
|
fn forward_pass(&self, graph: &Graph<CudaDevice>, output_node: NodeId) -> DeviceFunction<CudaDevice> {
|
||||||
|
let logits = graph.get_ref(self.0.logits.idx, GraphNodeIdTy::Values);
|
||||||
|
let targets = graph.get_ref(self.0.targets.idx, GraphNodeIdTy::Values);
|
||||||
|
let smax = graph.get_ref(output_node, GraphNodeIdTy::Ancillary(0));
|
||||||
|
let output = graph.get_ref(output_node, GraphNodeIdTy::Values);
|
||||||
|
|
||||||
|
let mut func = DeviceFunction::default();
|
||||||
|
|
||||||
|
func.push(function::MaybeUpdateBatchSize { input: logits.clone(), output: smax.clone() });
|
||||||
|
func.push(function::MaybeUpdateBatchSize { input: logits.clone(), output: output.clone() });
|
||||||
|
|
||||||
|
let threads = 512;
|
||||||
|
let entries_per_block = threads / 32;
|
||||||
|
let batch_size = Expr::Var;
|
||||||
|
let blocks = (batch_size.clone() + entries_per_block - 1) / entries_per_block;
|
||||||
|
let grid_dim = [blocks, Expr::Const(1), Expr::Const(1)];
|
||||||
|
let block_dim = [threads, 1, 1].map(Expr::Const);
|
||||||
|
let shared_mem_bytes = Expr::Const(0);
|
||||||
|
|
||||||
|
let layout = None;
|
||||||
|
let batched = logits.batch_size().is_some();
|
||||||
|
let shape = Shape::new(MAX_MOVES, 1);
|
||||||
|
|
||||||
|
let inputs = vec![
|
||||||
|
KernelInput::Size(batch_size),
|
||||||
|
KernelInput::Slice { slice: logits, layout, mutable: false, batched, shape },
|
||||||
|
KernelInput::Slice { slice: smax.clone(), layout, mutable: true, batched, shape },
|
||||||
|
];
|
||||||
|
|
||||||
|
let args = KernelArgs { inputs, grid_dim, block_dim, shared_mem_bytes };
|
||||||
|
|
||||||
|
let code = include_str!("loss/softmax.cu")
|
||||||
|
.lines()
|
||||||
|
.skip(5)
|
||||||
|
.map(|x| format!("{x}\n"))
|
||||||
|
.collect::<String>()
|
||||||
|
.replace("THREADS", &threads.to_string())
|
||||||
|
.replace("SIZE", &MAX_MOVES.to_string());
|
||||||
|
|
||||||
|
let kernel = unsafe { Kernel::new("Softmax".to_string(), code, args) };
|
||||||
|
|
||||||
|
func.push(kernel.unwrap());
|
||||||
|
|
||||||
|
func.push(function::CrossEntropy { a: smax, b: targets, output });
|
||||||
|
|
||||||
|
func
|
||||||
|
}
|
||||||
|
|
||||||
|
fn backward_pass(&self, graph: &Graph<CudaDevice>, output_node: NodeId) -> DeviceFunction<CudaDevice> {
|
||||||
|
GraphIROperationCompilable::<CudaMarker>::backward_pass(&self.0, graph, output_node)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,54 @@
|
|||||||
|
#ifndef STUFF
|
||||||
|
#define THREADS 512;
|
||||||
|
#define SIZE 64
|
||||||
|
#endif
|
||||||
|
|
||||||
|
constexpr int threads = THREADS;
|
||||||
|
constexpr int per_block = threads / 32;
|
||||||
|
constexpr int size = SIZE;
|
||||||
|
constexpr int per_thread = size / 32;
|
||||||
|
|
||||||
|
extern "C" __global__ void kernel(const int k, const float* input, float* output)
|
||||||
|
{
|
||||||
|
const int entry = per_block * blockIdx.x + (threadIdx.x / 32);
|
||||||
|
const int widx = threadIdx.x % 32;
|
||||||
|
|
||||||
|
if (entry >= k)
|
||||||
|
return;
|
||||||
|
|
||||||
|
float elems[per_thread];
|
||||||
|
|
||||||
|
elems[0] = input[widx + size * entry];
|
||||||
|
float maximum = elems[0];
|
||||||
|
|
||||||
|
#pragma unroll
|
||||||
|
for (int i = 1; i < per_thread; i++) {
|
||||||
|
elems[i] = input[widx + 32 * i + size * entry];
|
||||||
|
maximum = max(maximum, elems[i]);
|
||||||
|
}
|
||||||
|
|
||||||
|
maximum = max(maximum, __shfl_xor_sync(0xffffffff, maximum, 16));
|
||||||
|
maximum = max(maximum, __shfl_xor_sync(0xffffffff, maximum, 8));
|
||||||
|
maximum = max(maximum, __shfl_xor_sync(0xffffffff, maximum, 4));
|
||||||
|
maximum = max(maximum, __shfl_xor_sync(0xffffffff, maximum, 2));
|
||||||
|
maximum = max(maximum, __shfl_xor_sync(0xffffffff, maximum, 1));
|
||||||
|
|
||||||
|
float denom = 0.0F;
|
||||||
|
|
||||||
|
#pragma unroll
|
||||||
|
for (int i = 0; i < per_thread; i++) {
|
||||||
|
elems[i] = expf(elems[i] - maximum);
|
||||||
|
denom += elems[i];
|
||||||
|
}
|
||||||
|
|
||||||
|
denom += __shfl_xor_sync(0xffffffff, denom, 16);
|
||||||
|
denom += __shfl_xor_sync(0xffffffff, denom, 8);
|
||||||
|
denom += __shfl_xor_sync(0xffffffff, denom, 4);
|
||||||
|
denom += __shfl_xor_sync(0xffffffff, denom, 2);
|
||||||
|
denom += __shfl_xor_sync(0xffffffff, denom, 1);
|
||||||
|
|
||||||
|
#pragma unroll
|
||||||
|
for (int i = 0; i < per_thread; i++) {
|
||||||
|
output[widx + 32 * i + size * entry] = elems[i] / denom;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,174 @@
|
|||||||
|
use acyclib::{
|
||||||
|
dag::NodeId,
|
||||||
|
device::{
|
||||||
|
function::{DeviceFunction, MaybeUpdateBatchSize},
|
||||||
|
tensor::Shape,
|
||||||
|
},
|
||||||
|
graph::{
|
||||||
|
builder::{Affine, GraphBuilderNode},
|
||||||
|
ir::{
|
||||||
|
node::AnnotatedNode,
|
||||||
|
operation::{util, GraphIROperationBase, GraphIROperationCompilable},
|
||||||
|
BackendMarker, GraphIR, GraphIRError,
|
||||||
|
},
|
||||||
|
Graph, GraphNodeIdTy,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
use bullet_cuda_backend::{
|
||||||
|
kernel::{Expr, Kernel, KernelArgs, KernelInput},
|
||||||
|
CudaDevice, CudaMarker,
|
||||||
|
};
|
||||||
|
|
||||||
|
use crate::inputs::{MAX_MOVES, NUM_MOVES_INDICES};
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct SelectAffine {
|
||||||
|
weights: AnnotatedNode,
|
||||||
|
biases: AnnotatedNode,
|
||||||
|
input: AnnotatedNode,
|
||||||
|
indices: AnnotatedNode,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl SelectAffine {
|
||||||
|
pub fn new<'a>(
|
||||||
|
affine: Affine<'a, CudaMarker>,
|
||||||
|
input: GraphBuilderNode<'a, CudaMarker>,
|
||||||
|
indices: GraphBuilderNode<'a, CudaMarker>,
|
||||||
|
) -> Self {
|
||||||
|
Self {
|
||||||
|
weights: affine.weights.reshape(affine.weights.annotated_node().shape.transpose()).annotated_node(),
|
||||||
|
biases: affine.bias.annotated_node(),
|
||||||
|
input: input.annotated_node(),
|
||||||
|
indices: indices.annotated_node(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<B: BackendMarker> GraphIROperationBase<B> for SelectAffine {
|
||||||
|
fn nodes(&self) -> Vec<AnnotatedNode> {
|
||||||
|
vec![self.indices, self.input, self.weights, self.biases]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn output_shape(&self, ir: &GraphIR<B>) -> Result<Shape, GraphIRError> {
|
||||||
|
assert_eq!(self.weights.shape, Shape::new(self.input.shape.rows(), NUM_MOVES_INDICES));
|
||||||
|
assert_eq!(self.biases.shape, Shape::new(NUM_MOVES_INDICES, 1));
|
||||||
|
|
||||||
|
util::check_same_batching(ir, &[&self.indices, &self.input])?;
|
||||||
|
util::check_dense_eq(ir, &self.input, true)?;
|
||||||
|
util::check_dense_eq(ir, &self.indices, false)?;
|
||||||
|
util::check_dense_eq(ir, &self.weights, true)?;
|
||||||
|
util::check_dense_eq(ir, &self.biases, true)?;
|
||||||
|
util::check_not_batched(ir, &self.weights)?;
|
||||||
|
util::check_not_batched(ir, &self.biases)?;
|
||||||
|
|
||||||
|
Ok(Shape::new(MAX_MOVES, 1))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl GraphIROperationCompilable<CudaMarker> for SelectAffine {
|
||||||
|
fn forward_pass(&self, graph: &Graph<CudaDevice>, output_node: NodeId) -> DeviceFunction<CudaDevice> {
|
||||||
|
let input = graph.get_ref(self.input.idx, GraphNodeIdTy::Values);
|
||||||
|
let indices = graph.get_ref(self.indices.idx, GraphNodeIdTy::Values);
|
||||||
|
let weights = graph.get_ref(self.weights.idx, GraphNodeIdTy::Values);
|
||||||
|
let biases = graph.get_ref(self.biases.idx, GraphNodeIdTy::Values);
|
||||||
|
let output = graph.get_ref(output_node, GraphNodeIdTy::Values);
|
||||||
|
|
||||||
|
let mut func = DeviceFunction::default();
|
||||||
|
|
||||||
|
func.push(MaybeUpdateBatchSize { input: input.clone(), output: output.clone() });
|
||||||
|
|
||||||
|
let single_size = input.single_size();
|
||||||
|
let batch_size = Expr::Var;
|
||||||
|
let threads = (single_size / 4).min(512) as i32;
|
||||||
|
let grid_dim = [Expr::Const(64), batch_size, Expr::Const(1)];
|
||||||
|
let block_dim = [threads, 1, 1].map(Expr::Const);
|
||||||
|
let shared_mem_bytes = Expr::Const(4 * threads);
|
||||||
|
|
||||||
|
assert!((threads as u32).is_power_of_two(), "hl size must be a power of 2");
|
||||||
|
assert_eq!(MAX_MOVES, 64);
|
||||||
|
|
||||||
|
let layout = None;
|
||||||
|
let mutable = false;
|
||||||
|
|
||||||
|
let inputs = vec![
|
||||||
|
KernelInput::Slice { slice: weights, layout, mutable, batched: false, shape: self.weights.shape },
|
||||||
|
KernelInput::Slice { slice: biases, layout, mutable, batched: false, shape: self.biases.shape },
|
||||||
|
KernelInput::Slice { slice: input, layout, mutable, batched: true, shape: self.input.shape },
|
||||||
|
KernelInput::Slice { slice: indices, layout: Some(64), mutable, batched: true, shape: self.indices.shape },
|
||||||
|
KernelInput::Slice { slice: output, layout, mutable: true, batched: true, shape: Shape::new(MAX_MOVES, 1) },
|
||||||
|
];
|
||||||
|
|
||||||
|
let args = KernelArgs { inputs, block_dim, grid_dim, shared_mem_bytes };
|
||||||
|
|
||||||
|
let code = include_str!("select_affine/fwd.cu")
|
||||||
|
.lines()
|
||||||
|
.skip(5)
|
||||||
|
.map(|x| format!("{x}\n"))
|
||||||
|
.collect::<String>()
|
||||||
|
.replace("THREADS", &threads.to_string())
|
||||||
|
.replace("IN_SIZE", &single_size.to_string());
|
||||||
|
|
||||||
|
let kernel = unsafe { Kernel::new("SelectAffineFwd".to_string(), code, args) };
|
||||||
|
|
||||||
|
func.push(kernel.unwrap());
|
||||||
|
|
||||||
|
func
|
||||||
|
}
|
||||||
|
|
||||||
|
fn backward_pass(&self, graph: &Graph<CudaDevice>, output_node: NodeId) -> DeviceFunction<CudaDevice> {
|
||||||
|
let input = graph.get_ref(self.input.idx, GraphNodeIdTy::Values);
|
||||||
|
let indices = graph.get_ref(self.indices.idx, GraphNodeIdTy::Values);
|
||||||
|
let weights = graph.get_ref(self.weights.idx, GraphNodeIdTy::Values);
|
||||||
|
let input_grad = graph.get_ref(self.input.idx, GraphNodeIdTy::Gradients);
|
||||||
|
let weights_grad = graph.get_ref(self.weights.idx, GraphNodeIdTy::Gradients);
|
||||||
|
let biases_grad = graph.get_ref(self.biases.idx, GraphNodeIdTy::Gradients);
|
||||||
|
let output_grad = graph.get_ref(output_node, GraphNodeIdTy::Gradients);
|
||||||
|
|
||||||
|
let mut func = DeviceFunction::default();
|
||||||
|
|
||||||
|
func.push(MaybeUpdateBatchSize { input: output_grad.clone(), output: input_grad.clone() });
|
||||||
|
|
||||||
|
assert_eq!(MAX_MOVES, 64);
|
||||||
|
|
||||||
|
let single_size = input.single_size();
|
||||||
|
let batch_size = Expr::Var;
|
||||||
|
let threads = (single_size / 4).min(1024) as i32;
|
||||||
|
let grid_dim = [Expr::Const(64), batch_size, Expr::Const(1)];
|
||||||
|
let block_dim = [threads, 1, 1].map(Expr::Const);
|
||||||
|
let shared_mem_bytes = Expr::Const(16 * threads);
|
||||||
|
|
||||||
|
let layout = None;
|
||||||
|
let mutable = false;
|
||||||
|
|
||||||
|
let inputs = vec![
|
||||||
|
KernelInput::Slice { slice: weights, layout, mutable, batched: false, shape: self.weights.shape },
|
||||||
|
KernelInput::Slice { slice: input, layout, mutable, batched: true, shape: self.input.shape },
|
||||||
|
KernelInput::Slice { slice: indices, layout: Some(64), mutable, batched: true, shape: self.indices.shape },
|
||||||
|
KernelInput::Slice { slice: output_grad, layout, mutable, batched: true, shape: Shape::new(MAX_MOVES, 1) },
|
||||||
|
KernelInput::Slice { slice: input_grad, layout, mutable: true, batched: true, shape: self.input.shape },
|
||||||
|
KernelInput::Slice {
|
||||||
|
slice: weights_grad,
|
||||||
|
layout,
|
||||||
|
mutable: true,
|
||||||
|
batched: false,
|
||||||
|
shape: self.weights.shape,
|
||||||
|
},
|
||||||
|
KernelInput::Slice { slice: biases_grad, layout, mutable: true, batched: false, shape: self.biases.shape },
|
||||||
|
];
|
||||||
|
|
||||||
|
let args = KernelArgs { inputs, grid_dim, block_dim, shared_mem_bytes };
|
||||||
|
|
||||||
|
let code = include_str!("select_affine/bwd.cu")
|
||||||
|
.lines()
|
||||||
|
.skip(4)
|
||||||
|
.map(|x| format!("{x}\n"))
|
||||||
|
.collect::<String>()
|
||||||
|
.replace("IN_SIZE", &single_size.to_string());
|
||||||
|
|
||||||
|
let kernel = unsafe { Kernel::new("SelectAffineBwd".to_string(), code, args) };
|
||||||
|
|
||||||
|
func.push(kernel.unwrap());
|
||||||
|
|
||||||
|
func
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,67 @@
|
|||||||
|
#ifndef STUFF
|
||||||
|
#define IN_SIZE 1024
|
||||||
|
#endif
|
||||||
|
|
||||||
|
constexpr int in_size = IN_SIZE;
|
||||||
|
|
||||||
|
extern "C" __global__ void kernel(
|
||||||
|
const float* weights,
|
||||||
|
const float* input,
|
||||||
|
const int* moves,
|
||||||
|
const float* output_grad,
|
||||||
|
float* input_grad,
|
||||||
|
float* weights_grad,
|
||||||
|
float* biases_grad
|
||||||
|
) {
|
||||||
|
extern __shared__ float sdata[];
|
||||||
|
|
||||||
|
const int batch_size = gridDim.y;
|
||||||
|
const int loc_in_batch = blockIdx.y;
|
||||||
|
const int loc_in_moves = blockIdx.x;
|
||||||
|
const int tid = threadIdx.x;
|
||||||
|
const int locmb = loc_in_batch * 64 + loc_in_moves;
|
||||||
|
const int move = moves[locmb];
|
||||||
|
|
||||||
|
if (move != -1)
|
||||||
|
{
|
||||||
|
const float grd = output_grad[locmb];
|
||||||
|
|
||||||
|
const float4* tW = reinterpret_cast<const float4*>(weights + in_size * move);
|
||||||
|
const float4* tI = reinterpret_cast<const float4*>(input + in_size * loc_in_batch);
|
||||||
|
|
||||||
|
if (tid == 0) atomicAdd(biases_grad + move, grd);
|
||||||
|
|
||||||
|
for (int idx = tid; idx < in_size / 4; idx += blockDim.x)
|
||||||
|
{
|
||||||
|
const int section = 4 * blockDim.x * (idx / blockDim.x) + tid;
|
||||||
|
const float4 ti = tI[idx];
|
||||||
|
const float4 tw = tW[idx];
|
||||||
|
|
||||||
|
sdata[4 * tid ] = ti.x;
|
||||||
|
sdata[4 * tid + 1] = ti.y;
|
||||||
|
sdata[4 * tid + 2] = ti.z;
|
||||||
|
sdata[4 * tid + 3] = ti.w;
|
||||||
|
__syncthreads();
|
||||||
|
|
||||||
|
float* tWg = weights_grad + in_size * move + section;
|
||||||
|
atomicAdd(tWg , grd * sdata[tid ]);
|
||||||
|
atomicAdd(tWg + blockDim.x , grd * sdata[tid + blockDim.x ]);
|
||||||
|
atomicAdd(tWg + blockDim.x * 2, grd * sdata[tid + blockDim.x * 2]);
|
||||||
|
atomicAdd(tWg + blockDim.x * 3, grd * sdata[tid + blockDim.x * 3]);
|
||||||
|
__syncthreads();
|
||||||
|
|
||||||
|
sdata[4 * tid ] = tw.x;
|
||||||
|
sdata[4 * tid + 1] = tw.y;
|
||||||
|
sdata[4 * tid + 2] = tw.z;
|
||||||
|
sdata[4 * tid + 3] = tw.w;
|
||||||
|
__syncthreads();
|
||||||
|
|
||||||
|
float* tIg = input_grad + in_size * loc_in_batch + section;
|
||||||
|
atomicAdd(tIg , grd * sdata[tid ]);
|
||||||
|
atomicAdd(tIg + blockDim.x , grd * sdata[tid + blockDim.x ]);
|
||||||
|
atomicAdd(tIg + blockDim.x * 2, grd * sdata[tid + blockDim.x * 2]);
|
||||||
|
atomicAdd(tIg + blockDim.x * 3, grd * sdata[tid + blockDim.x * 3]);
|
||||||
|
__syncthreads();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
#ifndef STUFF
|
||||||
|
#define THREADS 512
|
||||||
|
#define IN_SIZE 1024
|
||||||
|
#endif
|
||||||
|
|
||||||
|
constexpr int threads = THREADS;
|
||||||
|
constexpr int in_size = IN_SIZE;
|
||||||
|
|
||||||
|
extern "C" __global__ void kernel(
|
||||||
|
const float* weights,
|
||||||
|
const float* biases,
|
||||||
|
const float* input,
|
||||||
|
const int* moves,
|
||||||
|
float* output
|
||||||
|
) {
|
||||||
|
extern __shared__ float sdata[];
|
||||||
|
|
||||||
|
const int batch_size = gridDim.y;
|
||||||
|
const int loc_in_batch = blockIdx.y;
|
||||||
|
const int loc_in_moves = blockIdx.x;
|
||||||
|
const int tid = threadIdx.x;
|
||||||
|
const int locmb = loc_in_batch * 64 + loc_in_moves;
|
||||||
|
const int move = moves[locmb];
|
||||||
|
|
||||||
|
const float4* tW = reinterpret_cast<const float4*>(weights + in_size * move);
|
||||||
|
const float4* tI = reinterpret_cast<const float4*>(input + in_size * loc_in_batch);
|
||||||
|
|
||||||
|
if (move != -1)
|
||||||
|
{
|
||||||
|
float local = 0.0F;
|
||||||
|
|
||||||
|
#pragma unroll
|
||||||
|
for (int idx = tid; idx < in_size / 4; idx += threads)
|
||||||
|
{
|
||||||
|
const float4 tw = tW[idx];
|
||||||
|
const float4 ti = tI[idx];
|
||||||
|
local += tw.x * ti.x + tw.y * ti.y + tw.z * ti.z + tw.w * ti.w;
|
||||||
|
}
|
||||||
|
|
||||||
|
sdata[tid] = local;
|
||||||
|
__syncthreads();
|
||||||
|
|
||||||
|
if constexpr (threads >= 1024) { if (tid < 512) sdata[tid] += sdata[tid + 512]; __syncthreads(); }
|
||||||
|
if constexpr (threads >= 512) { if (tid < 256) sdata[tid] += sdata[tid + 256]; __syncthreads(); }
|
||||||
|
if constexpr (threads >= 256) { if (tid < 128) sdata[tid] += sdata[tid + 128]; __syncthreads(); }
|
||||||
|
if constexpr (threads >= 128) { if (tid < 64) sdata[tid] += sdata[tid + 64]; __syncthreads(); }
|
||||||
|
|
||||||
|
if (tid < 32)
|
||||||
|
{
|
||||||
|
float partial = sdata[tid];
|
||||||
|
if constexpr (threads >= 64) { partial += sdata[tid + 32]; }
|
||||||
|
partial += __shfl_down_sync(0xffffffff, partial, 16);
|
||||||
|
partial += __shfl_down_sync(0xffffffff, partial, 8);
|
||||||
|
partial += __shfl_down_sync(0xffffffff, partial, 4);
|
||||||
|
partial += __shfl_down_sync(0xffffffff, partial, 2);
|
||||||
|
partial += __shfl_down_sync(0xffffffff, partial, 1);
|
||||||
|
|
||||||
|
if (tid == 0)
|
||||||
|
{
|
||||||
|
output[locmb] = partial + biases[move];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (tid == 0)
|
||||||
|
{
|
||||||
|
output[locmb] = -10000.0F;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Trains Rigby's policy network. Run from anywhere:
|
||||||
|
# powershell -ExecutionPolicy Bypass -File C:\Users\rektd\repos\Rigby\train\policy\train.ps1
|
||||||
|
# Extra arguments go to the trainer, e.g.:
|
||||||
|
# ... train.ps1 --superbatches 60 --hidden 4096 --id rigby-policy-v2
|
||||||
|
# ... train.ps1 --check checkpoints\rigby-policy-40
|
||||||
|
# Data: ..\data\lc0\policy.binpack, made by fetch.ps1 (or by lc02monty + interleave).
|
||||||
|
param([Parameter(ValueFromRemainingArguments = $true)] [string[]] $TrainerArgs)
|
||||||
|
|
||||||
|
# Native tools report through exit codes; 'Stop' would turn cargo's progress
|
||||||
|
# output on stderr into errors under Windows PowerShell.
|
||||||
|
$ErrorActionPreference = 'Continue'
|
||||||
|
Set-Location $PSScriptRoot
|
||||||
|
|
||||||
|
. .\env.ps1
|
||||||
|
|
||||||
|
if (-not ($TrainerArgs -contains '--data') -and -not ($TrainerArgs -contains '--check') -and
|
||||||
|
-not (Test-Path '..\data\lc0\policy.binpack')) {
|
||||||
|
throw 'No training data: ..\data\lc0\policy.binpack is missing (run fetch.ps1)'
|
||||||
|
}
|
||||||
|
|
||||||
|
cargo build --release --bin rigby-policy
|
||||||
|
if ($LASTEXITCODE -ne 0) { throw 'build failed' }
|
||||||
|
|
||||||
|
& .\target\release\rigby-policy.exe @TrainerArgs
|
||||||
|
exit $LASTEXITCODE
|
||||||
Reference in new issue
Block a user