# Z2I_rs **Repository Path**: Joker2770/Z2I_rs ## Basic Information - **Project Name**: Z2I_rs - **Description**: No description available - **Primary Language**: Rust - **License**: MIT - **Default Branch**: main - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2026-08-10 - **Last Updated**: 2026-11-16 ## Categories & Tags **Categories**: Uncategorized **Tags**: onnxruntime, gomocup, gomoku, Renju, alphazero ## README # Z2I_rs [![Release](https://github.com/Joker2770/Z2I_rs/actions/workflows/release.yml/badge.svg)](https://github.com/Joker2770/Z2I_rs/actions/workflows/release.yml) [![Rust](https://github.com/Joker2770/Z2I_rs/actions/workflows/rust.yml/badge.svg)](https://github.com/Joker2770/Z2I_rs/actions/workflows/rust.yml) [![Snap](https://github.com/Joker2770/Z2I_rs/actions/workflows/snap.yml/badge.svg)](https://github.com/Joker2770/Z2I_rs/actions/workflows/snap.yml) [![z2i-rs](https://snapcraft.io/z2i-rs/badge.svg)](https://snapcraft.io/z2i-rs) A Rust rewrite of Z2I. Z2I is a Gomoku/Renju AI based on a neural network and Monte Carlo Tree Search (MCTS); this project integrates board rules, MCTS, ONNX Runtime inference and the Gomocup/Piskvork engine protocol into a single Rust console program. This project works well with Gomoku managers such as [qpiskvork](https://github.com/Joker2770/qpiskvork): the manager starts the engine, sends game commands and manages games, while `pbrain-Z2I_rs` computes and returns moves through standard input/output. Related projects: - [Joker2770/Z2I](https://github.com/Joker2770/Z2I): the original Z2I project. - [Joker2770/qpiskvork](https://github.com/Joker2770/qpiskvork): Gomoku manager for human-vs-engine play, engine-vs-engine matches and game management. ## Features - MCTS search combined with ONNX neural network policy and value functions. - ONNX Runtime inference with batching and a background inference worker. - CPU build available by default; CUDA as an optional Cargo feature. - Tic-Tac-Toe mode is available through the `tic-tac-toe` Cargo feature. - Supports FreeStyle, Standard, Renju, Caro and Standard+Caro rule flags. - Implements the Gomocup/Piskvork-style console protocol: `START`, `BEGIN`, `TURN`, `BOARD`, `INFO`, `ABOUT`, `END`. - Model path and MCTS simulation count configurable via `config.toml`. - Includes programs for self-play data generation, model evaluation and evaluation against a random MCTS opponent. ## Building Requires the Rust stable toolchain and Cargo. ### CPU CPU is the default build: ```bash cargo build --release --bin pbrain-Z2I_rs ``` ### CUDA Build with CUDA provider support: ```bash cargo build --release --features cuda --bin pbrain-Z2I_rs ``` CUDA builds also require the host to have CUDA and related runtime libraries matching the ONNX Runtime/CUDA provider. Hosts without a GPU should use the default CPU build. ### Tic-Tac-Toe Build with the 3x3 board and three-in-a-row defaults: ```bash cargo build --release --features tic-tac-toe --bin pbrain-Z2I_rs ``` The same feature must be used for `train_and_eval` and `ort_train` so that self-play, evaluation and training tensors use the matching `3x3`/`9` shapes. The ONNX model must also be exported for a 3x3 board. ## Model & configuration The program searches for `config.toml` in the following order and uses the first one found: 1. User config dir: Linux `$XDG_CONFIG_HOME/Z2I_rs/` (falling back to `~/.config/Z2I_rs/` when unset), macOS `~/Library/Application Support/Z2I_rs/`, Windows `%APPDATA%\Z2I_rs\`; 2. current working directory; 3. directory of the executable. When none exists, the default model path and MCTS parameters in the source are used. For configs placed in the user directory it is recommended to write the model path as absolute (relative paths are still resolved against the current working dir / executable dir). Example: ```toml [model] default_model = "models/free-style_15x15_889.onnx" free_style_model = "models/free-style_15x15_889.onnx" renju_model = "models/renju_15x15_592.onnx" standard_model = "models/standard_15x15_535.onnx" caro_model = "models/caro_15x15_532.onnx" standard_caro_model = "models/standard_caro_15x15_533.onnx" [MCTS] # Total number of MCTS simulations for self-play and evaluation. # For protocol games, this is the upper bound when time permits. num_mct_sims = 500 # Number of simulations submitted and evaluated as one inference batch. # Larger values can improve throughput but increase latency and memory use. num_sim_per_batch = 8 # Print periodic search information while thinking. open_mind = true # Run background MCTS batches while waiting for the opponent. enable_ponder = true # Minimum remaining time (milliseconds) before starting a full batch. # Tune for the target machine and model; increase it on slower systems. time_reserve_ms = 1800 # Minimum remaining time (milliseconds) before starting one final simulation. # Increase it if a single simulation is slow or the system is heavily loaded. single_sim_reserve_ms = 400 # Time kept for applying and reporting the selected move (milliseconds). final_move_reserve_ms = 100 [ONNXRUNTIME] # Number of intra-op ONNX Runtime threads used for each inference session. num_intra_thread = 4 ``` Model files must be placed where the config specifies. The default build expects `4x15x15` input tensors and the `tic-tac-toe` build expects `4x3x3`; the ONNX model must be exported for the selected board size. The four channels are current player's stones, opponent's stones, last-move marker, and a constant side-to-move color plane (+1 Black / -1 White), respectively. ### Experimental Transformer training The Python self-play trainer can train an experimental conv-stem Transformer while keeping the existing four-channel input and `P`/`V` ONNX interface. In `train/common.py`, set `architecture` to `'transformer'`; the default remains `'cnn'`. The initial Transformer is deliberately small (width 64, two attention blocks, four heads) and uses the existing 8-way board-symmetry augmentation. Treat Transformer weights as a separate lineage. Use a dedicated build directory inside the repository (so `train_loop.sh` can find `../train`), and keep its weights, self-play data, `current_and_best_weight.txt`, and Rust `train_and_eval` binary separate from the CNN run. Copy replay data into this directory rather than symlinking it: the learner moves consumed files between data folders. For a random seed, set `BUILD_DIR` to this directory, create its weights folder with `mkdir -p "$BUILD_DIR/weights"`, and run `python3 train/learner.py prepare` before self-play. CNN checkpoints and optimizer states cannot be resumed as Transformer checkpoints. To initialize a Transformer from an existing CNN, use `train/convert_model.py --target-architecture transformer`; by default it fits the new model to the rule-matched MCTS policy/value labels in the replay files (`--target-source teacher` instead fits the CNN's raw predictions). The converter refuses to overwrite existing destination files. For the converted seed, pass `--dst "$BUILD_DIR/weights/"` with an unused numeric ID (such as `1206`), set that work directory's `current_and_best_weight.txt` to ` `, and set `architecture` to `'transformer'` before running `train_loop.sh` with that directory as `WORK_DIR`. This makes learner load the seed at that ID, train it, and save the next numeric ID; the Rust evaluator uses the matching `.onnx` file. Keep the CNN lineage untouched and restore its Python architecture setting before resuming CNN training. The converter's structural weight-mapping mode remains CNN-only. The distillation log prints `ENTROPY`, `TGT_ENTROPY` and `ACC` next to the losses, so the remaining policy error is readable: `p - TGT_ENTROPY` is the KL still left against the target, and an `ENTROPY` well above `TGT_ENTROPY` means the converted model is still flatter than its labels (more distillation steps, not fewer, are needed). The deprecated `ort_train` artifact pipeline also rejects Transformer mode rather than silently producing a training graph with frozen attention parameters. Before comparing playing strength, run `python3 -m unittest discover -s train -p 'test_*.py'` to validate model training and ONNX CPU export. Measure both fixed-simulation and fixed-time match results; attention may improve per-evaluation quality while reducing search throughput. ### Provider selection Provider initialization is currently controlled by Cargo features: CPU by default; with a CUDA build you can enable the CUDA provider in `src/ortcommon.rs`. For CPU-only hosts, simply use the build without `--features cuda`. ## Using with qpiskvork When `qpiskvork` acts as the manager, configure the built engine as: ```text pbrain-Z2I_rs ``` The program is a console process: it receives commands on stdin and writes responses to stdout. Use absolute paths for the engine and model files, since the manager may change the engine's working directory. Example launch: ```bash ./target/release/pbrain-Z2I_rs ``` Manual protocol test: ```text START 15 BEGIN TURN 7,7 END ``` Normally `START` replies `OK`, and `BEGIN`/`TURN` reply a move coordinate in `x,y` format. Commands that ask for a move but cannot be served are answered with an `ERROR ` line on stdout, so a manager waiting for a reply never hangs. Besides responses, stdout can carry `MESSAGE`/`ERROR`/`DEBUG` lines that are not tied to a request; a manager should skip lines it does not understand. ## Supported protocol commands | Command | Meaning | | --- | --- | | `START size` | Create a board of the given size and initialize the engine. | | `BEGIN` | Request the first move when the AI plays first. | | `TURN x,y` | Inform the opponent's move and request the AI's move. | | `BOARD` | Start receiving the full board; after `DONE`, request the AI's move. | | `INFO rule value` | Set the rule flag (bit 1 = exactly-five, bit 2 = continuous game, bit 4 = Renju, bit 8 = Caro). | | `INFO timeout_turn ms` | Per-move time limit; the engine stops searching once the deadline is reached. | | `INFO time_left ms` | Remaining match time announced by the manager; it caps the move as well and is authoritative for the move that follows it. | | `ABOUT` | Return the engine name and version. | | `END` | End the process. | Protocol details are in [Gomoku AI protocol.html](Gomoku%20AI%20protocol.html). The protocol requires the engine to flush stdout promptly; this project flushes output after processing a command. ## Rule flags `INFO rule value` uses bitflag values: | Rule | Value | | --- | ---: | | FreeStyle | `0` | | Standard | `1` | | Renju | `4` | | Caro | `8` | For example: ```text INFO rule 4 ``` selects the Renju rule. Rule flag combinations are parsed by the Rust side. ## Continuous game (self-play, `INFO rule` bit 2) `INFO rule` bit 2 puts the engine into a *continuous game*: it plays both colors itself, without an opponent, and reports every move to the manager on stdout. This suits custom managers and board viewers that consume a plain coordinate stream. ```text INFO rule 2 START 15 BEGIN ``` Behavior: - `INFO rule 2` enables the mode; the other bits still select the win rule, so `INFO rule 2` alone keeps FreeStyle, and `INFO rule 10` selects Caro *and* continuous game. An `INFO rule` value without bit 2 turns the mode off again. - `BEGIN` opens the move stream; the engine replies with the first coordinate and then keeps playing both colors until the game is over. While the stream runs, each reply is one `x,y` line on stdout, and `MESSAGE continuous game finished` is written to stdout when the game ends. - After the game is over the engine waits. A new `START` starts a new game and the stream resumes without another `BEGIN`; a `BEGIN` sent while no continuous game is in progress is refused with `ERROR cannot begin: no continuous game in progress` on stdout. - `TURN` is ignored during the mode (the engine has no opponent), and pondering is disabled because the engine is always the side to move. The refusal is reported as `ERROR TURN ignored during continuous game` on stdout, so a manager that sent `TURN` gets an answer instead of waiting forever. - Because no manager refreshes the clock per move, the engine deducts its own thinking time from the last `INFO time_left` value; `INFO timeout_turn` still caps each move. An `INFO time_left` announcement received before a move is authoritative and skips that deduction for that move, so a manager that refreshes the clock before every move and one that never refreshes it both get correct accounting. - Announcements are handled in command order, so a manager that reacts to a reported move reaches the engine while the *next* move is already being searched: the update applies from the move after that one. The engine never waits for an announcement, and the manager's value always replaces the locally deducted clock. - In `TURN`-driven mode the engine never deducts locally: the `INFO time_left` a manager sends before each move is used as-is, so every move gets the announced budget. - stdout carries everything a manager has to react to: the move coordinates, `OK` for a successful `START`, `ERROR ` when a command that expects a move cannot be served (`START` with an unsupported size, a `BEGIN` that cannot open the game, an unplayable `TURN` or `BOARD` position, a `TURN` ignored during a continuous game), `MESSAGE continuous game finished` when the self-play stream reaches the end of the game, `ERROR continuous game stopped` when the engine cannot continue it, and optional `DEBUG thinking ...` lines when `open_mind` is enabled in the configuration. stderr carries only diagnostics such as the configuration and model loading messages. Note that spontaneous multi-line output is outside the strict request/response pattern of the piskvork protocol, so a stock manager such as qpiskvork will lose sync. Use this mode with a manager built for it. An `INFO rule` value carrying bit 2 switches the mode on immediately, even in the middle of an ordinary game that already has stones on the board. Such a manager then gets `ERROR TURN ignored during continuous game` for the very next `TURN` instead of a move. Send `INFO rule` without bit 2 (for example `INFO rule 1`) to hand the game back to `TURN` control; the win rule itself still changes only from the next `START`. ## Training & evaluation Training/evaluation uses the separate `train_and_eval` binary: ```bash cargo run --release --bin train_and_eval -- prepare cargo run --release --bin train_and_eval -- generate 0 cargo run --release --bin train_and_eval -- eval_with_winner 10 cargo run --release --bin train_and_eval -- eval_with_random 10 ``` Command descriptions: - `prepare`: create `data/`, `weights/`, the weight state file and a default `openings.txt`. - `generate `: load the current weight and generate self-play training data. - `eval_with_winner `: evaluate the current weight against the best weight. - `eval_with_random `: evaluate the current weight against a random MCTS opponent without a neural network. - `verify_weight ...`: run the weight probe on `weights/.onnx` for each id and exit 1 if any fails (2 if one could not be run at all). A single id prints the full breakdown; a sweep prints one headline per weight, so a sharpness trend across a lineage is one command: `train_and_eval verify_weight 1229 1233 1237 1239`. ### Weight probe (`verify_weight`) A destroyed weight is not a rare accident: a training round on corrupt targets, a structure conversion whose distillation went wrong, or a stale ONNX companion file all produce a model that loads and plays while being no better than a random policy. Such a model loses every evaluation game, which is expensive to discover and easy to mistake for a real regression. The probe asks a weight three questions with **one forward pass per position** (about a second in total, no search): ``` $ train_and_eval verify_weight 1205 weight probe: PASS (3.1s, policy sharpness 0.772) outputs ok 6 position(s), |v| max 1.000 win in one ok 3/3 solved: horizontal gap p=1.000, vertical gap p=0.998, diagonal gap p=0.999 value (win in one) ok v=+1.000, +1.000, +1.000 block the four ok top1 156 p=0.833 (advisory) value (winning) ok v=+1.000 value (losing) ok v=-1.000 colour plane ok flipping ch3 shifts value by 0.000 and policy top-1 by 0.000 -- unused (advisory) per-position answer: win in one (horizontal gap) top1 111 p=1.000 v=+1.000 win in one (vertical gap) top1 97 p=0.998 v=+1.000 win in one (diagonal gap) top1 128 p=0.999 v=+1.000 must block the four top1 156 p=0.833 v=-1.000 value: mover wins top1 108 p=0.591 v=+1.000 value: mover loses top1 157 p=0.210 v=-1.000 ``` - **win in one** (3 shapes): the side to move has exactly one immediate five; the raw policy top-1 must be it. A uniform policy answers index 0 everywhere and solves none. Tactics are judged in bulk -- one miss out of three is tolerated, because the raw policy sees the shape with no search to help it. - **value (win in one)**: the *value* of those same shapes is judged on every one of them, and unlike the policy it has no tolerance: each probe is a decided position (the mover has an immediate five), so a value that comes back negative there is a sign error the search cannot repair. This is the on-distribution check for a value head that reads the side to move off the redundant colour plane: measured on a FreeStyle candidate (2026-09-17) the policy still solved 2/3 shapes and both value probes kept their signs, while the diagonal win in one evaluated -0.802 -- a collapsed head still reported that candidate as `bounded use` (see below), this line is what rejects it. - **block the four**: the opponent threatens five and the block is the only move that does not lose at once. Advisory only -- a policy preferring a counter-threat is weak, not broken, so this never rejects a candidate on its own. - **value signs**: a won position must evaluate positive and a lost one negative, and decisively so (|v| >= 0.5), which catches a flat or inverted value head. - **colour plane** (advisory): every probe is also run with channel 3 negated. That channel carries the absolute side-to-move colour, which on every reachable position is already a function of the two stone planes -- this engine never passes (a forbidden Black move ends the game rather than skipping the turn), so Black to move implies equal stone counts and White to move implies Black is one stone ahead. The plane is therefore informationally redundant, Renju included, and this line reports whether the network leans on it anyway, naming the probe behind the number (`1.799 (win in one (diagonal gap): -0.802 -> +0.997)`). A shift at or above `COLOUR_PLANE_LEAN_VALUE_SHIFT = 1.5` is printed as `FAIL ... (advisory)` but never rejected on its own, because the flipped input is one the engine can never produce: it contradicts the stone parity, so a value function of the perspective-normalised stone planes is free to weight the redundant plane however it likes and still be exactly right on every position the search asks about (the reference FreeStyle weight measures `color_scale == 0` with a colour-input column of ~5e-5, i.e. it *learned* to ignore the plane -- that is a valid solution, not the required one). Its resolution is limited in the other direction as well: the shift is read *after* the value head's `tanh`, so a decisive weight reports ~0.0 no matter how hard it leans on the plane -- a control weight built with a 3.0 weight on the colour input reports 0.296, while a value head that answers the plane *alone* (constant value, no board dependence) reports 1.049. That ordering is backwards, which is why the value criteria are the gate (measured on that collapsed control: `value (win in one)`, `value (winning)` and `value (losing)` all FAIL) and this line is a pointer to the weight to look at first when a value goes wrong where the board signal is weak. The 2026-09-13 Renju lineage (1.999, with v=+0.998 on a won position and v=+0.060 on a lost one) is rejected by `value (losing)` for the same reason. - **per-position answer**: the six raw answers (top-1 index, its probability and the value) behind the aggregate criteria. A value that is wrong on one shape and a value that is the same everywhere are different bugs with the same headline, and this block is what tells them apart; it is also what a rejected candidate archives in `eval_result.log`. - **policy sharpness** (the number in the headline) is the mean top-1 probability over the probes. It is the one figure that separates "weak" from "destroyed": a destroyed weight returns the uniform 1/225, while a merely weaker weight keeps its tactics with visibly lower confidence (a sharp model answers the block probe near 0.8, a diffuse one near 0.2). The per-shape probabilities are always printed, so a worse candidate can be compared to best instead of being guessed at. - Every probe position is parity-correct (`b == w` on Black's turn, `b == w + 1` on White's turn) with a harmless Black stone played last, and always White to move: White has no forbidden moves under any supported rule, so the expected move is rule-agnostic. `eval_with_winner` runs the probe on the candidate automatically and **rejects the candidate before playing any games** when it fails; it also probes best and prints its headline every round, plus the sharpness ratio, so a candidate that is far flatter than best is visible immediately: ``` policy sharpness: candidate 0.239 vs best 0.805 (ratio 0.30) <- much flatter than best: check the learner's replay window ``` Set `EVAL_SKIP_VERIFY=1` to bypass the gate, e.g. to study a known-bad weight or to time an evaluation. `generate` runs the same check on best first: a best weight that cannot run produces no data at all, and refusing early beats failing later inside the learner with a confusing "no valid training samples". A best weight that fails the probe deadlocks the loop rather than merely slowing it down: `generate` refuses to produce data from it, every candidate trained from it inherits the break, and the gate rejects each of those candidates without playing a game -- so rounds pass with no progress at all. The fingerprint is the counter in `current_and_best_weight.txt` drifting far above best, because a healthy loop only ever writes `N N` or `N+1 N` there (a rejection collapses current back to best, a promotion collapses both to the candidate): ``` Current weight: 1124, Best weight: 1107 WARNING: best weight 1107 also fails the probe; every candidate trained from it will look broken ``` Both `generate` and `eval_with_winner` therefore **move best back automatically**: the newest id within `ROLLBACK_SCAN_LIMIT` (default 20, one probe each; `0` disables it) below the failing best that still passes the probe becomes the new best (` `), and the ids in between are retrained from there. When nothing below best is usable, the scan reports one summary line naming every reason (an old 3-channel weight needs a re-export with `train/convert_model.py`, a missing file is just missing, a probed weight is below the bar) and `generate` **exits non-zero**: under the `set -e` of `train_loop.sh` the round ends instead of spinning, because a broken best makes every round identical -- generate refuses, the learner still trains on the stale window from the broken weight, and the candidate comes back worse (measured 2026-09-13: one round turned the value head into a colour-plane collapse of 1.998 whose value probes read v=+0.060 on a lost position, so the value criteria rejected it; 17 rounds burnt on a lineage whose best had a broken value head). Advisory lines do not reject anything by themselves, so the value criteria -- `value (win in one)` and the value signs -- are what has to be watched here. `EVAL_SKIP_VERIFY=1` keeps the loop running if you want to watch it anyway. ``` no healthy weight below 1157, so this lineage needs a fresh seed (see README 'Weight probe'): scanned 20 of the 20 id(s) below 1157: 11 from another input layout (3-channel era: re-export them with train/convert_model.py to use them again); 9 with no weight file STOP: best weight 1157 is unusable and nothing below it is healthy, ... ``` Note that a 128-sim screen is shallow (only 8 inference batches per move), so it punishes a diffuse policy harder than a real game would: a candidate that passes the probe but scores far below best should be re-checked at a higher `EVAL_SIMS` (256 or 384 still costs only seconds per pair) before its weakness is treated as a real regression. ### Colour-paired evaluations Acceptance evaluation always gives Black the first move, so a rule can be colour symmetric and still not be colour symmetric *as a sampled distribution*: the reachable positions are only closed under a colour swap inside the mirror universe where White moves first. `eval_with_winner` therefore starts its games from an opening book and plays every opening **twice with the colours exchanged**: - `openings.txt` in the training work dir holds one opening per line: comma or whitespace separated board indices (`row * board_size + col`), colours alternating Black, White, ... so the count must be even. `#` starts a comment and unusable lines are reported and skipped. - The even ply count is what makes the colour-swapped twin a legal "Black to move" position, so the first-move advantage cancels *inside* a pair and the pair score is a fair strength estimate. A file with no usable opening falls back to the built-in book. - The book is spread over the eight board symmetries, so a small book still yields many distinct pairs. Odd `games` values leave the last game unpaired: it still counts in the win rate but is excluded from the pair statistic. - Each evaluation logs the per-pair scores plus a two-sided exact sign test over the decisive pairs, which is a much sharper statement than the raw win rate over the same number of independent games. Promotion still uses the existing `UPDATE_THRESHOLD` rule on the overall score, so the log reports both. ### Evaluation cost knobs `eval_with_winner` / `eval_with_random` print and log a cost line that separates session creation from actual play, e.g. ``` eval cost: 25 pairs / 50 games, load 0.8s + games 98.4s = 99.2s, 4.0s per pair total / 3.9s per pair of play, 128 sims/move (EVAL_SIMS), 2 worker(s) ``` Use it to budget a session instead of guessing: - **`load` is per-process and does not scale with the game count**, so it dominates short evaluations and disappears in long ones. A large `load` is a cold ONNX Runtime/CUDA start or a heavy weight file (loading the runtime or the weights from a network drive is a common cause) — not an expensive search. `games` is the part that grows with `games`/`EVAL_SIMS`. - **`EVAL_SIMS=`**: pin the simulations per move. Without it the evaluation follows `sims_for_weight`, which grows to `SIMS_CAP` — a late-generation evaluation then costs up to 3x a generation-0 one for the same games. Both sides always get the same value. Note that the MCTS floor is one batch (`DEFAULT_SIM_PER_BATCH_NUM`), so budgets below that batch size all cost the same. - **`EVAL_WORKERS=`** (default 2): play `n` games concurrently. Workers are independent and each owns its own ONNX sessions, so the merged result does not depend on `n` — it is a pure wall-clock lever. Board rendering is disabled when `n > 1` (interleaved boards are unreadable); set `EVAL_WORKERS=1` to keep them. Measure both settings with the cost line before fixing a value. - Evaluating a weight against itself (`current == best`, which happens on a re-run right after a rollback) is skipped instead of burning a round and jittering the shared Elo rating with search noise. `EVAL_ALLOW_SELF_MATCH=1` runs it anyway: a self-match is the cheapest control that the harness is sound, because it must score ~0.5 at any budget. - A failed evaluation (missing or unloadable weight, a weight whose input channels do not match `INPUT_CHANNEL_SIZE`, or a game that could not be played) reports zero games, rejects the candidate and leaves best in place. The failure is contained in the worker, so a bad weight no longer kills the process mid-run. ### Running the loop `train/train_loop.sh` runs generate -> train -> acceptance evaluation in a loop and now carries the recommended defaults, so it is run as-is: ```bash cd train && ./train_loop.sh ``` | variable | default | meaning | |---|---|---| | `WORK_DIR` | `build` | work dir holding the binary, `data*/` and `weights/` | | `NUM_CONTEST` | `50` | evaluation games (even = complete colour-swapped pairs) | | `CHECK_FREQ` | `1` | evaluate every round; `>1` accepts the candidate without playing | | `EVAL_SIMS` | `256` | simulations per move during evaluation | | `EVAL_WORKERS` | `2` | games played concurrently during evaluation | | `REPLAY_INCLUDE_ARCHIVE` | `1` | let a short replay window fall back to `data_archive/` | | `ROLLBACK_SCAN_LIMIT` | `20` | ids the automatic best rollback scans for a healthy checkpoint (`0` off) | | `BATCH_ID` / `STEP` | `0` / `16` | batch id start and per-round step (`STEP` = `NUM_2_SELF_PLAY`) | | `MAX_ITERS` | `1000` | rounds to run | Every value is still overridable from the shell, e.g. `EVAL_SIMS=384 ./train_loop.sh`. A round costs roughly 85s of evaluation play plus ~2s of weight probing at the defaults, on top of the self-play and training time; lower `EVAL_SIMS` (128) to make it cheaper, raise it (384) when a candidate's loss has to be trusted as a real strength gap. Diagnostic switches (`EVAL_SKIP_VERIFY`, `EVAL_ALLOW_SELF_MATCH`) stay off unless set explicitly. Python training scripts are in `train/`; install dependencies with: ```bash python3 -m pip install -r train/requirements.txt ``` ### Replay window The learner trains on the newest `examples_buffer_max_len * games_per_iter` self-play files (default 20 x 16 = 320) taken from `data/` and `data_backup/`. A short window is the failure mode that quietly flattens a policy: the value head still converges while the policy never sharpens, so the candidate loses badly at a low simulation budget without looking broken. The learner therefore prints the window size, the sample count and the step count, and warns when the window is short: ``` replay window: 20 iters x 16 games = 320 files, selected 18 WARNING: the replay window is short by 302 file(s) (18/320). Training will barely move the model... ``` `REPLAY_INCLUDE_ARCHIVE=1` fills a short window from `data_archive/` with the newest archived files. Self-play samples do not depend on the model that generated them, so a work dir that was recreated (or a lineage restarted after an input-layout change) can still train on its archived games instead of starving. The live files keep the head of the window, so recency weighting is preserved. The **rule flag in each file header is filtered before the window is filled**, which is what makes a hot-started work dir behave. On a directory copied from another rule (the `*_lead_by_*` flow) the parent's files are the newest ones, so filling the window first would spend every slot on files `load_samples` then discards, leaving the round to train on only the handful of files it just generated -- a starved window that never trips the short-window warning. Foreign files are excluded from the window and from the `data_archive/` fallback, and archived away after the round, so the directory cleans itself up instead of re-reading them every round. An incomplete file (a `.part` a running self-play process has not renamed yet) is ignored but never moved: ``` replay window: 20 iters x 16 games = 320 files, selected 16 rule check: 304 file(s) carry another rule and were left out of the window (expected 4); they are archived to .../data_archive after this round WARNING: the replay window is short by 304 file(s) (16/320). ... 304 file(s) in data/ + data_backup/ belong to another rule, and a work dir started from another rule needs its own 320 files before the window is full. ``` The training flow needs the Python side to produce initial ONNX weights before the Rust side can run self-play and evaluation with a model. ### Label audit (`train/audit_labels.py`) The learner's worst failures are silent: a window whose games abort (no winner, so every ply is labelled `v = 0`) or whose winner is always the same colour still trains, still lowers the value loss, and only shows up much later as a value head that answers "whose turn is it" -- which the probe then reports as a value that leans on the constant colour plane, and which `value (win in one)` and the value signs reject. This command audits the newest-first window the learner would consume and prints the label statistics that make it visible: ```bash cd train && python3 audit_labels.py --dir ../build --expect-rule 1 ``` - `winner: Black ... White ... none/aborted ...`: games with no winner carry `v = 0` on every ply, so an abort-heavy window teaches the value head "nobody is winning"; - `v by side to move (the ch3-shortcut test)`: the mean label for Black-to-move and White-to-move plies. Saturated opposite means are only reachable when one colour wins nearly every game, which is exactly the label stream the constant colour plane can fit; - `v per ply` and the `contradict` warning: a ply whose sign disagrees with its own game's winner means the `v` stream itself is broken (`play.rs` writes `v = colour * win`); - `pi: mean entropy / top-1 / support`: whether the search targets are sharp enough to teach a policy at all (a nearly uniform `pi` means the simulation count or the seed is the problem, not the data). It also verifies each game's **ending** against the position it was decided from. `play.rs` stores the position *before* the move about to be played at every ply, so the deciding move is not in the file -- but the ending is still pinned down: a positive label at the last stored ply must be a win from that position (some gap-fill completes a line the rule accepts), a negative one means the mover lost on **their own** move, which only Renju allows (Black's forbidden move ends the game with White winning), and neither side may already hold a deciding line before that move. Caro is the one rule where a five can sit on the board without having ended the game: `oxxxxxo`, blocked by an opponent stone at both ends, is not a win (`caro.rs` omits it from `WIN_SHAPES`), so those games are reported as a note rather than as having run past their end. The aggregate label statistics cannot catch this class of error, because they are self-consistent by construction: ``` termination check: 38/40 game(s) end the way their labels say (...) note: 2 game(s) ended with the mover losing on their own move -- Renju's forbidden-move loss data_16_bbbbbbbb: labelled Black win on the last move, but the position before it lets Black complete no winning line ``` ... and on a Caro build, the five that did not end anything is named, line by line: ``` note: 3 game(s) hold a five Caro does not count (the run is blocked by an opponent stone at both ends, `oxxxxxo`), which is why those games played on instead of ending: data_259_25bf9ae7(...): row 1 col 1 (horizontal, 5 in a row) ``` That note is worth reading on a Renju build: a game that ends by Black's forbidden move labels every Black-to-move ply as "losing", so a window dominated by those games teaches a value head "whose turn is it" instead of "who is winning" -- the label-side cause of the colour-plane collapse the probe reports on the weight side. Use `--no-termination-check` to skip the pass. A window smaller than 5 readable games reports the statistics without a verdict, since a single game is always won by one colour. It exits 1 on a degenerate window, so it can gate a run, and `--self-test` round-trips synthetic windows (a learnable one, a single-colour one, an undecided one) without touching the work dir. `--files N` (default 40), `--all` and `--include-archive` select the window exactly like the learner does. ### Renju legality in self-play The playable table `Gomoku` hands to the search only encodes "empty cell" (`load_position` and `execute_move`). Renju's forbidden moves are not in it, so without help the search priors, the Dirichlet noise, the stored target π and the move actually played all disagreed with the `RenjuJudge` that decides the game: a Black move the judge rejects ends the game with White winning, which is the "the mover loses on its own move" ending the label audit notes. A window made of those games labels every Black-to-move ply as losing, so the value head is trained on `v = f(side to move)` and collapses onto the constant colour plane the probe reports (its `colour plane` line names the probe behind the number; the value criteria reject the weight). `Gomoku::refresh_playable_moves` closes that gap by asking the same `RenjuJudge::is_legal` the judge asks and clearing the points it rejects: - it is called before every search and after every move -- in self-play (`play.rs`), in evaluation (`train_and_eval.rs`) and in the protocol engine (`main.rs`), including after the opponent's move so background pondering starts from a correct root; - it only does work when the rule contains Renju **and** Black is to move. White has no forbidden moves and no other rule has any, so FreeStyle, Standard, Caro and Standard+Caro are bit-for-bit unchanged (the playable set the filter sees is then a superset of the explored children, so nothing is dropped); - it costs one `is_legal` pass over the empty points per decision point, not per simulation: the search keeps using the cheap table on its own clones. Each `generate` round now reports what it saw, so a regression cannot hide: ``` Self play: no forbidden-move endings ``` A non-zero `WARNING: N self-play game(s) ended by the mover's own forbidden move ...` means the search and the judge have drifted apart again (or the work dir still holds files written before the fix). Such a game is still written by default, because dropping it hides the signal; `SELFPLAY_DROP_FORBIDDEN=1` drops it instead, which is only useful while a poisoned lineage is still being cleaned -- a window made mostly of those games would then starve rather than train. ### RIF 9.3 (allowed double-threes) RIF's `THREE` is not a geometric shape: it is a row of three stones that can still be made into a *straight four* (an unbroken four with both ends empty). Rule 9.3 therefore allows a Black double-three when at most one of its threes is still extendable, and it gives two separate conditions for "extendable": - **9.3a** -- some extension point makes a straight four **without** an overline or a double-four at that intersection; - **9.3b** -- some extension point makes a straight four **without** being a forbidden double-three itself. This is the recursive half of the rule; `RenjuJudge::A3_EXTENSION_DEPTH` caps how deep it is followed (level 2, measured as the point where the effect stops). The move is forbidden only when **both** counts reach two. Counting the two conditions separately matters: a single "the extension must avoid overline, double-four *and* double-three" test -- the "true three" rule several engines use -- is not the same rule and errs on the permissive side, so the judge does not use it (`double_three_forbidden_by_both_conditions` pins such a position). On random Renju games the exception lifts roughly a fifth of the double-three rejections in dense positions and about a twentieth in the first 40 plies; the evaluation costs nothing measurable, because the 9.3 work sits behind the `sum4 < 2 && sum3 >= 2` gate and only the points that can actually become double-threes pay for it. ### ORT Training (Deprecated) The standalone `ort_train` binary is deprecated and retained for compatibility; avoid using it for new training workflows. It needs ONNX Runtime Training artifacts, not ordinary inference models. The artifact directory must contain: ```text training_model.onnx eval_model.onnx optimizer_model.onnx checkpoint ``` After generating the artifacts, the Rust training entry can read the Rust self-play data in `data/`: ```bash cargo run --features training --bin ort_train -- \ artifacts data weights/1.onnx artifacts/checkpoint.updated 128 1 ``` Argument order: `artifact_dir data_dir output_model checkpoint batch_size epochs`. The default training input names are `board`, `target_p`, `target_v`, matching the Python model; exported inference outputs are `P` and `V`. If the training graph uses other names, pass three more name arguments. Each complete self-play file is expanded with the same eight rotations/flips as the Python learner. Incomplete or corrupted files are skipped. Ordinary `weights/*.onnx` supports inference only and cannot be used directly as ORT Training artifacts. ## Inference & throughput Each MCTS simulation sends its inference request to the background ONNX worker. The worker batches `session.run()` calls once the batch reaches `batch_size` or the short wait window ends, then returns results in FIFO request order through each response channel. Therefore, a larger batch size may improve GPU throughput, but increases the per-request latency and memory usage. The MCTS simulation count is controlled by `num_mct_sims`. ### Session lifetime (`NeuralNetwork` shutdown) Every `NeuralNetwork` owns one ONNX Runtime `Session` on its own `onnx-inference` thread, and it releases that session deterministically when it is dropped: the request channel is closed and the thread is joined, so the worker destroys the `Session` in the thread that created it instead of leaving it to the process to exit around. This is not cosmetic. Each `Session` holds an `Arc`, and ONNX Runtime requires every session to be released while its own globals are still intact — that is why `ort` releases the process-wide environment from a `.fini_array` hook, with the comment that "ONNX Runtime is *very* particular about `ReleaseEnv` being called before any C++ destructors are called". A `Session` still alive when `main` returns makes that teardown run against a live environment and a live provider (a detached worker thread parked in `recv()` leaves exactly that behind). The symptom is an abort *after* the last line of the command: ``` Self play: no forbidden-move endings corrupted double-linked list Aborted (core dumped) ``` Read that message for what it is: `corrupted double-linked list` is printed by glibc's allocator, not by Rust. A Rust bug would have said `thread '...' panicked at ...` first (the release profile sets `panic = "abort"`, which still prints the panic before aborting), and this crate contains no `unsafe` at all — so the heap was damaged by native code, and the only native code in the process is ONNX Runtime (plus the CUDA provider on GPU builds). Joining the worker keeps every session's release inside ORT's supported order and removes the race between one session being torn down and another one starting up or the process exiting. If it still happens, capture the abort's stack from the core dump, since that names the native frame that corrupted the heap: ```bash ulimit -c unlimited gdb -batch -ex bt ./train_and_eval core # or: gdb -batch -ex run -ex bt --args ./train_and_eval generate 247 ``` Frames under `libonnxruntime.so` (or `libcuda`/`libcudnn`) confirm the native side; the fix for that is a matching CUDA-enabled `libonnxruntime.so` for this `ort` build (`--features cuda` needs `ORT_LIB_LOCATION` pointing at it), not a source change here. ## Snap A snap named `z2i-rs` is published on snapcraft.io; the packaging lives in `snap/snapcraft.yaml`. It ships the engine binary only and builds from the GitHub main branch. No weights are bundled — after installing, copy `snap/config.toml` to `~/snap/z2i-rs/current/.config/Z2I_rs/config.toml` and point the model paths at your own ONNX weight. Build locally (requires lxd): ```bash sudo snap install lxd && sudo lxd init --auto snapcraft pack ``` Or build in destructive mode (not recommended for release): ```bash snapcraft pack --destructive-mode ``` ## Development checks ```bash cargo fmt --all cargo check --all-targets cargo test --all-targets # python-side self-checks (stdlib only, no work dir required) python3 train/audit_labels.py --self-test python3 train/learner.py --self-test ``` ## License This project uses the MIT License; see [LICENSE](LICENSE).