diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..a45886c9bf8b5d047a53fb396b4504a285f362d4 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,3 @@ +**/node_modules +**/.next +**/target diff --git a/.gitattributes b/.gitattributes index 580d310c2d211aca166288a207e972ced9bb0100..0bb75f73d568dc6f0e1e0733e94ab58027ddbfbf 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1 +1 @@ -*.safetensors filter=lfs diff=lfs merge=lfs -text +*.onnx filter=lfs diff=lfs merge=lfs -text diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..6eb10aa4400d434a958b112e560878079ca3f104 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,39 @@ +# Hugging Face Docker Space: one process, one port. ct-bot serves the JSON API +# and the static Next.js build together on 7860. +# Build context is the bundle prepare.sh assembles (rust/, frontend/, the model). + +# --- frontend: static export --------------------------------------------------- +FROM node:20-slim AS web +WORKDIR /web +COPY frontend/package.json frontend/package-lock.json ./ +RUN npm ci +COPY frontend/ ./ +# Empty API URL = same origin: the page calls /api/* on the server that served it. +ENV NEXT_OUTPUT=export NEXT_PUBLIC_API_URL="" +RUN npx next build + +# --- engine -------------------------------------------------------------------- +FROM rust:1.92-slim-trixie AS engine +# ort's build script downloads the prebuilt ONNX Runtime over TLS; g++ provides +# the libstdc++ the statically linked runtime needs at link time. +RUN apt-get update && apt-get install -y --no-install-recommends \ + pkg-config ca-certificates libssl-dev g++ && rm -rf /var/lib/apt/lists/* +WORKDIR /build +COPY rust/ ./rust/ +RUN cargo build --release --manifest-path rust/Cargo.toml -p ct-bot + +# --- runtime ------------------------------------------------------------------- +FROM debian:trixie-slim +RUN apt-get update && apt-get install -y --no-install-recommends ca-certificates \ + && rm -rf /var/lib/apt/lists/* && useradd -m -u 1000 user +WORKDIR /app +COPY --from=engine /build/rust/target/release/ct-bot /usr/local/bin/ct-bot +COPY --from=web /web/out ./web +COPY model.int8.onnx ./model.int8.onnx +USER user + +# MCTS_SIMS can be overridden from the Space settings (Variables) without a +# rebuild. On the free 2-vCPU tier 800 sims is ~2 s a move; 2000 is ~5 s. +ENV PORT=7860 MCTS_SIMS=800 ORT_THREADS=2 STATIC_DIR=/app/web RUST_LOG=info +EXPOSE 7860 +CMD ["sh", "-c", "exec ct-bot serve --model /app/model.int8.onnx --threads \"$ORT_THREADS\""] diff --git a/README.md b/README.md index fd307d87e006a4348b729a3eaf545fcc9f0d6448..3cfb9d29273b630c2c7ba7a1e04db1a7b41bce94 100644 --- a/README.md +++ b/README.md @@ -1,11 +1,10 @@ --- title: ChessTransformer emoji: ♟️ -colorFrom: indigo +colorFrom: green colorTo: gray -sdk: gradio -sdk_version: 5.49.0 -app_file: app.py +sdk: docker +app_port: 7860 pinned: false license: mit short_description: Play a chess transformer trained only on human games @@ -14,15 +13,20 @@ short_description: Play a chess transformer trained only on human games # ♟️ ChessTransformer Play an **11.7M-parameter transformer trained only on human games** (no self-play, -no reinforcement learning), playing via AlphaZero-style MCTS. At full strength it -reaches **~2100 Elo** against Stockfish; this Space runs on CPU at a lower -simulation count so moves come back in ~1–2s. +no reinforcement learning), searching with AlphaZero-style MCTS. At full strength it +reaches **~2100 Elo** against Stockfish. -You play **White** — drag a piece and the bot replies automatically. Use the -slider to trade strength for speed. +- Pick a color and a clock, then play: drag or click to move, premove while it + thinks, right-click to draw arrows and mark squares. +- **Watch it play itself**, or press **Autoplay** mid-game to hand it your side. +- The **Engine search** tab shows the branches it explored for each move; hover one + to replay that line on the board. + +The engine is the Rust `ct-bot` (ONNX Runtime, int8, CPU). On this free 2-vCPU +Space it searches 800 positions a move, about 2 seconds. Code, weights, and the training pipeline: **https://github.com/tchauffi/ChessTransformer** > This `README.md` is the Space config. The deployable Space is assembled by -> `prepare.sh` (see `DEPLOY.md`) — it bundles `app.py`, this file, the slim -> `requirements.txt`, the `chesstransformer` package source, and the model weights. +> `prepare.sh` (see `DEPLOY.md`): this file, the Dockerfile, the `rust/` and +> `frontend/` sources, and the int8 model. diff --git a/app.py b/app.py deleted file mode 100644 index 3a5df93d37aa9386f27b94d31c611a0403e1dd38..0000000000000000000000000000000000000000 --- a/app.py +++ /dev/null @@ -1,243 +0,0 @@ -"""ChessTransformer — Hugging Face Space (Gradio). - -Play the transformer chess engine in the browser. Runs on CPU: the model is -only 11.7M params, so MCTS at a modest sim count returns a move in ~1-2s. - -Weights are resolved in this order: - 1. ``MODEL_PATH`` env var (a checkpoint dir with model.safetensors + config) - 2. a ``model/`` dir next to this file (how ``prepare.sh`` ships the Space) - 3. the repo's ``data/models/pos2move_v2.1`` (for local dev runs) - 4. download from GitHub (LFS media) as a last resort -""" - -from __future__ import annotations - -import itertools -import os -import sys -from pathlib import Path - -import chess -import gradio as gr -from gradio_chessboard import Chessboard - -# ── make `chesstransformer` importable ────────────────────────────────────── -# On the Space the package is vendored next to this file (cwd is on sys.path). -# For local dev runs from the repo, add the repo's src/ to the path. -_repo_src = Path(__file__).resolve().parents[1] / "src" -if (_repo_src / "chesstransformer").exists(): - sys.path.insert(0, str(_repo_src)) - -from chesstransformer.bots import Pos2MoveV2MctsBot # noqa: E402 - -START_FEN = chess.STARTING_FEN -DEFAULT_SIMS = int(os.environ.get("MCTS_SIMS", "400")) - -# GitHub locations for the last-resort weight download. -_GH = "tchauffi/ChessTransformer" -_BRANCH = os.environ.get("MODEL_BRANCH", "main") -_RAW = f"https://raw.githubusercontent.com/{_GH}/{_BRANCH}/data/models/pos2move_v2.1" -_LFS = f"https://media.githubusercontent.com/media/{_GH}/{_BRANCH}/data/models/pos2move_v2.1" - - -def _download_weights() -> str: - import urllib.request - - dest = Path("/tmp/pos2move_v2.1") - dest.mkdir(parents=True, exist_ok=True) - for fname, url in [("model_config.json", f"{_RAW}/model_config.json"), - ("model.safetensors", f"{_LFS}/model.safetensors")]: - out = dest / fname - if not out.exists(): - print(f"Downloading {fname} …") - urllib.request.urlretrieve(url, out) - return str(dest) - - -def resolve_model_dir() -> str: - env = os.environ.get("MODEL_PATH") - if env and (Path(env) / "model.safetensors").exists(): - return env - for cand in ( - Path(__file__).resolve().parent / "model", - Path("model"), - Path(__file__).resolve().parents[1] / "data" / "models" / "pos2move_v2.1", - ): - if (cand / "model.safetensors").exists(): - return str(cand) - return _download_weights() - - -# ── load the bot once (CPU, no compile) ───────────────────────────────────── -MODEL_DIR = resolve_model_dir() -bot = Pos2MoveV2MctsBot( - model_dir=MODEL_DIR, - num_simulations=DEFAULT_SIMS, - device="cpu", - compile=False, - time_limit=0.0, - # Sample the opening moves (∝ visit count) so games aren't identical every - # time; switches to deterministic best-move play after the opening. - move_temp=1.0, - move_temp_plies=12, -) - - -def _human_color(human_color: str) -> bool: - return chess.BLACK if human_color == "black" else chess.WHITE - - -def _white_pov_value(board: chess.Board) -> float: - """Value-head eval in [-1, 1] from White's perspective (+ = White better).""" - if board.is_game_over(): - if board.is_checkmate(): - return -1.0 if board.turn == chess.WHITE else 1.0 - return 0.0 # stalemate / draw - v = bot.get_value(board) - if v is None: - return 0.0 - return v if board.turn == chess.WHITE else -v - - -def eval_bar_html(board: chess.Board, orientation: str) -> str: - """A vertical eval bar (White share fills from the bottom of White's side). - Flipped to match the board orientation so the viewer's side is at the bottom.""" - wv = _white_pov_value(board) - white_pct = round(max(0.0, min(1.0, (wv + 1) / 2)) * 100, 1) - white_div = f'
' - black_div = f'
' - # orientation "white": Black on top, White on bottom; flipped when "black". - segments = black_div + white_div if orientation == "white" else white_div + black_div - return ( - f'
' - f'{segments}
' - ) - - -def _result_text(board: chess.Board, human_color: str) -> str: - outcome = board.outcome() - if outcome is None: - return "" - if outcome.winner is None: - return f"Draw ({outcome.termination.name.lower().replace('_', ' ')}). New game?" - who = "You win! 🎉" if outcome.winner == _human_color(human_color) else "ChessTransformer wins." - return f"Checkmate — {who} New game?" - - -def _bot_move(board: chess.Board, sims: int): - """Play the side to move with the bot; return its SAN and value.""" - bot.num_simulations = int(sims) - uci, value = bot.predict(board) - san = board.san(chess.Move.from_uci(uci)) - board.push_uci(uci) - return san, value - - -def on_move(fen: str, sims: int, human_color: str): - """Human just moved; reply with the bot's move (whichever side is to move). - The board orientation matches the human's color, so the eval bar does too. - - A generator: first yields a "thinking" status (so the player sees the bot is - working during the ~1-3s CPU search), then yields the bot's reply.""" - board = chess.Board(fen) - if board.is_game_over(): - yield board.fen(), _result_text(board, human_color), eval_bar_html(board, human_color) - return - - # Immediate feedback while the search runs (board/eval unchanged for now). - yield gr.update(), "⏳ ChessTransformer is thinking…", gr.update() - - san, value = _bot_move(board, sims) - - if board.is_game_over(): - status = f"Bot played **{san}**. {_result_text(board, human_color)}" - else: - eval_str = f" (eval {value:+.2f})" if value is not None else "" - status = f"Bot played **{san}**{eval_str}. Your move." - yield board.fen(), status, eval_bar_html(board, human_color) - - -# Monotonic id so every New game yields a *distinct* setup dict — otherwise a -# same-colour replay returns an identical dict and the gr.render block, seeing no -# change, wouldn't rebuild (and reset) the board. -_game_counter = itertools.count(1) - - -def new_game(play_as: str, sims: int): - """Start a fresh game. If the human plays Black, the bot (White) opens. - - Returns (setup, eval_bar). The setup dict drives a gr.render block — changing - it rebuilds the board so its orientation (chessboard.js reads it only at - construction) actually flips to the human's side.""" - human_color = "black" if play_as == "Black" else "white" - board = chess.Board() - if human_color == "black": - san, _ = _bot_move(board, sims) - status = f"New game — you are **Black**. Bot opened with **{san}**. Your move." - else: - status = "New game — you are **White**. Make your move." - setup = {"fen": board.fen(), "orientation": human_color, "color": human_color, - "status": status, "nonce": next(_game_counter)} - return setup, eval_bar_html(board, human_color) - - -with gr.Blocks(title="ChessTransformer", theme=gr.themes.Soft()) as demo: - gr.Markdown( - "# ♟️ ChessTransformer\n" - "An **11.7M-parameter transformer trained only on human games** " - "(no self-play, no RL), playing via AlphaZero-style MCTS. " - "It reaches **~2100 Elo** vs Stockfish at full strength; this CPU demo " - "runs at a lower sim count so moves come back quickly.\n\n" - "**Pick your color and hit New game.** Drag a piece to move — the bot " - "replies automatically. " - "[GitHub repo →](https://github.com/tchauffi/ChessTransformer)" - ) - setup = gr.State({"fen": START_FEN, "orientation": "white", "color": "white", - "status": "You are **White**. Make your move.", "nonce": 0}) - - with gr.Row(): - # Solid min_widths so the board container always has a size when the - # gr.render block (re)mounts it — chessboard.js reloads the whole page if - # it inits at 0 width, which is what caused the mobile flicker/reload loop. - eval_col = gr.Column(scale=0, min_width=44) - board_col = gr.Column(scale=3, min_width=340) - ctrl_col = gr.Column(scale=1, min_width=200) - - with eval_col: - eval_bar = gr.HTML(eval_bar_html(chess.Board(), "white"), visible=False) - - with ctrl_col: - play_as = gr.Radio(["White", "Black"], value="White", label="Play as") - sims = gr.Slider(32, 1200, value=DEFAULT_SIMS, step=8, - label="Engine strength (MCTS sims/move)", - info="Higher = stronger but slower on CPU") - show_eval = gr.Checkbox(False, label="Show evaluation bar") - new_btn = gr.Button("New game", variant="primary") - - # The board lives in a gr.render so switching color rebuilds it with the new - # orientation (chessboard.js reads orientation only at construction). The - # min_width above keeps the container sized so the remount can't init at 0. - with board_col: - @gr.render(inputs=setup) - def render_board(cfg): - board = Chessboard(value=cfg["fen"], game_mode=True, min_width=320, - orientation=cfg["orientation"], label="Drag to move") - status = gr.Markdown(cfg["status"]) - color = cfg["color"] - - def handle(fen, s): # generator → streams the "thinking" update first - yield from on_move(fen, s, color) - - # show_progress="hidden": our "⏳ thinking…" status is the signal, so - # Gradio's default overlay doesn't sit over the board. - board.move(handle, inputs=[board, sims], outputs=[board, status, eval_bar], - show_progress="hidden") - - show_eval.change(lambda show: gr.update(visible=show), inputs=show_eval, outputs=eval_bar) - new_btn.click(new_game, inputs=[play_as, sims], outputs=[setup, eval_bar]) - - -if __name__ == "__main__": - demo.launch() diff --git a/chesstransformer/__init__.py b/chesstransformer/__init__.py deleted file mode 100644 index 206d4bbf521b2669a51e26f8664f8bfcae6d47d1..0000000000000000000000000000000000000000 --- a/chesstransformer/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""This is the main package for the ChessTransformer project.""" diff --git a/chesstransformer/benchmark/__init__.py b/chesstransformer/benchmark/__init__.py deleted file mode 100644 index cf5eab0057d7c46a1125073146523269aeac1c2f..0000000000000000000000000000000000000000 --- a/chesstransformer/benchmark/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .bot_benchmark import BotBenchmark - -__all__ = ["BotBenchmark"] diff --git a/chesstransformer/benchmark/bot_benchmark.py b/chesstransformer/benchmark/bot_benchmark.py deleted file mode 100644 index 6b447c5d04c691934e4592e276b452b6fb7051cc..0000000000000000000000000000000000000000 --- a/chesstransformer/benchmark/bot_benchmark.py +++ /dev/null @@ -1,399 +0,0 @@ -""" -Bot benchmarking system for comparing chess bot performance. - -Usage: - python -m chesstransformer.benchmark.bot_benchmark \\ - --bot1-type position2move --bot1-checkpoint path/to/checkpoint \\ - --bot2-type random \\ - --num-games 100 \\ - --output results.json -""" - -import chess -import time -import json -from pathlib import Path -from typing import List, Tuple, Optional -from dataclasses import dataclass, asdict -from tqdm import tqdm - -from chesstransformer.bots import Position2MoveBot, LegacyPosition2MoveBot, RandomBot - - -@dataclass -class GameResult: - """Single game result statistics.""" - - game_id: int - white_bot: str - black_bot: str - result: str # "1-0", "0-1", "1/2-1/2" - num_moves: int - white_time: float - black_time: float - termination: str # "checkmate", "stalemate", "insufficient_material", "max_moves" - - def to_dict(self): - return asdict(self) - - -@dataclass -class BenchmarkStats: - """Aggregate statistics for a bot.""" - - bot_name: str - total_games: int - wins: int - losses: int - draws: int - avg_moves_per_game: float - avg_time_per_move: float - total_time: float - win_rate: float - win_as_white: int - win_as_black: int - - def to_dict(self): - return asdict(self) - - -class BotBenchmark: - """Benchmark system for comparing chess bots.""" - - def __init__(self, max_moves: int = 500, time_limit: Optional[float] = None): - """ - Initialize benchmark. - - Args: - max_moves: Maximum moves per game before declaring draw - time_limit: Optional time limit per move in seconds - """ - self.max_moves = max_moves - self.time_limit = time_limit - self.game_results: List[GameResult] = [] - self.bot_counter = 0 # Counter for unique bot IDs - - def create_bot( - self, bot_type: str, checkpoint_path: Optional[str] = None, bot_name: Optional[str] = None, **kwargs - ): - """ - Factory method to create bots. - - Args: - bot_type: Type of bot ("position2move", "legacy_position2move", "random") - checkpoint_path: Path to model checkpoint (for Position2MoveBot) - bot_name: Optional custom name for the bot (for tracking multiple instances) - **kwargs: Additional bot-specific arguments - """ - if bot_type.lower() == "position2move": - if checkpoint_path: - bot = Position2MoveBot(model_path=checkpoint_path) - else: - bot = Position2MoveBot() - elif bot_type.lower() == "legacy_position2move": - if checkpoint_path: - bot = LegacyPosition2MoveBot(model_path=checkpoint_path) - else: - bot = LegacyPosition2MoveBot() - elif bot_type.lower() == "random": - bot = RandomBot() - else: - raise ValueError(f"Unknown bot type: {bot_type}") - - # Assign unique identifier - if bot_name: - bot._benchmark_id = bot_name - else: - self.bot_counter += 1 - bot._benchmark_id = f"{bot.__class__.__name__}_{self.bot_counter}" - - return bot - - def play_game(self, white_bot, black_bot, game_id: int, verbose: bool = False) -> GameResult: - """ - Play a single game between two bots. - - Args: - white_bot: Bot playing white - black_bot: Bot playing black - game_id: Unique game identifier - verbose: Print move-by-move progress - - Returns: - GameResult with statistics - """ - board = chess.Board() - white_time = 0.0 - black_time = 0.0 - move_count = 0 - - while not board.is_game_over() and move_count < self.max_moves: - current_bot = white_bot if board.turn == chess.WHITE else black_bot - - start_time = time.time() - - move, _ = current_bot.predict(board) - - elapsed = time.time() - start_time - - if board.turn == chess.WHITE: - white_time += elapsed - else: - black_time += elapsed - - board.push(chess.Move.from_uci(move)) - move_count += 1 - - if verbose and move_count % 10 == 0: - print(f"Move {move_count}: {move}") - - # Determine result and termination reason - if board.is_checkmate(): - result = "0-1" if board.turn == chess.WHITE else "1-0" - termination = "checkmate" - elif board.is_stalemate(): - result = "1/2-1/2" - termination = "stalemate" - elif board.is_insufficient_material(): - result = "1/2-1/2" - termination = "insufficient_material" - elif board.is_seventyfive_moves(): - result = "1/2-1/2" - termination = "75_move_rule" - elif board.is_fivefold_repetition(): - result = "1/2-1/2" - termination = "repetition" - elif move_count >= self.max_moves: - result = "1/2-1/2" - termination = "max_moves" - else: - # Should not reach here if game ended normally - result = "1/2-1/2" - termination = "unknown" - - return GameResult( - game_id=game_id, - white_bot=white_bot._benchmark_id, - black_bot=black_bot._benchmark_id, - result=result, - num_moves=move_count, - white_time=white_time, - black_time=black_time, - termination=termination, - ) - - def run_benchmark( - self, bot1, bot2, num_games: int, alternate_colors: bool = True, verbose: bool = False - ) -> Tuple[BenchmarkStats, BenchmarkStats]: - """ - Run full benchmark between two bots. - - Args: - bot1: First bot - bot2: Second bot - num_games: Number of games to play - alternate_colors: Alternate colors each game - verbose: Print game-by-game results - - Returns: - Tuple of (bot1_stats, bot2_stats) - """ - self.game_results = [] - - pbar = tqdm(range(num_games), desc="Playing games") - for game_id in pbar: - if alternate_colors and game_id % 2 == 1: - # Swap colors - white_bot, black_bot = bot2, bot1 - else: - white_bot, black_bot = bot1, bot2 - - result = self.play_game(white_bot, black_bot, game_id, verbose=verbose) - self.game_results.append(result) - - if verbose: - print(f"Game {game_id + 1}: {result.white_bot} vs {result.black_bot} = {result.result}") - - # Update progress bar with current stats - bot1_wins = sum(1 for r in self.game_results if self._bot_won(r, bot1._benchmark_id)) - bot2_wins = sum(1 for r in self.game_results if self._bot_won(r, bot2._benchmark_id)) - pbar.set_postfix({bot1._benchmark_id: bot1_wins, bot2._benchmark_id: bot2_wins}) - - # Calculate statistics - bot1_stats = self._calculate_stats(bot1._benchmark_id) - bot2_stats = self._calculate_stats(bot2._benchmark_id) - - return bot1_stats, bot2_stats - - def _bot_won(self, result: GameResult, bot_name: str) -> bool: - """Check if bot won the game.""" - if bot_name == result.white_bot and result.result == "1-0": - return True - if bot_name == result.black_bot and result.result == "0-1": - return True - return False - - def _calculate_stats(self, bot_name: str) -> BenchmarkStats: - """Calculate aggregate statistics for a bot.""" - bot_results = [] - wins = 0 - losses = 0 - draws = 0 - win_as_white = 0 - win_as_black = 0 - total_time = 0.0 - total_moves = 0 - - for result in self.game_results: - is_white = result.white_bot == bot_name - is_black = result.black_bot == bot_name - - if not (is_white or is_black): - continue - - bot_results.append(result) - total_moves += result.num_moves - - if is_white: - total_time += result.white_time - if result.result == "1-0": - wins += 1 - win_as_white += 1 - elif result.result == "0-1": - losses += 1 - else: - draws += 1 - else: - total_time += result.black_time - if result.result == "0-1": - wins += 1 - win_as_black += 1 - elif result.result == "1-0": - losses += 1 - else: - draws += 1 - - total_games = len(bot_results) - avg_moves = total_moves / total_games if total_games > 0 else 0 - avg_time_per_move = total_time / total_moves if total_moves > 0 else 0 - win_rate = wins / total_games if total_games > 0 else 0 - - return BenchmarkStats( - bot_name=bot_name, - total_games=total_games, - wins=wins, - losses=losses, - draws=draws, - avg_moves_per_game=avg_moves, - avg_time_per_move=avg_time_per_move, - total_time=total_time, - win_rate=win_rate, - win_as_white=win_as_white, - win_as_black=win_as_black, - ) - - def save_results(self, output_path: str): - """Save benchmark results to JSON file.""" - output = { - "config": {"max_moves": self.max_moves, "time_limit": self.time_limit, "num_games": len(self.game_results)}, - "games": [r.to_dict() for r in self.game_results], - "stats": { - bot_name: self._calculate_stats(bot_name).to_dict() - for bot_name in set([r.white_bot for r in self.game_results] + [r.black_bot for r in self.game_results]) - }, - } - - output_file = Path(output_path) - output_file.parent.mkdir(parents=True, exist_ok=True) - - with output_file.open("w", encoding="utf-8") as f: - json.dump(output, f, indent=2) - - print(f"Results saved to: {output_path}") - - def print_summary(self, bot1_stats: BenchmarkStats, bot2_stats: BenchmarkStats): - """Print formatted summary of benchmark results.""" - print("\n" + "=" * 80) - print("BENCHMARK RESULTS") - print("=" * 80) - - for stats in [bot1_stats, bot2_stats]: - print(f"\n{stats.bot_name}:") - print(f" Total Games: {stats.total_games}") - print(f" Wins: {stats.wins} ({stats.win_rate:.1%})") - print(f" - As White: {stats.win_as_white}") - print(f" - As Black: {stats.win_as_black}") - print(f" Losses: {stats.losses}") - print(f" Draws: {stats.draws}") - print(f" Avg Moves/Game: {stats.avg_moves_per_game:.1f}") - print(f" Avg Time/Move: {stats.avg_time_per_move:.3f}s") - print(f" Total Time: {stats.total_time:.1f}s") - - print("\n" + "=" * 80) - - -def main(): - """CLI entry point for bot benchmarking.""" - import argparse - - parser = argparse.ArgumentParser(description="Benchmark chess bots") - parser.add_argument( - "--bot1-type", - type=str, - required=True, - choices=["position2move", "legacy_position2move", "random"], - help="Type of first bot", - ) - parser.add_argument("--bot1-checkpoint", type=str, default=None, help="Checkpoint path for bot1 (if applicable)") - parser.add_argument( - "--bot1-name", type=str, default=None, help="Custom name for bot1 (useful when comparing same bot types)" - ) - parser.add_argument( - "--bot2-type", - type=str, - required=True, - choices=["position2move", "legacy_position2move", "random"], - help="Type of second bot", - ) - parser.add_argument("--bot2-checkpoint", type=str, default=None, help="Checkpoint path for bot2 (if applicable)") - parser.add_argument( - "--bot2-name", type=str, default=None, help="Custom name for bot2 (useful when comparing same bot types)" - ) - parser.add_argument("--num-games", type=int, default=100, help="Number of games to play") - parser.add_argument("--max-moves", type=int, default=500, help="Maximum moves per game") - parser.add_argument("--time-limit", type=float, default=None, help="Time limit per move in seconds") - parser.add_argument("--output", type=str, default="benchmark_results.json", help="Output file for results") - parser.add_argument("--no-alternate", action="store_true", help="Don't alternate colors between games") - parser.add_argument("--verbose", action="store_true", help="Print detailed game information") - - args = parser.parse_args() - - # Create benchmark - benchmark = BotBenchmark(max_moves=args.max_moves, time_limit=args.time_limit) - - # Create bots - print(f"Creating {args.bot1_type} bot...") - bot1 = benchmark.create_bot(args.bot1_type, checkpoint_path=args.bot1_checkpoint, bot_name=args.bot1_name) - - print(f"Creating {args.bot2_type} bot...") - bot2 = benchmark.create_bot(args.bot2_type, checkpoint_path=args.bot2_checkpoint, bot_name=args.bot2_name) - - # Run benchmark - print(f"\nRunning benchmark: {args.num_games} games") - print(f"Max moves per game: {args.max_moves}") - if args.time_limit: - print(f"Time limit per move: {args.time_limit}s") - - bot1_stats, bot2_stats = benchmark.run_benchmark( - bot1, bot2, num_games=args.num_games, alternate_colors=not args.no_alternate, verbose=args.verbose - ) - - # Print summary - benchmark.print_summary(bot1_stats, bot2_stats) - - # Save results - benchmark.save_results(args.output) - - -if __name__ == "__main__": - main() diff --git a/chesstransformer/bots/__init__.py b/chesstransformer/bots/__init__.py deleted file mode 100644 index 93d475e795d897bd7a43e6e647637e42ae86d57c..0000000000000000000000000000000000000000 --- a/chesstransformer/bots/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -from .pos2move_v2_bot import Pos2MoveV2Bot -from .pos2move_v2_mcts_bot import Pos2MoveV2MctsBot -from .random_bot import RandomBot - -__all__ = ["Pos2MoveV2Bot", "Pos2MoveV2MctsBot", "RandomBot"] diff --git a/chesstransformer/bots/legacy_position2move_bot.py b/chesstransformer/bots/legacy_position2move_bot.py deleted file mode 100644 index 941ec8b68305c437c4ce257b10671680744eab4c..0000000000000000000000000000000000000000 --- a/chesstransformer/bots/legacy_position2move_bot.py +++ /dev/null @@ -1,222 +0,0 @@ -"""Legacy Position2Move bot for V2 model compatibility. - -The V2 model was trained with an older architecture that uses: -- MultiHeadAttention instead of GroupedQueryAttention -- LayerNorm with gamma/beta instead of RMSNorm with weight -- Standard GELU FeedForward instead of SwiGLU -- No CLS token, castling, en passant, or halfmove embeddings -""" - -from pathlib import Path -import json -import torch -import torch.nn as nn -import chess -from safetensors import safe_open -from chesstransformer.models.transformer.attention import MultiHeadAttention -from chesstransformer.models.tokenizer import PostionTokenizer, MoveTokenizer - - -class LayerNorm(nn.Module): - """Legacy LayerNorm with gamma/beta naming.""" - - def __init__(self, embed_dim): - super().__init__() - self.gamma = nn.Parameter(torch.ones(embed_dim)) - self.beta = nn.Parameter(torch.zeros(embed_dim)) - self.eps = 1e-6 - - def forward(self, x): - mean = x.mean(dim=-1, keepdim=True) - var = x.var(dim=-1, unbiased=False, keepdim=True) - return self.gamma * (x - mean) / torch.sqrt(var + self.eps) + self.beta - - -class FeedForward(nn.Module): - """Legacy FeedForward network.""" - - def __init__(self, embed_dim): - super().__init__() - self.layers = nn.Sequential( - nn.Linear(embed_dim, 4 * embed_dim), - nn.GELU(approximate="tanh"), - nn.Linear(4 * embed_dim, embed_dim), - ) - - def forward(self, x): - return self.layers(x) - - -class LegacyTransformerBlock(nn.Module): - """Legacy transformer block for V2 model.""" - - def __init__( - self, - embed_dim, - num_heads, - context_length, - dropout, - qkv_bias, - mask_future=False, - ): - super().__init__() - self.att = MultiHeadAttention( - d_in=embed_dim, - d_out=embed_dim, - num_heads=num_heads, - context_length=context_length, - dropout=dropout, - qkv_bias=qkv_bias, - mask_future=mask_future, - ) - self.feed_forward = FeedForward(embed_dim) - self.norm1 = LayerNorm(embed_dim) - self.norm2 = LayerNorm(embed_dim) - self.dropout_shortcut = nn.Dropout(dropout) - - def forward(self, x): - shortcut = x - x = self.norm1(x) - x = self.att(x) - x = self.dropout_shortcut(x) - x = x + shortcut - - shortcut = x - x = self.norm2(x) - x = self.feed_forward(x) - x = self.dropout_shortcut(x) - x = x + shortcut - - return x - - -class LegacyPosition2MoveModel(nn.Module): - """Legacy Position2Move model architecture for V2 compatibility.""" - - def __init__( - self, - vocab_size: int = 13, - move_vocab_size: int = 1968, - embed_dim: int = 512, - nb_transformer_layers: int = 8, - num_heads: int = 8, - dropout: float = 0.1, - kvq_bias: bool = False, - mask_future: bool = False, - ): - super().__init__() - - # Board piece embeddings - self.token_embedding = nn.Embedding(vocab_size, embed_dim) - self.position_embedding = nn.Embedding(64, embed_dim) # 64 squares - self.player_embedding = nn.Embedding(2, embed_dim) # 2 players - - self.dropout = nn.Dropout(dropout) - self.transformer_blocks = nn.Sequential( - *[ - LegacyTransformerBlock( - embed_dim=embed_dim, - num_heads=num_heads, - context_length=64, - dropout=dropout, - qkv_bias=kvq_bias, - mask_future=mask_future, - ) - for _ in range(nb_transformer_layers) - ] - ) - - self.norm = LayerNorm(embed_dim) - self.lm_head = nn.Linear(embed_dim, move_vocab_size, bias=False) - - def forward(self, x, is_white): - batch_size, seq_len = x.shape - - # Get embeddings - token_emb = self.token_embedding(x) - pos_indices = torch.arange(seq_len, device=x.device) - pos_emb = self.position_embedding(pos_indices) - player_emb = self.player_embedding(is_white.long()) - - # Combine embeddings - x = token_emb + pos_emb.unsqueeze(0) + player_emb.unsqueeze(1) - x = self.dropout(x) - - # Transformer blocks - x = self.transformer_blocks(x) - x = self.norm(x) - - # Mean pooling - x = x.mean(dim=1) - - # Output - logits = self.lm_head(x) - return logits - - -data_folder = Path(__file__).parents[1] / "data" - - -class LegacyPosition2MoveBot: - """Bot using the legacy V2 model architecture.""" - - def __init__( - self, - model_path: str = str((data_folder / "models/position2moveV2.0/model.safetensors").resolve()), - device: str = "cpu", - ): - self.device = device - self.position_tokenizer = PostionTokenizer() - self.move_tokenizer = MoveTokenizer() - - config_path = Path(model_path).parent / "config.json" - - with open(config_path, "r") as f: - self.config = json.load(f) - - # Load legacy model - self.model = LegacyPosition2MoveModel(**self.config).to(device) - - with safe_open(model_path, framework="pt", device=device) as f: - state_dict = {k: f.get_tensor(k) for k in f.keys()} - self.model.load_state_dict(state_dict) - - self.model.eval() - - @torch.no_grad() - def predict(self, board: chess.Board): - tokens_ids = self.position_tokenizer.encode(board) - torch_input = torch.tensor(tokens_ids).unsqueeze(0).long().to(self.device) - - is_white = board.turn - is_white = torch.tensor([is_white]).bool().to(self.device) - - logits = self.model(torch_input, is_white) - - legal_moves = [m.uci() for m in board.legal_moves] - - mask = torch.full((logits.size(-1),), float("-inf")).to(self.device) - for move in legal_moves: - move_id = self.move_tokenizer.encode(move) - mask[move_id] = 0.0 - - masked_logits = logits[0] + mask - probs = torch.softmax(masked_logits, dim=-1) - - # Sample from distribution with temperature - predicted_move_id = torch.multinomial(probs * 0.2, num_samples=1).item() - proba = probs[predicted_move_id].item() - - predicted_move = self.move_tokenizer.decode(predicted_move_id) - return predicted_move, proba - - -if __name__ == "__main__": - bot = LegacyPosition2MoveBot() - - board = chess.Board() - print("Initial board:") - print(board) - - move, proba = bot.predict(board) - print(f"Bot suggests move: {move} with probability {proba:.4f}") diff --git a/chesstransformer/bots/pos2move_v2_bot.py b/chesstransformer/bots/pos2move_v2_bot.py deleted file mode 100644 index d40be50a21f52cc8fbc6c4847d30a4ac344c1689..0000000000000000000000000000000000000000 --- a/chesstransformer/bots/pos2move_v2_bot.py +++ /dev/null @@ -1,499 +0,0 @@ -"""Bot for Pos2MoveV2 with alpha-beta search + BF16.""" - -from __future__ import annotations - -import json -import time as _time -from pathlib import Path - -import chess -import chess.polyglot -import numpy as np -import torch -from safetensors import safe_open - -from chesstransformer.models.tokenizer import PostionTokenizer -from chesstransformer.models.tokenizer.alphazero_move_encoder import move_to_action_plane -from chesstransformer.models.transformer.pos2move_v2 import Pos2MoveV2 - -_DEFAULT_RUN = Path(__file__).parents[3] / "data" / "models" / "pos2move_v2.1" - -# Fixed batch-size buckets. Batched evals are zero-padded up to the next bucket -# so the (optionally compiled) model only ever sees a handful of static shapes. -_BATCH_BUCKETS = (4, 8, 16, 32) - - -class _SearchTimeout(Exception): - pass - - -class Pos2MoveV2Bot: - def __init__( - self, - model_dir: str | Path = _DEFAULT_RUN, - depth: int = 3, - top_p: float = 0.90, - time_limit: float = 30.0, - tt_size: int = 500_000, - device: str = "cuda" if torch.cuda.is_available() else "cpu", - use_ema: bool = False, - compile: bool = True, - quiescence_depth: int = 4, - ): - self.depth = depth - self.top_p = top_p - self.time_limit = time_limit - self.quiescence_depth = quiescence_depth - self.nodes_searched = 0 - self.tt_hits = 0 - self.completed_depth = 0 - self.device = device - self.position_tokenizer = PostionTokenizer() - - model_dir = Path(model_dir) - - config_path = model_dir / "model_config.json" - if not config_path.exists(): - config_path = model_dir.parent.parent / "model_config.json" - if not config_path.exists(): - raise FileNotFoundError(f"No model_config.json found for {model_dir}") - - with open(config_path) as f: - config = json.load(f) - - model = Pos2MoveV2(**config) - - safetensors_path = model_dir / "model.safetensors" - if not safetensors_path.exists(): - raise FileNotFoundError(f"No model.safetensors in {model_dir}") - with safe_open(str(safetensors_path), framework="pt", device="cpu") as f: - state_dict = {k: f.get_tensor(k) for k in f.keys()} - - if any(k.startswith("_orig_mod.") for k in state_dict): - state_dict = {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()} - - model.load_state_dict(state_dict) - - if use_ema: - ema_path = model_dir / "ema_state.pt" - if not ema_path.exists(): - raise FileNotFoundError(f"No ema_state.pt in {model_dir}") - ema_state = torch.load(str(ema_path), map_location="cpu", weights_only=True) - ema_state = {k.replace("_orig_mod.", ""): v for k, v in ema_state.items()} - missing, unexpected = model.load_state_dict(ema_state, strict=False) - if unexpected: - print(f"WARNING: EMA contains unexpected keys: {unexpected}") - print(f"EMA weights loaded ({len(ema_state)} tensors; {len(missing)} buffers kept).") - - model.eval() - self.model = model.bfloat16().to(device) - - self._buf_board = torch.zeros(1, 64, dtype=torch.long, device=device) - self._buf_player = torch.zeros(1, dtype=torch.long, device=device) - self._buf_castling = torch.zeros(1, dtype=torch.long, device=device) - self._buf_ep = torch.zeros(1, dtype=torch.long, device=device) - self._batch_bufs: dict[int, tuple] = {} - - self._tt_size = tt_size - self._tt: dict[int, tuple[np.ndarray, float]] = {} - self._deadline: float = 0.0 - - # CUDA graphs collapse the Python/kernel-launch overhead that dominates - # this tiny model at small batch sizes. Bucketed batches keep the number - # of captured graphs small. Falls back to eager if compilation fails. - self._compiled = False - if compile and device == "cuda": - self._eager_model = self.model - try: - self.model = torch.compile(self.model, mode="reduce-overhead") - self._compiled = True - except Exception as e: # pragma: no cover - environment dependent - print(f"WARNING: torch.compile unavailable ({e}); using eager.") - self.model = self._eager_model - - self._warmup() - - print( - f"Pos2MoveV2Bot loaded (device={device}, depth={depth}, " - f"top_p={top_p:.0%}, params={sum(p.numel() for p in self.model.parameters()) / 1e6:.1f}M)" - ) - - @torch.no_grad() - def _warmup(self): - try: - # Batch-1 path (single-position _evaluate). - for _ in range(3): - self.model(self._buf_board, self._buf_player, self._buf_castling, self._buf_ep) - # Each bucket shape used by _batch_run, so compilation / CUDA-graph - # capture happens up front rather than mid-search. - for bucket in _BATCH_BUCKETS: - b, p, c, e = self._batch_buffers(bucket) - for _ in range(3): - self.model(b, p, c, e) - except Exception as e: # pragma: no cover - environment dependent - if self._compiled: - print(f"WARNING: compiled warmup failed ({e}); falling back to eager.") - self.model = self._eager_model - self._compiled = False - self.model(self._buf_board, self._buf_player, self._buf_castling, self._buf_ep) - else: - raise - if self.device == "cuda": - torch.cuda.synchronize() - - def _adaptive_time_limit(self, board: chess.Board) -> float: - if self.time_limit <= 0: - return 0.0 - ply = len(board.move_stack) - move_number = ply // 2 + 1 - if move_number <= 10: - scale = 0.10 - elif move_number <= 20: - scale = 0.40 - elif move_number <= 40: - scale = 1.0 - else: - scale = 0.60 - return self.time_limit * scale - - def predict(self, board: chess.Board) -> tuple[str, float | None]: - self.nodes_searched = 0 - self.tt_hits = 0 - self.completed_depth = 0 - - effective_limit = self._adaptive_time_limit(board) - self._deadline = _time.monotonic() + effective_limit if effective_limit > 0 else float("inf") - - best_move = None - best_value = 0.0 - - for d in range(1, self.depth + 1): - stack_len = len(board.move_stack) - try: - move, value = self._search_root(board, d) - best_move = move - best_value = value - self.completed_depth = d - except _SearchTimeout: - while len(board.move_stack) > stack_len: - board.pop() - break - - if best_move is None: - best_move = next(iter(board.legal_moves)) - - return best_move.uci(), best_value - - def get_value(self, board: chess.Board) -> float: - _, value = self._evaluate(board) - return value - - def _check_time(self): - if _time.monotonic() >= self._deadline: - raise _SearchTimeout() - - @torch.no_grad() - def _evaluate(self, board: chess.Board) -> tuple[np.ndarray, float]: - key = chess.polyglot.zobrist_hash(board) - cached = self._tt.get(key) - if cached is not None: - self.tt_hits += 1 - return cached - - position = self.position_tokenizer.encode(board) - self._buf_board[0] = torch.tensor(position, dtype=torch.long, device=self.device) - self._buf_player[0] = int(board.turn) - - castling = 0 - if board.has_kingside_castling_rights(chess.WHITE): - castling |= 1 - if board.has_queenside_castling_rights(chess.WHITE): - castling |= 2 - if board.has_kingside_castling_rights(chess.BLACK): - castling |= 4 - if board.has_queenside_castling_rights(chess.BLACK): - castling |= 8 - self._buf_castling[0] = castling - - ep_file = chess.square_file(board.ep_square) if board.has_legal_en_passant() else 8 - self._buf_ep[0] = ep_file - - move_logits, value_t = self.model( - self._buf_board, self._buf_player, self._buf_castling, self._buf_ep - ) - - logits = move_logits[0].float().cpu().numpy() - value = float(value_t.item()) - - if self._tt_size > 0 and len(self._tt) >= self._tt_size: - del self._tt[next(iter(self._tt))] - self._tt[key] = (logits, value) - - return logits, value - - def _batch_buffers(self, bucket: int): - """Persistent zero-padded device buffers per bucket size. - - Using a small fixed set of batch shapes keeps torch.compile / CUDA - graphs from recompiling (and re-capturing) on every distinct batch size. - """ - bufs = self._batch_bufs.get(bucket) - if bufs is None: - bufs = ( - torch.zeros(bucket, 64, dtype=torch.long, device=self.device), - torch.zeros(bucket, dtype=torch.long, device=self.device), - torch.zeros(bucket, dtype=torch.long, device=self.device), - torch.zeros(bucket, dtype=torch.long, device=self.device), - ) - self._batch_bufs[bucket] = bufs - return bufs - - @staticmethod - def _bucket_for(n: int) -> int: - for b in _BATCH_BUCKETS: - if n <= b: - return b - return _BATCH_BUCKETS[-1] - - @torch.no_grad() - def _batch_run(self, items: list[tuple[np.ndarray, int, int, int, int]]): - n = len(items) - bucket = self._bucket_for(n) - board_arr, player_arr, castling_arr, ep_arr = self._batch_buffers(bucket) - # Zero the padding rows (token/index 0 is a valid embedding index). - board_arr.zero_() - player_arr.zero_() - castling_arr.zero_() - ep_arr.zero_() - - for i, (pos, player, castling, ep, _) in enumerate(items): - board_arr[i] = torch.tensor(pos, dtype=torch.long) - player_arr[i] = player - castling_arr[i] = castling - ep_arr[i] = ep - - move_logits, value_t = self.model(board_arr, player_arr, castling_arr, ep_arr) - # Slice off padding before the host copy. - logits_np = move_logits[:n].float().cpu().numpy() - values_np = value_t[:n].float().cpu().numpy() - - for i, (_, _, _, _, key) in enumerate(items): - if self._tt_size > 0 and len(self._tt) >= self._tt_size: - del self._tt[next(iter(self._tt))] - self._tt[key] = (logits_np[i], float(values_np[i].item())) - - def _encode_position(self, board: chess.Board) -> tuple[np.ndarray, int, int, int]: - position = self.position_tokenizer.encode(board) - player = int(board.turn) - castling = 0 - if board.has_kingside_castling_rights(chess.WHITE): - castling |= 1 - if board.has_queenside_castling_rights(chess.WHITE): - castling |= 2 - if board.has_kingside_castling_rights(chess.BLACK): - castling |= 4 - if board.has_queenside_castling_rights(chess.BLACK): - castling |= 8 - ep_file = chess.square_file(board.ep_square) if board.has_legal_en_passant() else 8 - return position, player, castling, ep_file - - def _prefetch_children(self, board: chess.Board, moves: list[chess.Move]): - uncached = [] - for move in moves: - board.push(move) - key = chess.polyglot.zobrist_hash(board) - # Cheap terminal proxy: positions with no legal moves (checkmate / - # stalemate) are scored directly by _alpha_beta, so skip a wasted - # model eval on them. Claimable-draw positions (threefold / 50-move) - # still have legal moves; caching their eval is harmless because - # _alpha_beta's authoritative is_game_over check overrides it. - if key not in self._tt and any(board.legal_moves): - pos, player, castling, ep_file = self._encode_position(board) - uncached.append((pos, player, castling, ep_file, key)) - board.pop() - if len(uncached) >= 2: - self._batch_run(uncached) - - def _top_p_for_depth(self, depth: int, max_depth: int) -> float: - plies_from_root = max_depth - depth - if plies_from_root == 0: - return self.top_p - elif plies_from_root <= 2: - return self.top_p * 0.7 - else: - return self.top_p * 0.5 - - def _search_root(self, board: chess.Board, depth: int) -> tuple[chess.Move, float]: - ordered_moves = self._order_moves(board, self.top_p) - if not ordered_moves: - return chess.Move.null(), 0.0 - self._prefetch_children(board, [m for m, _ in ordered_moves]) - best_move = ordered_moves[0][0] - alpha = float("-inf") - for move, _ in ordered_moves: - self._check_time() - board.push(move) - value = -self._alpha_beta(board, depth - 1, -float("inf"), -alpha, depth) - board.pop() - if value > alpha: - alpha = value - best_move = move - return best_move, alpha - - def _terminal_value(self, board: chess.Board) -> float | None: - """Negamax terminal value (side-to-move POV), or None if not terminal. - - Uses cheap checks instead of ``is_game_over(claim_draw=True)`` (whose - ``can_claim_threefold_repetition`` dominated the profile): no-legal-move - positions are mate/stalemate, and draws are detected via material, - 3-fold repetition and the 50-move clock — without the expensive - "a move *could* force a repetition" probe. - """ - if not any(board.legal_moves): - return -1.0 if board.is_check() else 0.0 - if ( - board.is_insufficient_material() - or board.is_repetition(3) - or board.halfmove_clock >= 100 - ): - return 0.0 - return None - - @torch.no_grad() - def _quiescence(self, board: chess.Board, alpha: float, beta: float, qdepth: int) -> float: - """Resolve tactical noise before trusting the value head. - - Stand-pat on the value head, then search only forcing moves (captures - and promotions) so the leaf isn't evaluated in the middle of an - unresolved exchange (the horizon effect). - """ - self.nodes_searched += 1 - self._check_time() - - term = self._terminal_value(board) - if term is not None: - return term - - logits, stand_pat = self._evaluate(board) - if stand_pat >= beta: - return beta - if stand_pat > alpha: - alpha = stand_pat - if qdepth <= 0: - return alpha - - noisy = [] - for move in board.legal_moves: - if board.is_capture(move) or move.promotion: - plane = move_to_action_plane(move.from_square, move.to_square, move.promotion) - noisy.append((float(logits[move.from_square, plane]), move)) - if not noisy: - return alpha - noisy.sort(key=lambda x: -x[0]) - - for _, move in noisy: - board.push(move) - score = -self._quiescence(board, -beta, -alpha, qdepth - 1) - board.pop() - if score >= beta: - return beta - if score > alpha: - alpha = score - return alpha - - def _alpha_beta(self, board: chess.Board, depth: int, alpha: float, beta: float, max_depth: int) -> float: - self.nodes_searched += 1 - self._check_time() - - term = self._terminal_value(board) - if term is not None: - return term - - if depth <= 0: - if self.quiescence_depth > 0: - return self._quiescence(board, alpha, beta, self.quiescence_depth) - _, value = self._evaluate(board) - return value - - p = self._top_p_for_depth(depth, max_depth) - ordered_moves = self._order_moves(board, p) - self._prefetch_children(board, [m for m, _ in ordered_moves]) - - for move, _ in ordered_moves: - board.push(move) - score = -self._alpha_beta(board, depth - 1, -beta, -alpha, max_depth) - board.pop() - if score >= beta: - return beta - if score > alpha: - alpha = score - return alpha - - def _order_moves(self, board: chess.Board, p: float, min_moves: int = 2, max_moves: int = 30): - logits, _ = self._evaluate(board) - moves = [] - raw_scores = [] - for move in board.legal_moves: - plane = move_to_action_plane(move.from_square, move.to_square, move.promotion) - raw_scores.append(float(logits[move.from_square, plane])) - moves.append(move) - if not moves: - return [] - - scores = np.array(raw_scores, dtype=np.float64) - scores -= scores.max() - exp_scores = np.exp(scores) - probs = exp_scores / exp_scores.sum() - - order = np.argsort(-probs) - cumsum = 0.0 - selected = [] - for idx in order: - selected.append((moves[idx], float(probs[idx]))) - cumsum += probs[idx] - if cumsum >= p and len(selected) >= min_moves: - break - if len(selected) >= max_moves: - break - - while len(selected) < min_moves and len(selected) < len(moves): - selected.append((moves[order[len(selected)]], float(probs[order[len(selected)]]))) - - return selected - - -if __name__ == "__main__": - import argparse - import time - - parser = argparse.ArgumentParser() - parser.add_argument("model_dir", nargs="?", default=str(_DEFAULT_RUN)) - parser.add_argument("depth", nargs="?", type=int, default=3) - parser.add_argument("top_p", nargs="?", type=float, default=0.90) - parser.add_argument("--ema", action="store_true") - args = parser.parse_args() - - bot = Pos2MoveV2Bot( - model_dir=args.model_dir, depth=args.depth, top_p=args.top_p, - time_limit=30.0, use_ema=args.ema, - ) - - board = chess.Board() - print(f"\nStarting position:\n{board}\n") - - for i in range(10): - t0 = time.time() - move_uci, value = bot.predict(board) - elapsed = time.time() - t0 - print( - f"{'White' if board.turn else 'Black'} plays {move_uci} " - f"(depth={bot.completed_depth}/{args.depth}, value={value:+.3f}, " - f"nodes={bot.nodes_searched}, tt_hits={bot.tt_hits}, time={elapsed:.2f}s)" - ) - board.push_uci(move_uci) - print(board) - print() - - if board.is_game_over(): - print(f"Game over: {board.result()}") - break diff --git a/chesstransformer/bots/pos2move_v2_mcts_bot.py b/chesstransformer/bots/pos2move_v2_mcts_bot.py deleted file mode 100644 index caa54576b7326aa142fe747f6696f89040cdfab9..0000000000000000000000000000000000000000 --- a/chesstransformer/bots/pos2move_v2_mcts_bot.py +++ /dev/null @@ -1,318 +0,0 @@ -"""AlphaZero-style PUCT MCTS engine for Pos2MoveV2. - -Subclasses :class:`Pos2MoveV2Bot` to reuse its (torch.compiled, transposition- -cached) ``_evaluate`` — the policy head supplies move priors and the value head -scores leaves. Move selection is by visit count (the standard AlphaZero choice). - -Node representation is **edge-centric**: a node stores its children's visit -counts / values / priors as numpy arrays, and child ``_Node`` objects are created -lazily only when a child is actually descended into. This avoids allocating a -node per legal move at every expansion (which dominated latency) and lets PUCT -selection run vectorized over the arrays. Leaves are collected in batches with -virtual loss so the network sees one batched forward per wave. -""" - -from __future__ import annotations - -import math - -import chess -import numpy as np - -from chesstransformer.bots.pos2move_v2_bot import _BATCH_BUCKETS, _DEFAULT_RUN, Pos2MoveV2Bot -from chesstransformer.models.tokenizer.alphazero_move_encoder import move_to_action_plane - - -class _Node: - """A search node. Child visit stats live in arrays here (edge-centric); child - ``_Node`` objects are created lazily on first descent. A node is *expanded* - once ``moves`` is set.""" - - __slots__ = ("moves", "priors", "child_N", "child_W", "children") - - def __init__(self): - self.moves: list[chess.Move] | None = None - self.priors: np.ndarray | None = None - self.child_N: np.ndarray | None = None # int64, per child - self.child_W: np.ndarray | None = None # float64, child-POV total value - self.children: list[_Node | None] | None = None - - @property - def expanded(self) -> bool: - return self.moves is not None - - -class Pos2MoveV2MctsBot(Pos2MoveV2Bot): - def __init__( - self, - *args, - num_simulations: int = 800, - c_puct: float = 1.0, - prior_temp: float = 1.0, - fpu: float | None = 0.2, - sim_batch: int = 16, - tree_reuse: bool = True, - move_temp: float = 0.0, - move_temp_plies: int = 0, - **kwargs, - ): - super().__init__(*args, **kwargs) - self.num_simulations = num_simulations - self.c_puct = c_puct - # Move selection. By default the move is argmax(visit count) — fully - # deterministic (what the gauntlet / API rely on). For variety (e.g. so - # the opening isn't identical every game), set move_temp > 0 to *sample* - # the move ∝ visit_count**(1/move_temp) for the first move_temp_plies - # half-moves, then fall back to argmax. move_temp=1 samples proportional - # to visits; higher is more random. - self.move_temp = move_temp - self.move_temp_plies = move_temp_plies - # Tree reuse: keep the searched subtree under the moves actually played - # and re-root it next move, so prior visits carry over (effectively - # deeper search for free). Requires the caller to keep board.move_stack - # across calls; falls back to a fresh tree otherwise (e.g. boards rebuilt - # from FEN with no history). - self.tree_reuse = tree_reuse - self._reuse_root: _Node | None = None - self._reuse_moves: list | None = None - # prior_temp > 1 flattens the policy priors so good-but-low-prior moves - # still get explored (the value head can then promote them). fpu (first- - # play-urgency): value unvisited children as parent_Q - fpu; None keeps - # the legacy behavior (unvisited contribute 0 to selection). - self.prior_temp = prior_temp - self.fpu = fpu - # Leaves collected per network call. >1 amortizes the GPU->CPU sync that - # otherwise dominates (one stall per simulation). 1 = legacy single-leaf. - # Capped at the largest batch bucket so _batch_run's preallocated buffers - # (and the captured CUDA graphs) are never overrun. - self.sim_batch = max(1, min(sim_batch, _BATCH_BUCKETS[-1])) - - # ── expansion ──────────────────────────────────────────────────────── - def _compute_priors(self, moves: list[chess.Move], logits: np.ndarray) -> np.ndarray: - """Softmax policy priors over legal moves, with temperature flattening.""" - scores = np.array( - [ - logits[m.from_square, move_to_action_plane(m.from_square, m.to_square, m.promotion)] - for m in moves - ], - dtype=np.float64, - ) - scores /= self.prior_temp - scores -= scores.max() - exp = np.exp(scores) - return exp / exp.sum() - - def _expand_node(self, node: _Node, moves: list[chess.Move], priors: np.ndarray): - self.nodes_searched += 1 - n = len(moves) - node.moves = moves - node.priors = priors - node.child_N = np.zeros(n, dtype=np.int64) - node.child_W = np.zeros(n, dtype=np.float64) - node.children = [None] * n - - def _expand_leaf(self, node: _Node, board: chess.Board) -> float: - """Evaluate ``board`` (policy + value) and expand ``node``; return value.""" - logits, value = self._evaluate(board) - moves = list(board.legal_moves) - self._expand_node(node, moves, self._compute_priors(moves, logits)) - return value - - # ── selection / descent / backup ───────────────────────────────────── - def _select_idx(self, node: _Node) -> int: - """Vectorized PUCT: pick the child index maximizing -Q + U.""" - N = node.child_N - total = int(N.sum()) - sqrt_total = math.sqrt(1.0 + total) # +1 ≈ the node's own eval visit - # value-to-parent = -child_Q (child stores value from its own POV). - q_parent = np.zeros_like(node.child_W) - np.divide(-node.child_W, N, out=q_parent, where=N > 0) - if self.fpu is not None: - parent_q = (-node.child_W.sum() / total) if total > 0 else 0.0 - q_parent[N == 0] = parent_q - self.fpu - u = (self.c_puct * sqrt_total) * node.priors / (1.0 + N) - return int(np.argmax(q_parent + u)) - - def _descend(self, node: _Node, board: chess.Board, apply_vl: bool): - """Walk to an unexpanded leaf, pushing moves. Returns (leaf_node, path), - where path is the list of (node, child_idx) edges traversed.""" - path: list[tuple[_Node, int]] = [] - while node.expanded: - idx = self._select_idx(node) - if apply_vl: - # Virtual loss: a virtual *win* in the child's POV looks like a - # loss to this node under -Q selection, so concurrent descents in - # the batch avoid the path. - node.child_N[idx] += 1 - node.child_W[idx] += 1.0 - path.append((node, idx)) - board.push(node.moves[idx]) - child = node.children[idx] - if child is None: - child = _Node() - node.children[idx] = child - node = child - return node, path - - @staticmethod - def _backup(path: list[tuple[_Node, int]], value: float): - """Negamax backup over edges (no virtual loss).""" - v = value - for node, idx in reversed(path): - node.child_N[idx] += 1 - node.child_W[idx] += v - v = -v - - @staticmethod - def _backup_vl(path: list[tuple[_Node, int]], value: float): - """Backup that undoes the per-edge virtual loss (+1 added during descent) - and applies the real, sign-alternating value. N already counted.""" - v = value - for node, idx in reversed(path): - node.child_W[idx] += v - 1.0 - v = -v - - # ── search drivers ─────────────────────────────────────────────────── - def _simulate(self, root: _Node, board: chess.Board): - node, path = self._descend(root, board, apply_vl=False) - pushed = len(path) - term = self._terminal_value(board) - value = term if term is not None else self._expand_leaf(node, board) - self._backup(path, value) - for _ in range(pushed): - board.pop() - - def _run_batch(self, root: _Node, board: chess.Board, batch_n: int): - """Collect up to ``batch_n`` leaves (virtual loss during descent), - evaluate the unique uncached non-terminal ones in one batched forward, - then expand and back them up.""" - leaves = [] # (path, leaf_node, key, moves, cached eval or None) - items_by_key = {} # key -> (pos, player, castling, ep, key) - - for _ in range(batch_n): - node, path = self._descend(root, board, apply_vl=True) - term = self._terminal_value(board) - if term is not None: - self._backup_vl(path, term) - else: - key = chess.polyglot.zobrist_hash(board) - moves = list(board.legal_moves) - # Reuse cached policy+value (transpositions / reused subtree / - # prior moves); only batch positions we haven't evaluated yet. - # Capture the cached entry *now*: once the TT is at capacity, - # _batch_run's inserts evict oldest entries, so a hit found here - # may no longer be in the TT after the batch runs. - cached = self._tt.get(key) - if cached is not None: - self.tt_hits += 1 - elif key not in items_by_key: - pos, player, castling, ep = self._encode_position(board) - items_by_key[key] = (pos, player, castling, ep, key) - leaves.append((path, node, key, moves, cached)) - for _ in range(len(path)): - board.pop() - - if items_by_key: - self._batch_run(list(items_by_key.values())) # populates self._tt - - for path, node, key, moves, cached in leaves: - logits, value = cached if cached is not None else self._tt[key] - if not node.expanded: - self._expand_node(node, moves, self._compute_priors(moves, logits)) - self._backup_vl(path, value) - - # ── tree reuse ─────────────────────────────────────────────────────── - def _take_reuse_root(self, board: chess.Board) -> _Node | None: - """Re-root the retained tree to ``board`` if it follows the previous - search position by a few plies. Consumes the stored tree.""" - root = self._reuse_root - self._reuse_root = None - if root is None or self._reuse_moves is None: - return None - ms = board.move_stack - rp = len(self._reuse_moves) - gap = len(ms) - rp - if gap < 1 or gap > 4 or list(ms[:rp]) != self._reuse_moves: - return None - node = root - for mv in ms[rp:]: - if not node.expanded: - return None - try: - idx = node.moves.index(mv) - except ValueError: - return None - child = node.children[idx] - if child is None or not child.expanded: - return None - node = child - return node if node.expanded else None - - def predict(self, board: chess.Board) -> tuple[str, float | None]: - self.nodes_searched = 0 - self.tt_hits = 0 - self.completed_depth = self.num_simulations - - if not any(board.legal_moves): - return chess.Move.null().uci(), 0.0 - - root = self._take_reuse_root(board) if self.tree_reuse else None - if root is None: - root = _Node() - self._expand_leaf(root, board) - - if self.sim_batch <= 1: - for _ in range(self.num_simulations): - self._simulate(root, board) - else: - done = 0 - while done < self.num_simulations: - n = min(self.sim_batch, self.num_simulations - done) - self._run_batch(root, board, n) - done += n - - ply = 2 * (board.fullmove_number - 1) + (0 if board.turn == chess.WHITE else 1) - if self.move_temp > 0 and ply < self.move_temp_plies and root.child_N.sum() > 0: - # Sample ∝ visit_count**(1/temp) over the opening plies for variety. - weights = root.child_N.astype(np.float64) ** (1.0 / self.move_temp) - total = weights.sum() - best_idx = int(np.random.choice(len(weights), p=weights / total)) if total > 0 \ - else int(np.argmax(root.child_N)) - else: - best_idx = int(np.argmax(root.child_N)) - best_move = root.moves[best_idx] - n = int(root.child_N[best_idx]) - # Root value from side-to-move POV (negate child's POV). - best_value = float(-root.child_W[best_idx] / n) if n > 0 else 0.0 - - if self.tree_reuse: - self._reuse_root = root - self._reuse_moves = list(board.move_stack) - - return best_move.uci(), best_value - - -if __name__ == "__main__": - import argparse - import time - - parser = argparse.ArgumentParser() - parser.add_argument("model_dir", nargs="?", default=str(_DEFAULT_RUN)) - parser.add_argument("--sims", type=int, default=800) - parser.add_argument("--c-puct", type=float, default=1.0) - parser.add_argument("--ema", action="store_true") - args = parser.parse_args() - - bot = Pos2MoveV2MctsBot( - model_dir=args.model_dir, num_simulations=args.sims, c_puct=args.c_puct, - time_limit=0.0, use_ema=args.ema, - ) - board = chess.Board() - for _ in range(8): - t0 = time.time() - mv, val = bot.predict(board) - print(f"{'W' if board.turn else 'B'} {mv} val={val:+.3f} " - f"sims={bot.num_simulations} nodes={bot.nodes_searched} time={time.time()-t0:.2f}s") - board.push_uci(mv) - if board.is_game_over(): - break diff --git a/chesstransformer/bots/position2move_bot.py b/chesstransformer/bots/position2move_bot.py deleted file mode 100644 index ebd8b29efdc5e7b94fd342b55cbdec11a963551f..0000000000000000000000000000000000000000 --- a/chesstransformer/bots/position2move_bot.py +++ /dev/null @@ -1,88 +0,0 @@ -from pathlib import Path -import json -import torch -import chess -from safetensors import safe_open -from chesstransformer.models.transformer.position2move import Position2MoveModel -from chesstransformer.models.tokenizer import PostionTokenizer, MoveTokenizer - -data_foler = Path(__file__).parents[1] / "data" - - -class Position2MoveBot: - def __init__( - self, - model_path: str = str((data_foler / "models/position2moveV2.1/best_model/model.safetensors").resolve()), - device: str = "cpu", - ): - self.device = device - self.position_tokenizer = PostionTokenizer() - self.move_tokenizer = MoveTokenizer() - - config_path = Path(model_path).parent / "config.json" - - with open(config_path, "r") as f: - self.config = json.load(f) - - # Load model - self.model = Position2MoveModel(**self.config).to(device) - - with safe_open(model_path, framework="pt", device=device) as f: - state_dict = {k: f.get_tensor(k) for k in f.keys()} - - # Handle compiled model prefix (_orig_mod.) - if any(k.startswith("_orig_mod.") for k in state_dict.keys()): - state_dict = {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()} - - self.model.load_state_dict(state_dict) - - self.model.eval() - - @torch.no_grad() - def predict(self, board: chess.Board): - tokens_ids = self.position_tokenizer.encode(board) - torch_input = torch.tensor(tokens_ids).unsqueeze(0).long().to(self.device) # Add batch dimension - - is_white = board.turn - is_white = torch.tensor([is_white]).bool().to(self.device) # Add batch dimension - - logits = self.model(torch_input, is_white) - - legal_moves = [m.uci() for m in board.legal_moves] - - mask = torch.full((logits.size(-1),), float("-inf")).to(self.device) - for move in legal_moves: - move_id = self.move_tokenizer.encode(move) - mask[move_id] = 0.0 - - masked_logits = logits[0] + mask # Assuming batch size of 1 - probs = torch.softmax(masked_logits, dim=-1) - # draw the move from the distribution - predicted_move_id = torch.multinomial(probs * 0.2, num_samples=1).item() - proba = probs[predicted_move_id].item() - - predicted_move = self.move_tokenizer.decode(predicted_move_id) - return predicted_move, proba - - -if __name__ == "__main__": - bot = Position2MoveBot() - - board = chess.Board() - - print("Initial board:") - print(board) - - move, proba = bot.predict(board) - print(f"Bot suggests move: {move} with probability {proba:.4f}") - - board.push_uci(move) - print("Board after bot move:") - print(board) - - move, proba = bot.predict(board) - print(f"Bot suggests move: {move} with probability {proba:.4f}") - - board.push_uci(move) - print("Board after bot move:") - print(board) diff --git a/chesstransformer/bots/random_bot.py b/chesstransformer/bots/random_bot.py deleted file mode 100644 index 4075696d23cdbfcfbc6b512051c6a06985f0a498..0000000000000000000000000000000000000000 --- a/chesstransformer/bots/random_bot.py +++ /dev/null @@ -1,33 +0,0 @@ -import chess -import random - - -class RandomBot: - def __init__(self): - pass - - def predict(self, board: chess.Board) -> chess.Move: - legal_moves = list(board.legal_moves) - if not legal_moves: - raise ValueError("No legal moves available.") - # pick a random move - move = random.choice(legal_moves) - return move.uci(), None - - -if __name__ == "__main__": - bot = RandomBot() - board = chess.Board() - print("Initial board:") - print(board) - move = bot.predict(board) - print(f"RandomBot suggests move: {move}") - board.push(move) - print("Board after move:") - print(board) - - move = bot.predict(board) - print(f"RandomBot suggests move: {move}") - board.push(move) - print("Board after move:") - print(board) diff --git a/chesstransformer/datasets/__init__.py b/chesstransformer/datasets/__init__.py deleted file mode 100644 index 6b1c05cc18b81d6d340f8199987293ed40c12b2f..0000000000000000000000000000000000000000 --- a/chesstransformer/datasets/__init__.py +++ /dev/null @@ -1,10 +0,0 @@ -from .lichess import LichessDataset -from .lichess_simple_uci import LichessSimpleUciDataset -from .puzzle_dataset import LichessPuzzleDataset, LichessPuzzleFullSolutionDataset - -__all__ = [ - "LichessDataset", - "LichessSimpleUciDataset", - "LichessPuzzleDataset", - "LichessPuzzleFullSolutionDataset", -] diff --git a/chesstransformer/datasets/dataset_h5_convertor.py b/chesstransformer/datasets/dataset_h5_convertor.py deleted file mode 100644 index 36759a65bbe91aa5e26bf7fb4ad6c4964a2f0adb..0000000000000000000000000000000000000000 --- a/chesstransformer/datasets/dataset_h5_convertor.py +++ /dev/null @@ -1,404 +0,0 @@ -import h5py -import chess.pgn -import zstandard as zstd -import numpy as np -from tqdm import tqdm -from multiprocessing import Pool, cpu_count -from chesstransformer.models.tokenizer.move_tokenizer import MoveTokenizer -import io -from pathlib import Path - -# Per-worker globals initialised once per process -_worker_tokenizer = None -_worker_exclude_tcs = [] - - -def _worker_init(exclude_tcs): - global _worker_tokenizer, _worker_exclude_tcs - _worker_tokenizer = MoveTokenizer() - _worker_exclude_tcs = exclude_tcs - - -def _process_raw_game(raw_pgn: str): - """Full pipeline in each worker: text-filter → parse → tokenize. - - Moving parse into workers parallelises the most expensive step. - The fast text-level filter avoids even calling chess.pgn.read_game - for excluded time controls. - """ - global _worker_tokenizer, _worker_exclude_tcs - - # Fast text-level filter before expensive PGN parsing - if _worker_exclude_tcs: - idx = raw_pgn.find('[Event "') - if idx >= 0: - end = raw_pgn.find('"]', idx + 8) - if end >= 0: - event_lower = raw_pgn[idx + 8 : end].lower() - if any(tc in event_lower for tc in _worker_exclude_tcs): - return None - - game = chess.pgn.read_game(io.StringIO(raw_pgn)) - if game is None: - return None - - if game.headers.get("Variant", "Standard") != "Standard": - return None - - result_str = game.headers.get("Result", "*") - if result_str == "1/2-1/2": - result = 0 - elif result_str == "1-0": - result = 1 - elif result_str == "0-1": - result = 2 - else: - return None - - try: - white_elo = int(game.headers.get("WhiteElo", "1500")) - except ValueError: - white_elo = 1500 - try: - black_elo = int(game.headers.get("BlackElo", "1500")) - except ValueError: - black_elo = 1500 - - tokens = [] - for move in game.mainline_moves(): - try: - tokens.append(_worker_tokenizer.encode(move.uci())) - except ValueError: - return None - - if len(tokens) < 10: - return None - - return np.array(tokens, dtype=np.int16), white_elo, black_elo, result, len(tokens) - - -def _iter_raw_games(stream): - """Yield individual PGN game strings from a text stream. - - Splits on '[Event' lines, which always start each game in standard PGN. - Line-by-line reading keeps memory usage constant regardless of file size. - """ - buf = [] - for line in stream: - if line.startswith("[Event ") and buf: - yield "".join(buf) - buf = [line] - else: - buf.append(line) - if buf: - text = "".join(buf).strip() - if text: - yield text - - -class PGNtoHDF5Converter: - def __init__( - self, - output_path: str, - chunk_size: int = 10000, - num_workers: int = None, - exclude_time_controls: list = None, - ): - """ - Convert PGN files to HDF5 format storing complete games as UCI move sequences. - - Args: - output_path: Path to save the HDF5 file - chunk_size: Number of games to accumulate before writing (default: 10000) - exclude_time_controls: List of time control categories to skip, matched against - the Lichess Event header (e.g. ["Bullet", "Blitz", "UltraBullet"]) - """ - self.output_path = output_path - self.chunk_size = chunk_size - default_workers = (cpu_count() or 1) - 1 - self.num_workers = max(1, num_workers if num_workers is not None else max(1, default_workers)) - self.exclude_time_controls = [tc.lower() for tc in (exclude_time_controls or [])] - - def convert(self, input_path: str, max_games: int = None): - """Convert PGN files to HDF5. Input can be a file or folder.""" - path = Path(input_path) - if not path.exists(): - raise FileNotFoundError(f"Path not found: {input_path}") - if path.is_file(): - self._convert_single_file(path, max_games) - elif path.is_dir(): - self._convert_folder(path, max_games) - else: - raise ValueError(f"Invalid input path: {input_path}") - - def _convert_folder(self, folder_path: Path, max_games: int = None): - pgn_files = sorted(list(folder_path.glob("*.pgn")) + list(folder_path.glob("*.pgn.zst"))) - if not pgn_files: - raise ValueError(f"No PGN files found in {folder_path}") - - done = self._completed_files() - pending = [f for f in pgn_files if f.name not in done] - - print(f"Found {len(pgn_files)} PGN file(s) in {folder_path}") - if done: - print(f"Resuming: {len(done)} already converted, {len(pending)} remaining") - for f in pending: - print(f" - {f.name}") - print() - - if not pending: - print("Nothing to do — every file is already in the output.") - return 0 - - total_games = 0 - started = bool(done) - for pgn_file in pending: - remaining = None if max_games is None else max(0, max_games - total_games) - if remaining == 0: - break - print(f"\nProcessing: {pgn_file.name}") - total_games += self._convert_single_file(pgn_file, remaining, append=started) - started = True - if max_games and total_games >= max_games: - print(f"\nReached maximum game limit ({max_games})") - break - - print(f"\n{'=' * 60}") - print(f"All files processed! Total games: {total_games}") - print(f"Output: {self.output_path}") - - def _convert_single_file(self, pgn_path: Path, max_games: int = None, append: bool = False): - if pgn_path.suffix == ".zst" or pgn_path.name.endswith(".pgn.zst"): - return self._convert_compressed_file(str(pgn_path), max_games, append) - else: - return self._convert_uncompressed_file(str(pgn_path), max_games, append) - - def convert_pgn_zst(self, pgn_path: str, max_games: int = None): - """Deprecated: Use convert() instead.""" - return self._convert_compressed_file(pgn_path, max_games, append=False) - - # ------------------------------------------------------------------ - # Internal helpers - # ------------------------------------------------------------------ - - _DATASET_NAMES = ("moves", "white_elo", "black_elo", "result", "num_moves") - - def _completed_files(self) -> list[str]: - """Names of PGN files already fully written into the output, for resume.""" - path = Path(self.output_path) - if not path.exists(): - return [] - try: - with h5py.File(path, "r") as f: - return [str(n) for n in f.attrs.get("converted_files", [])] - except OSError: - return [] - - def _mark_converted(self, hdf5_file, name: str): - """Commit a finished PGN file: record its name and the row watermark.""" - done = [str(n) for n in hdf5_file.attrs.get("converted_files", [])] - if name not in done: - done.append(name) - hdf5_file.attrs["converted_files"] = np.array(done, dtype=h5py.string_dtype()) - hdf5_file.attrs["committed_rows"] = int(min(hdf5_file[n].shape[0] for n in self._DATASET_NAMES)) - - def _rewind_to_watermark(self, hdf5_file): - """Discard everything written after the last fully converted PGN file. - - Length agreement is not enough to detect an interrupted run: `_write_batch` - resizes all five datasets before writing any of them, so a crash mid-batch - leaves them equal-length with a junk tail. Worse, the rows a dead run *did* - write would be duplicated when its PGN file — never added to `converted_files` - — gets reconverted. Rewinding to the committed watermark drops both. - """ - lengths = {n: hdf5_file[n].shape[0] for n in self._DATASET_NAMES} - mark = int(hdf5_file.attrs.get("committed_rows", -1)) - if mark < 0: # written before watermarks existed; fall back to length agreement - mark = min(lengths.values()) - if any(length != mark for length in lengths.values()): - print(f"Rewinding interrupted output: {lengths} -> {mark} rows") - for name in self._DATASET_NAMES: - hdf5_file[name].resize((mark,)) - - def _create_datasets(self, hdf5_file): - """Create all HDF5 datasets (called only when not appending).""" - dt = h5py.vlen_dtype(np.dtype("int16")) - for name, dtype in [ - ("moves", dt), - ("white_elo", "int16"), - ("black_elo", "int16"), - ("result", "int8"), - ("num_moves", "int16"), - ]: - hdf5_file.create_dataset( - name, - shape=(0,), - maxshape=(None,), - dtype=dtype, - compression="gzip", - compression_opts=4, - chunks=(self.chunk_size,), - ) - - def _write_batch(self, hdf5_file, games, white_elos, black_elos, results, num_moves): - old = hdf5_file["moves"].shape[0] - new = old + len(games) - for ds in ("moves", "white_elo", "black_elo", "result", "num_moves"): - hdf5_file[ds].resize((new,)) - # One slice assignment, not one write per game: each per-game write re-read and - # re-compressed the whole gzip chunk, costing ~1 ms/game in the main process and - # starving the workers. - moves_arr = np.empty(len(games), dtype=object) - moves_arr[:] = games - try: - hdf5_file["moves"][old:new] = moves_arr - except TypeError: - # h5py re-normalises the object array internally, and when every game in the - # batch happens to have the same length (always so for a single game) that - # collapses it to 2-D and the vlen write is refused. Only degenerate batches - # hit this — typically the 1-game remainder of a file's final flush — so the - # slow path costs nothing in practice. - for i, g in enumerate(games): - hdf5_file["moves"][old + i] = g - hdf5_file["white_elo"][old:new] = np.array(white_elos, dtype=np.int16) - hdf5_file["black_elo"][old:new] = np.array(black_elos, dtype=np.int16) - hdf5_file["result"][old:new] = np.array(results, dtype=np.int8) - hdf5_file["num_moves"][old:new] = np.array(num_moves, dtype=np.int16) - - def _run_conversion(self, stream, hdf5_file, max_games) -> tuple[int, int]: - """Core loop: stream raw PGN text → workers parse+tokenize → write HDF5. - - Returns (game_count, total_positions). - """ - game_count = 0 - total_positions = 0 - games_buf, we_buf, be_buf, res_buf, nm_buf = [], [], [], [], [] - - pbar = tqdm(desc="Processing games", unit="games") - - def flush(): - if games_buf: - self._write_batch(hdf5_file, games_buf, we_buf, be_buf, res_buf, nm_buf) - games_buf.clear(); we_buf.clear(); be_buf.clear() - res_buf.clear(); nm_buf.clear() - - def accumulate(result): - nonlocal game_count, total_positions - token_array, we, be, res, nm = result - games_buf.append(token_array) - we_buf.append(we); be_buf.append(be) - res_buf.append(res); nm_buf.append(nm) - total_positions += nm - game_count += 1 - pbar.update(1) - if len(games_buf) >= self.chunk_size: - flush() - - use_parallel = self.num_workers > 1 - raw_iter = _iter_raw_games(stream) - - if use_parallel: - pool = Pool( - processes=self.num_workers, - initializer=_worker_init, - initargs=(self.exclude_time_controls,), - ) - early_stop = False - try: - # imap_unordered streams results as soon as each worker finishes — - # no need to wait for a full chunk_size batch before seeing progress. - for result in pool.imap_unordered(_process_raw_game, raw_iter, chunksize=200): - if result is None: - continue - accumulate(result) - if max_games and game_count >= max_games: - early_stop = True - break - finally: - if early_stop: - pool.terminate() - else: - pool.close() - pool.join() - else: - # Sequential fallback (single worker) - _worker_init(self.exclude_time_controls) - for raw_pgn in raw_iter: - result = _process_raw_game(raw_pgn) - if result is None: - continue - accumulate(result) - if max_games and game_count >= max_games: - break - - flush() - pbar.close() - return game_count, total_positions - - def _convert_compressed_file(self, pgn_path: str, max_games: int = None, append: bool = False): - with open(pgn_path, "rb") as f: - dctx = zstd.ZstdDecompressor() - with dctx.stream_reader(f) as reader: - stream = io.TextIOWrapper(reader, encoding="utf-8") - mode = "a" if append else "w" - with h5py.File(self.output_path, mode) as hdf5_file: - if append and "moves" in hdf5_file: - self._rewind_to_watermark(hdf5_file) - else: - self._create_datasets(hdf5_file) - game_count, total_positions = self._run_conversion(stream, hdf5_file, max_games) - if not max_games or game_count < max_games: - self._mark_converted(hdf5_file, Path(pgn_path).name) - - self._print_summary(game_count, total_positions) - return game_count - - def _convert_uncompressed_file(self, pgn_path: str, max_games: int = None, append: bool = False): - with open(pgn_path, "r", encoding="utf-8") as pgn_file: - mode = "a" if append else "w" - with h5py.File(self.output_path, mode) as hdf5_file: - if append and "moves" in hdf5_file: - self._rewind_to_watermark(hdf5_file) - else: - self._create_datasets(hdf5_file) - game_count, total_positions = self._run_conversion(pgn_file, hdf5_file, max_games) - if not max_games or game_count < max_games: - self._mark_converted(hdf5_file, Path(pgn_path).name) - - self._print_summary(game_count, total_positions) - return game_count - - def _print_summary(self, game_count, total_positions): - print("File conversion complete!") - print(f"Games from this file: {game_count}") - print(f"Positions from this file: {total_positions}") - avg = (total_positions / game_count) if game_count else 0.0 - print(f"Average moves per game: {avg:.1f}") - - -# Usage script -if __name__ == "__main__": - import argparse - - parser = argparse.ArgumentParser(description="Convert PGN/PGN.zst file(s) or folder to HDF5") - parser.add_argument("--input", type=str, required=True, help="Input .pgn/.pgn.zst file or folder") - parser.add_argument("--output", type=str, required=True, help="Output .h5 file") - parser.add_argument("--max-games", type=int, default=None, help="Maximum games to process") - parser.add_argument("--chunk-size", type=int, default=10000, help="Batch size for writing") - parser.add_argument("--num-workers", type=int, default=None, help="Worker processes (default: cpu count - 1)") - parser.add_argument( - "--exclude-time-controls", - nargs="+", - default=[], - metavar="TC", - help="Time control categories to skip (e.g. Bullet Blitz UltraBullet)", - ) - - args = parser.parse_args() - converter = PGNtoHDF5Converter( - args.output, - chunk_size=args.chunk_size, - num_workers=args.num_workers, - exclude_time_controls=args.exclude_time_controls, - ) - converter.convert(args.input, max_games=args.max_games) diff --git a/chesstransformer/datasets/flat_shard_dataset.py b/chesstransformer/datasets/flat_shard_dataset.py deleted file mode 100644 index be373fe73889af294018cb1b2fc6cd14c4a3d66d..0000000000000000000000000000000000000000 --- a/chesstransformer/datasets/flat_shard_dataset.py +++ /dev/null @@ -1,231 +0,0 @@ -"""Memmap-backed dataset over the flat shards written by ``scripts/build_shards.py``. - -Implements ``doc/dataset_shards.md`` §4. Every expensive thing ``HDF5ChessDataset`` does -per sample — gzip decompression, python-chess replay, legal-move enumeration, tokenizing — -has already been paid at build time. What is left here is a numpy gather out of page cache. - -Two decisions carry most of the speed: - -**Batch-level fetch.** At 202 bytes per sample the per-item Python call overhead dominates -the actual work, so ``__getitem__`` accepts a *list* of indices and does one vectorised -gather per batch. Drive it with :func:`make_dataloader`, which wires up a ``BatchSampler`` -and ``batch_size=None`` so the DataLoader hands the whole index list through untouched. - -**The legal mask is not built on CPU.** Returning ``(64, 73)`` bools would put 2.4 MB per -batch of 512 back on the H2D wire — the exact cost the shard format exists to remove. The -loader ships the ``(B, 64)`` uint16 index list (64 KB) and the training loop calls -:func:`scatter_legal_planes` on device. - -**Distributed use.** This is a map-style dataset, so rank splitting is -``DistributedSampler``'s job, not the dataset's — see :func:`make_dataloader`. Map-style + -``DistributedSampler`` is preferred over an ``IterableDataset`` that owns shard *k* when -``k % (world_size * num_workers) == rank * num_workers + worker`` because the latter can -only shuffle within a worker's own shards: sample correlation then survives into the batch, -and the assignment silently unbalances whenever ``world_size * num_workers`` does not -divide the shard count. The shards here are a build-parallelism and train/val/test-split -unit; they deliberately do not constrain who reads what. -""" - -import json -import os -from pathlib import Path - -import numpy as np -import torch -from torch.utils.data import BatchSampler, DataLoader, RandomSampler, SequentialSampler - -from chesstransformer.datasets.shard_format import ( - FORMAT_VERSION, - NUM_ACTION_PLANES, - NUM_SQUARES, - PAD_ACTION, - dtype_from_meta, -) - -#: Fields handed to the trainer, in the dtype the model wants them in. Kept narrow on the -#: wire (uint8/int16) and widened on device — an int64 ``position`` would be 8x the copy -#: for an embedding lookup that accepts int32 anyway. -_SCALAR_FIELDS = ("from_square", "action_plane", "castling_rights", "en_passant_file", "is_white") - - -class FlatShardDataset(torch.utils.data.Dataset): - """One split of a shard directory, as one addressable array of samples.""" - - def __init__(self, shard_dir: str | Path, split: str = "train"): - self.shard_dir = Path(shard_dir) - self.split = split - - with (self.shard_dir / "meta.json").open() as fh: - self.meta = json.load(fh) - - if self.meta["format_version"] != FORMAT_VERSION: - raise ValueError( - f"{self.shard_dir} was built with format_version " - f"{self.meta['format_version']}, this code reads {FORMAT_VERSION}. Rebuild." - ) - - if split not in self.meta["splits"]: - raise KeyError(f"unknown split {split!r}; have {list(self.meta['splits'])}") - - self.dtype = dtype_from_meta(self.meta["record_dtype"]) - self.pad_action = int(self.meta["pad_action"]) - - wanted = set(self.meta["splits"][split]) - self.shard_meta = [m for m in self.meta["shards"] if m["shard_id"] in wanted] - if not self.shard_meta: - raise ValueError(f"split {split!r} of {self.shard_dir} is empty") - - # Cumulative offsets: a global index resolves to (shard, row) with one searchsorted. - counts = np.array([m["num_samples"] for m in self.shard_meta], dtype=np.int64) - self.offsets = np.concatenate([[0], np.cumsum(counts)]) - self._len = int(self.offsets[-1]) - - # Opened lazily, per process. np.memmap survives fork harmlessly, but building the - # handles in __init__ would map every shard in the parent for no reason. - self._shards = None - self._shards_pid = None - - # The whole point of memmap is that the page cache holds one copy that all workers - # share. np.load(...) without mmap_mode would give each of N workers its own. - self.game_ranges = [(m["game_start"], m["game_end"]) for m in self.shard_meta] - - def __len__(self): - return self._len - - @property - def shards(self): - pid = os.getpid() - if self._shards is None or self._shards_pid != pid: - self._shards = [ - np.load(self.shard_dir / m["path"], mmap_mode="r") for m in self.shard_meta - ] - self._shards_pid = pid - return self._shards - - def __getstate__(self): - state = self.__dict__.copy() - state["_shards"] = None - state["_shards_pid"] = None - return state - - def _gather(self, idx: np.ndarray) -> np.ndarray: - """Fetch records for a batch of global indices, preserving their order.""" - shard_of = np.searchsorted(self.offsets, idx, side="right") - 1 - rows = idx - self.offsets[shard_of] - - shards = self.shards - out = np.empty(len(idx), dtype=self.dtype) - for sid in np.unique(shard_of): - where = np.nonzero(shard_of == sid)[0] - r = rows[where] - # Read each shard in ascending row order: sequential page touches, even though - # the batch itself is shuffled. - order = np.argsort(r, kind="stable") - out[where[order]] = shards[sid][r[order]] - return out - - def __getitem__(self, index): - """Accepts a single index or — the fast path — a list/array of them.""" - if isinstance(index, (int, np.integer)): - batch = self._gather(np.array([index], dtype=np.int64)) - else: - batch = self._gather(np.asarray(index, dtype=np.int64)) - - # Everything stays at its on-disk width. A batch of 512 is then 103 KB rather than - # the 5.81 MB the HDF5 path collates, and the widening to int64/bool happens on - # device in the trainer's unpack_batch, where it is free. - # - # int16 rather than uint16 for the two u2 fields because torch has no uint16; both - # are safely in range (legal_idx <= 4672, move_number max observed 601). - out = { - "position": torch.from_numpy(np.ascontiguousarray(batch["position"])), - "legal_idx": torch.from_numpy(np.ascontiguousarray(batch["legal_idx"]).astype(np.int16)), - "legal_cnt": torch.from_numpy(np.ascontiguousarray(batch["legal_cnt"])), - "result": torch.from_numpy(np.ascontiguousarray(batch["result"])), - "move_number": torch.from_numpy( - np.ascontiguousarray(batch["move_number"]).astype(np.int16) - ), - } - for name in _SCALAR_FIELDS: - out[name] = torch.from_numpy(np.ascontiguousarray(batch[name])) - return out - - def game_id_set(self) -> set: - """Game indices this split covers. Used by the split-disjointness assertion.""" - ids = set() - for g0, g1 in self.game_ranges: - ids.update(range(g0, g1)) - return ids - - -def scatter_legal_planes(legal_idx: torch.Tensor, pad_action: int = PAD_ACTION) -> torch.Tensor: - """Rebuild the ``(B, 64, 73)`` bool legal mask from the packed index list, on device. - - ``legal_idx`` is ``(B, C)`` with unused slots set to ``pad_action`` (== 64*73), one past - the end of the action space. Scattering into a tensor with one extra column parks that - padding in a scratch slot which is then sliced off — if padding were 0 instead, every - sample would come back with square a1 / plane 0 marked legal. - """ - b = legal_idx.size(0) - flat = torch.zeros(b, pad_action + 1, dtype=torch.bool, device=legal_idx.device) - flat.scatter_(1, legal_idx.long(), True) - return flat[:, :pad_action].view(b, NUM_SQUARES, NUM_ACTION_PLANES) - - -def worker_init_fn(worker_id: int): - """Give every worker (and every rank) its own numpy RNG stream. - - PyTorch reseeds ``random`` and ``torch`` per worker but *not* ``numpy``, so all workers - inherit the parent's numpy state and draw the identical sequence — and under DDP so - would every rank. Nothing in this dataset's hot path uses ``np.random`` any more, but - ``HDF5ChessDataset._sample_move_idx`` does, and the fix belongs wherever a worker starts. - """ - rank = int(os.environ.get("RANK", 0)) - np.random.seed((torch.initial_seed() + 977 * rank) % (2**32)) - - -def make_dataloader( - dataset: FlatShardDataset, - batch_size: int, - shuffle: bool, - num_workers: int = 4, - drop_last: bool = False, - pin_memory: bool = True, - prefetch_factor: int = 4, - seed: int = 0, - distributed: bool = False, -) -> DataLoader: - """Build the batch-fetch DataLoader this dataset is designed for. - - ``batch_size=None`` disables the DataLoader's own batching so the ``BatchSampler``'s - index *list* reaches ``__getitem__`` intact and the gather happens once per batch - rather than once per sample. Without this the dataset still works and runs roughly an - order of magnitude slower. - - ``distributed=True`` wraps a ``DistributedSampler`` so each rank sees a disjoint - 1/world_size of the split. Remember to call ``loader.sampler.sampler.set_epoch(epoch)`` - — the BatchSampler nests it one level down. - """ - if distributed: - from torch.utils.data import DistributedSampler - - inner = DistributedSampler(dataset, shuffle=shuffle, seed=seed, drop_last=drop_last) - elif shuffle: - generator = torch.Generator() - generator.manual_seed(seed) - inner = RandomSampler(dataset, generator=generator) - else: - inner = SequentialSampler(dataset) - - sampler = BatchSampler(inner, batch_size=batch_size, drop_last=drop_last) - - return DataLoader( - dataset, - batch_size=None, - sampler=sampler, - num_workers=num_workers, - pin_memory=pin_memory, - persistent_workers=num_workers > 0, - prefetch_factor=prefetch_factor if num_workers > 0 else None, - worker_init_fn=worker_init_fn, - ) diff --git a/chesstransformer/datasets/h5_lichess_dataset.py b/chesstransformer/datasets/h5_lichess_dataset.py deleted file mode 100644 index 817442c6d2431d307684e39058b2bc75acf0a0c1..0000000000000000000000000000000000000000 --- a/chesstransformer/datasets/h5_lichess_dataset.py +++ /dev/null @@ -1,295 +0,0 @@ -import os - -import h5py -import torch -from torch.utils.data import Dataset -import numpy as np -import chess -from chesstransformer.models.tokenizer.position_tokenizer import PostionTokenizer -from chesstransformer.models.tokenizer.move_tokenizer import MoveTokenizer -from chesstransformer.models.tokenizer.alphazero_move_encoder import ( - move_to_action_plane, - NUM_ACTION_PLANES, -) - - -class HDF5ChessDataset(Dataset): - def __init__( - self, - hdf5_path: str, - cache_size: int = 500, - min_elo: int = None, - max_elo: int = None, - sample_weighting: str = "middlegame", - skip_opening_plies: int = 0, - rdcc_nbytes: int = 32 << 20, - ): - """ - Efficient dataset that loads games as UCI sequences and samples random positions. - - Each dataset index corresponds to one game. When a sample is requested, it: - 1. Uses the index to select a game - 2. Samples a position within that game (uniform or phase-weighted) - 3. Replays the game to that position to get the board state - 4. Returns the encoded board state + the next move - - Args: - hdf5_path: Path to HDF5 file containing games - cache_size: Number of games to cache in memory - min_elo: Minimum average ELO for filtering games (optional) - max_elo: Maximum average ELO for filtering games (optional) - sample_weighting: "uniform" (legacy) or "middlegame" (triangular peak around move 25) - skip_opening_plies: Force sampling to start at this ply (0 = no restriction) - rdcc_nbytes: HDF5 chunk cache per dataset. ``moves`` is gzipped in chunks of - 10,000 games, so a random read decompresses a whole chunk; h5py's 1 MB - default cannot hold one and every read pays full decompression. 32 MB - takes a random ``moves[g]`` from 0.22 ms to 0.12 ms. - """ - self.hdf5_path = hdf5_path - self.cache_size = cache_size - self.game_cache = {} # Cache for game move sequences - self.position_tokenizer = PostionTokenizer() - self.move_tokenizer = MoveTokenizer() - self.sample_weighting = sample_weighting - self.skip_opening_plies = skip_opening_plies - self.rdcc_nbytes = rdcc_nbytes - - # Long-lived read handle, opened lazily by _h5(). See the note there for why - # this must never be opened in __init__. - self._file = None - self._file_pid = None - - # Load metadata and filter games by ELO - with h5py.File(hdf5_path, "r") as f: - self.num_games = f["moves"].shape[0] - num_moves = f["num_moves"][:] - white_elos = f["white_elo"][:] - black_elos = f["black_elo"][:] - results = f["result"][:] - - # Filter games by ELO if specified - valid_games = np.ones(self.num_games, dtype=bool) - if min_elo is not None or max_elo is not None: - avg_elos = (white_elos + black_elos) / 2 - if min_elo is not None: - valid_games &= avg_elos >= min_elo - if max_elo is not None: - valid_games &= avg_elos <= max_elo - - # Store valid game indices and their move counts - self.valid_game_indices = np.where(valid_games)[0] - self.num_moves_per_game = num_moves[valid_games] - - # Per-game metadata stays in RAM: 1.53M games is 1.5 MB of int8 plus - # 3 MB of int16, and reading these three scalars back out of HDF5 per - # sample cost more than the game decode itself. Kept *unfiltered*, so - # they are indexed by the actual game index, not the dataset index. - self.white_elos = white_elos - self.black_elos = black_elos - self.results = results - - total_positions = int(self.num_moves_per_game.sum()) - print(f"Loaded dataset: {len(self.valid_game_indices)} games with {total_positions} total positions") - if min_elo or max_elo: - print(f"Filtered by ELO: {min_elo or 0} - {max_elo or 'inf'}") - - def __len__(self): - """Return the number of games in the dataset.""" - return len(self.valid_game_indices) - - def _sample_move_idx(self, max_move_idx: int) -> int: - """Sample a position index within a game. - - - "uniform": legacy behavior, np.random.randint(0, max_move_idx) - - "middlegame": triangular weight peaking around ply 25, - downweights opening (rare unique positions) and very late - endgame (sparse signal). Falls back to uniform for short games. - - Optionally enforces ``skip_opening_plies`` as a hard floor. - """ - lo = min(self.skip_opening_plies, max_move_idx - 1) if max_move_idx > 1 else 0 - hi = max_move_idx # exclusive upper bound - - if self.sample_weighting == "uniform" or hi - lo <= 8: - return int(np.random.randint(lo, hi)) - - # Triangular weights: ramp up over plies 0->20, flat 20-40, taper 40->80 - plies = np.arange(lo, hi) - ramp_up = np.minimum(plies / 20.0, 1.0) - taper = np.minimum(np.maximum((80.0 - plies) / 40.0, 0.1), 1.0) - weights = ramp_up * taper - weights = weights / weights.sum() - return int(np.random.choice(plies, p=weights)) - - def _h5(self) -> h5py.File: - """Return this *process's* HDF5 handle, opening it on first use. - - Deliberately not opened in ``__init__``. DataLoader workers are forked, and - HDF5 is not fork-safe: a handle inherited across ``fork()`` is shared library - state that two processes then mutate independently. It does not raise — it - returns corrupted data or deadlocks, which is far worse. Opening on first - ``__getitem__`` means every worker gets its own handle after the fork. - - The PID check covers the case where the parent process reads a sample (e.g. - ``num_workers=0``, or a shape probe) before spawning workers, which would - otherwise leave an open handle for the children to inherit. - """ - pid = os.getpid() - if self._file is None or self._file_pid != pid: - self._file = h5py.File( - self.hdf5_path, - "r", - rdcc_nbytes=self.rdcc_nbytes, - rdcc_nslots=10007, # prime, comfortably > chunks held in the cache - ) - self._file_pid = pid - return self._file - - def __getstate__(self): - """Drop the handle when pickled (``spawn`` start method); h5py.File is not - picklable and each process must open its own anyway.""" - state = self.__dict__.copy() - state["_file"] = None - state["_file_pid"] = None - return state - - def _get_game_moves(self, game_idx: int) -> np.ndarray: - """Load and cache a game's move sequence. - - Only ``moves`` comes from HDF5; the per-game scalars live in RAM (see __init__). - """ - if game_idx in self.game_cache: - return self.game_cache[game_idx] - - moves = self._h5()["moves"][game_idx] - - # Update cache (simple LRU-like behavior) - if len(self.game_cache) >= self.cache_size: - # Remove oldest item - self.game_cache.pop(next(iter(self.game_cache))) - - self.game_cache[game_idx] = moves - return moves - - def __getitem__(self, idx): - """ - Returns a position-move pair by: - 1. Using idx to select a game - 2. Uniformly sampling a random position within that game - 3. Replaying the game to get the board state - 4. Returning encoded board + next move - """ - # Map dataset index to actual game index - actual_game_idx = self.valid_game_indices[idx] - - # Load game moves; the scalars are RAM lookups (indexed by actual game index) - game_moves = self._get_game_moves(actual_game_idx) - white_elo = int(self.white_elos[actual_game_idx]) - black_elo = int(self.black_elos[actual_game_idx]) - result = int(self.results[actual_game_idx]) - num_moves = self.num_moves_per_game[idx] - - # Uniformly sample a position within the game (exclude last move - no next move) - max_move_idx = num_moves - 1 - if max_move_idx <= 0: - # Edge case: game with only one move, use position 0 - move_idx = 0 - else: - move_idx = self._sample_move_idx(int(max_move_idx)) - - # Replay game to position - board = chess.Board() - for i in range(move_idx): - # Decode move token to UCI string - move_token = int(game_moves[i]) - move_uci = self._decode_move_token(move_token) - try: - move = chess.Move.from_uci(move_uci) - board.push(move) - except (ValueError, AssertionError): - # If move is invalid, skip to next position - # This shouldn't happen with properly encoded data - pass - - # Encode current position - position = self.position_tokenizer.encode(board) - position_tensor = torch.tensor(position, dtype=torch.long) - - legal_moves_planes = torch.zeros(64, NUM_ACTION_PLANES, dtype=torch.bool) - for move in board.legal_moves: - plane = move_to_action_plane(move.from_square, move.to_square, move.promotion) - legal_moves_planes[move.from_square, plane] = True - - # Get next move - next_move_token = torch.tensor(int(game_moves[move_idx]), dtype=torch.long) - - # Parse next move for grid format (from/to squares + promotion) - next_move_uci = self._decode_move_token(int(game_moves[move_idx])) - next_move = chess.Move.from_uci(next_move_uci) - from_square = next_move.from_square - to_square = next_move.to_square - - # AlphaZero action plane for this move - action_plane = move_to_action_plane(from_square, to_square, next_move.promotion) - - # Get turn indicator - is_white = board.turn # True for white, False for black - - # Get castling rights as a single integer (0-15) - # Bit 0: white kingside, Bit 1: white queenside, Bit 2: black kingside, Bit 3: black queenside - castling_rights = 0 - if board.has_kingside_castling_rights(chess.WHITE): - castling_rights |= 1 - if board.has_queenside_castling_rights(chess.WHITE): - castling_rights |= 2 - if board.has_kingside_castling_rights(chess.BLACK): - castling_rights |= 4 - if board.has_queenside_castling_rights(chess.BLACK): - castling_rights |= 8 - - # Get en passant file (0-7 for a-h, 8 for none) - if board.has_legal_en_passant(): - en_passant_file = chess.square_file(board.ep_square) - else: - en_passant_file = 8 # No en passant - - return { - "position": position_tensor, - "move": next_move_token, - "is_white": is_white, - "castling_rights": castling_rights, - "en_passant_file": en_passant_file, - "move_number": move_idx, - "white_elo": white_elo, - "black_elo": black_elo, - "result": result, - "from_square": from_square, - "action_plane": action_plane, - "legal_moves_planes": legal_moves_planes, - } - - def _decode_move_token(self, token: int) -> str: - """Decode a move token back to UCI string.""" - return self.move_tokenizer.decode(token) - - -if __name__ == "__main__": - # Example usage - import sys - - if len(sys.argv) < 2: - print("Usage: python h5_lichess_dataset.py ") - sys.exit(1) - - dataset = HDF5ChessDataset(sys.argv[1], cache_size=100) - print(f"Dataset length: {len(dataset)}") - - # Test a few samples - for i in range(min(5, len(dataset))): - sample = dataset[i] - print(f"\nSample {i}:") - print(f" Position shape: {sample['position'].shape}") - print(f" Move token: {sample['move'].item()}") - print(f" Turn: {'White' if sample['is_white'] else 'Black'}") - print(f" ELOs: {sample['white_elo']} vs {sample['black_elo']}") - print(f" Move number: {sample['move_number']} over {dataset.num_moves_per_game[i]} moves") diff --git a/chesstransformer/datasets/lichess.py b/chesstransformer/datasets/lichess.py deleted file mode 100644 index 38c861492879c2d0956af75bd6c661acc967a544..0000000000000000000000000000000000000000 --- a/chesstransformer/datasets/lichess.py +++ /dev/null @@ -1,223 +0,0 @@ -from torch.utils.data import Dataset -import zstandard as zstd -import chess.pgn -import io -import torch - - -def extract_games_optimized(filepath, num_games=1000000, batch_size=1000): - """ - Optimized game extraction with progress tracking. - Process in batches and show estimated time remaining. - - Args: - filepath: Path to the compressed PGN file - num_games: Number of games to extract (default: 1,000,000) - batch_size: Number of games to process in each batch (default: 1,000) - - Returns: - List of extracted games - """ - games = [] - dctx = zstd.ZstdDecompressor() - with open(filepath, "rb") as f: - with dctx.stream_reader(f) as reader: - text_stream = io.TextIOWrapper(reader, encoding="utf-8") - pgn = chess.pgn.read_game(text_stream) - game_count = 0 - batch_count = 0 - - while pgn is not None and game_count < num_games: - # check if the game ended by a win/loss/draw - if pgn.headers.get("Result") not in ["1-0", "0-1", "1/2-1/2"]: - pgn = chess.pgn.read_game(text_stream) - continue - - # Skip Chess960 games - only use classical chess - variant = pgn.headers.get("Variant", "Standard") - if variant != "Standard": - pgn = chess.pgn.read_game(text_stream) - continue - - games.append(pgn) - game_count += 1 - batch_count += 1 - - if batch_count >= batch_size: - batch_count = 0 - print(f"Extracted {game_count}/{num_games} games...") - - pgn = chess.pgn.read_game(text_stream) - - print(f"Finished extracting {len(games)} games.") - return games - - -def encode_game_moves(game, notation="uci", seprator=" "): - """ - Encode the moves of a single game using the provided tokenizer. - - Args: - game: A chess.pgn.Game object - notation: Notation format for moves ("uci" or "san", default: "uci") - seprator: String to separate moves (default: " ") - - Returns: - List of moves as a single formatted string - """ - if notation == "uci": - move_sequence = seprator.join([move.uci() for move in game.mainline_moves()]) - elif notation == "san": - board = game.board() - move_sequence = seprator.join( - [ - board.san(move) - for move in game.mainline_moves() - if not board.push(move) # Push the move to update the board state - ] - ) - else: - raise ValueError("Unsupported notation format. Use 'uci' or 'san'.") - - ending_condition = seprator + { - "1-0": "<1-0>", - "0-1": "<0-1>", - "1/2-1/2": "<1/2-1/2>", - }.get(game.headers.get("Result", ""), "") - if ending_condition: - move_sequence += ending_condition - - return move_sequence - - -class LichessDataset(Dataset): - def __init__( - self, - dataset_path, - tokenizer, - notation="uci", - context_length=512, - nb_games=100000, - ): - """ - Lichess dataset for training chess move prediction models. - - Args: - dataset_path: Path to the lichess dataset file (PGN format) - tokenizer: Tokenizer object to convert moves to token IDs - notation: Notation format for moves ("uci" or "san", default: "uci") - context_length: Maximum sequence length for model input (default: 512) - """ - self.tokenizer = tokenizer - self.context_length = context_length - self.notation = notation - - print(f"Loading dataset from {dataset_path}...") - self.games = extract_games_optimized(dataset_path, num_games=nb_games) - print(f"Total games loaded: {len(self.games)}") - - self.encoded_games = [] - # encode and stack games together - for idx, game in enumerate(self.games): - encoded_moves = encode_game_moves(game, notation=self.notation) - token_ids = self.tokenizer.encode(encoded_moves).ids - - self.encoded_games.append(token_ids) - - # flatten the list of token ids - self.encoded_games = [token_id for game in self.encoded_games for token_id in game] - - def __len__(self): - return len(self.encoded_games) // self.context_length - - def __getitem__(self, idx): - """ - Get a sequence of token IDs for training. - - Args: - idx: Index of the game to retrieve - Returns: - input, target: Tuple of input and target token ID lists - """ - start_idx = idx * self.context_length - end_idx = start_idx + self.context_length + 1 # +1 for target shift - - if end_idx > len(self.encoded_games): - raise IndexError("Index out of range for the dataset.") - - input_ids = self.encoded_games[start_idx : end_idx - 1] - target_ids = self.encoded_games[start_idx + 1 : end_idx] - - input_tensor = torch.tensor(input_ids, dtype=torch.long) - target_tensor = torch.tensor(target_ids, dtype=torch.long) - - return input_tensor, target_tensor - - -if __name__ == "__main__": - from pathlib import Path - import argparse - from chesstransformer.models.tokenizer import create_bpe_tokenizer - - def arg_parser(): - parser = argparse.ArgumentParser(description="Test LichessDataset") - parser.add_argument( - "--dataset_path", - type=str, - default="data/Lichess Rated Games 2017.pgn.zst", - help="Path to the lichess dataset file (PGN format)", - ) - parser.add_argument( - "--num_games", - type=int, - default=10000, - help="Number of games to load for testing (default: 1000)", - ) - parser.add_argument( - "--vocab_path", - type=str, - default="src/chesstransformer/data/tokenizer_models/bpe_tokenizer_vocab2000.json", - help="Path to the trained tokenizer file", - ) - parser.add_argument( - "--context_length", - type=int, - default=512, - help="Context length for sequences (default: 512)", - ) - parser.add_argument( - "--notation", - type=str, - choices=["uci", "san"], - default="uci", - help="Notation format for moves (default: uci)", - ) - args = parser.parse_args() - return args - - args = arg_parser() - dataset_path = Path(args.dataset_path) - num_games = args.num_games - vocab_path = Path(args.vocab_path) - context_length = args.context_length - notation = args.notation - - import tokenizers - - tokenizer = tokenizers.Tokenizer.from_file(str(vocab_path)) - print(f"Loading Lichess dataset from {dataset_path}...") - dataset = LichessDataset( - dataset_path=dataset_path, - tokenizer=tokenizer, - notation=notation, - context_length=context_length, - nb_games=num_games, - ) - - print(f"Dataset loaded with {len(dataset)} games.") - input_ids, target_ids = dataset[0] - print(f"Sample input IDs: {input_ids}") - print(f"Sample target IDs: {target_ids}") - print(f"Encoded and stacked {len(dataset.encoded_games)} token IDs.") - - print(f"Decoded sample moves: {tokenizer.decode(input_ids)}") diff --git a/chesstransformer/datasets/lichess_simple_uci.py b/chesstransformer/datasets/lichess_simple_uci.py deleted file mode 100644 index 64a345732694247ed629a4fed2d340c7728926b3..0000000000000000000000000000000000000000 --- a/chesstransformer/datasets/lichess_simple_uci.py +++ /dev/null @@ -1,136 +0,0 @@ -from pathlib import Path -import json -from torch.utils.data import Dataset -import zstandard as zstd -import chess.pgn -import io -import torch -import chess - - -root_path = Path(__file__).parents[1] -print(f"Root path: {root_path}") - - -class LichessSimpleUciDataset(Dataset): - def __init__( - self, - dataset_path, - vocab_path=root_path / "data/tokenizer_models/uci_vocab.json", - context_length=512, - num_samples=100_000, - ): - """ - Lichess dataset in the simple UCI format.""" - - self.dataset_path = dataset_path - self.num_samples = num_samples - self.vocab_path = vocab_path - self.context_length = context_length - self._load_vocab() - self.games = self._extract_games() - - def _extract_games(self, only_check_mate=True): - games = [] - dctx = zstd.ZstdDecompressor() - with open(self.dataset_path, "rb") as f: - with dctx.stream_reader(f) as reader: - text_stream = io.TextIOWrapper(reader, encoding="utf-8") - game_count = 0 - - while game_count < self.num_samples: - pgn = chess.pgn.read_game(text_stream) - if pgn is None: - break - - # Check if the game ended by a win/loss/draw - if pgn.headers.get("Result") not in ["1-0", "0-1", "1/2-1/2"]: - continue - - # Skip Chess960 games - only use classical chess - variant = pgn.headers.get("Variant", "Standard") - if variant != "Standard": - continue - - games.append(pgn) - game_count += 1 - - if game_count % 10000 == 0: - print(f"Extracted {game_count}/{self.num_samples} games...", end="\r") - - print(f"\nFinished extracting {len(games)} games.") - return games - - def _load_vocab(self): - with open(self.vocab_path, "r") as f: - self.vocab = json.load(f) - self.token_to_id = {token: idx for idx, token in enumerate(self.vocab)} - - def __len__(self): - return len(self.games) - - def __getitem__(self, idx): - game = self.games[idx] - token_ids = self.encode_game(game) - legals_mask = self.get_legal_moves_mask(game) - target_ids = token_ids[1:] + [-100] # Shifted targets with -100 for padding - return { - "input_ids": torch.tensor(token_ids, dtype=torch.long), - "target_ids": torch.tensor(target_ids, dtype=torch.long), - "legal_moves_mask": legals_mask, - } - - def encode_game(self, game): - move_list = [move.uci() for move in game.mainline_moves()] - move_list = [""] + move_list + [""] - token_ids = self.encode_moves(move_list) - return token_ids - - def encode_moves(self, moves): - token_ids = [] - for move in moves: - if move in self.token_to_id: - token_ids.append(self.token_to_id[move]) - else: - token_ids.append(self.token_to_id[""]) - - return token_ids - - def get_legal_moves_mask(self, game): - """ - For each move in the game, generate a mask of legal moves at that position. - Returns a list of masks, where each mask is a tensor of shape (vocab_size,) - with 1.0 for legal moves and 0.0 for illegal moves. - """ - board = game.board() - masks = [] - - for move in game.mainline_moves(): - # Get all legal moves at current position - legal_moves = [m.uci() for m in board.legal_moves] - - # Create mask for all tokens in vocabulary - mask = torch.zeros(len(self.vocab), dtype=torch.float32) - - # Set 1.0 for legal moves - for legal_move in legal_moves: - if legal_move in self.token_to_id: - mask[self.token_to_id[legal_move]] = 1.0 - - masks.append(mask) - - # Apply the move to the board for next iteration - board.push(move) - - # Add mask for and tokens - start_end_mask = torch.zeros(len(self.vocab), dtype=torch.float32) - start_end_mask[self.token_to_id[""]] = 1.0 - start_end_mask[self.token_to_id[""]] = 1.0 - masks = [start_end_mask] + masks + [start_end_mask] - - return torch.stack(masks) - - def decode_game(self, token_ids): - id_to_token = {idx: token for token, idx in self.token_to_id.items()} - moves = [id_to_token.get(tid, "") for tid in token_ids if tid in id_to_token] - return " ".join(moves) diff --git a/chesstransformer/datasets/puzzle_dataset.py b/chesstransformer/datasets/puzzle_dataset.py deleted file mode 100644 index 386e06ce8e3417c409f1fdcdbb546779b214c4da..0000000000000000000000000000000000000000 --- a/chesstransformer/datasets/puzzle_dataset.py +++ /dev/null @@ -1,259 +0,0 @@ -import csv -import zstandard as zstd -import torch -from torch.utils.data import Dataset -import chess -from typing import Optional -from chesstransformer.models.tokenizer.position_tokenizer import PostionTokenizer -from chesstransformer.models.tokenizer.move_tokenizer import MoveTokenizer - - -class LichessPuzzleDataset(Dataset): - """Dataset for Lichess chess puzzles. - - Each puzzle consists of: - - A FEN position (the position where the puzzle starts) - - A sequence of moves (the solution to the puzzle) - - Rating and themes - - The dataset returns position-move pairs where: - - position: The current board state encoded as 64 tokens - - move: The next move in the puzzle solution - - is_white: Whether white is to move - """ - - def __init__( - self, - puzzle_path: str, - min_rating: int = None, - max_rating: int = None, - themes: list[str] = None, - max_puzzles: int = None, - ): - """ - Args: - puzzle_path: Path to the .csv.zst puzzle file - min_rating: Minimum puzzle rating to include - max_rating: Maximum puzzle rating to include - themes: List of themes to filter by (e.g., ['mate', 'mateIn2']) - max_puzzles: Maximum number of puzzles to load (for testing) - """ - self.position_tokenizer = PostionTokenizer() - self.move_tokenizer = MoveTokenizer() - self.puzzles = [] - - print(f"Loading puzzles from {puzzle_path}...") - - # Load and filter puzzles - with zstd.open(puzzle_path, "rt", encoding="utf-8") as f: - reader = csv.DictReader(f) - for i, row in enumerate(reader): - if max_puzzles and i >= max_puzzles: - break - - # Parse puzzle data - puzzle_rating = int(row["Rating"]) - puzzle_themes = row["Themes"].split() - - # Apply filters - if min_rating and puzzle_rating < min_rating: - continue - if max_rating and puzzle_rating > max_rating: - continue - if themes and not any(theme in puzzle_themes for theme in themes): - continue - - # Parse moves (space-separated UCI moves) - moves = row["Moves"].split() - if len(moves) < 2: # Need at least opponent move + our response - continue - - self.puzzles.append( - { - "puzzle_id": row["PuzzleId"], - "fen": row["FEN"], - "moves": moves, - "rating": puzzle_rating, - "themes": puzzle_themes, - "game_url": row["GameUrl"], - } - ) - - if (i + 1) % 10000 == 0: - print(f"Loaded {i + 1} puzzles...") - - print(f"Total puzzles loaded: {len(self.puzzles)}") - - # Calculate total position-move pairs - self.total_pairs = sum(len(p["moves"]) - 1 for p in self.puzzles) - print(f"Total position-move pairs: {self.total_pairs}") - - def __len__(self): - """Return total number of position-move pairs across all puzzles.""" - return self.total_pairs - - def __getitem__(self, idx): - """ - Returns a position-move pair from the puzzle dataset. - - The dataset is indexed as a flat sequence of all position-move pairs - across all puzzles. This means we need to: - 1. Find which puzzle this index belongs to - 2. Find which move within that puzzle - 3. Replay the game to get the board state - 4. Return the encoded position + next move - """ - # Find the puzzle and move index - cumulative = 0 - for puzzle in self.puzzles: - puzzle_pairs = len(puzzle["moves"]) - 1 - if idx < cumulative + puzzle_pairs: - # Found the right puzzle - move_idx = idx - cumulative - break - cumulative += puzzle_pairs - else: - raise IndexError(f"Index {idx} out of range") - - # Set up the board from FEN - board = chess.Board(puzzle["fen"]) - - # Apply moves up to (but not including) the target move - for i in range(move_idx + 1): # +1 because first move is opponent's - move = chess.Move.from_uci(puzzle["moves"][i]) - board.push(move) - - # Get the target move - target_move = puzzle["moves"][move_idx + 1] - - # Encode the position - position_tokens = self.position_tokenizer.encode(board) - - # Encode the move - try: - move_token = self.move_tokenizer.encode(target_move) - except ValueError: - # If move not in vocabulary, skip this sample - # This shouldn't happen often with proper vocab - print(f"Warning: Move {target_move} not in vocabulary for puzzle {puzzle['puzzle_id']}") - move_token = 0 # Use a default - - # Get legal moves mask for loss calculation - legal_moves = list(board.legal_moves) - legal_moves_mask = torch.zeros(self.move_tokenizer.vocab_size, dtype=torch.float32) - for move in legal_moves: - try: - move_id = self.move_tokenizer.encode(move.uci()) - legal_moves_mask[move_id] = 1.0 - except ValueError: - continue - - return { - "position": torch.tensor(position_tokens, dtype=torch.long), - "move": torch.tensor(move_token, dtype=torch.long), - "is_white": board.turn == chess.WHITE, - "puzzle_id": puzzle["puzzle_id"], - "puzzle_rating": puzzle["rating"], - "legal_moves_mask": legal_moves_mask, - "themes": puzzle["themes"], - } - - def get_puzzle_by_id(self, puzzle_id: str): - """Get a complete puzzle by its ID.""" - for puzzle in self.puzzles: - if puzzle["puzzle_id"] == puzzle_id: - return puzzle - return None - - -class LichessPuzzleFullSolutionDataset(Dataset): - """Alternative puzzle dataset that returns complete puzzles (not individual moves). - - Useful for evaluation where you want to test solving the entire puzzle. - """ - - def __init__( - self, - puzzle_path: str, - min_rating: int = None, - max_rating: int = None, - themes: list[str] = None, - max_puzzles: int = None, - ): - """ - Args: - puzzle_path: Path to the .csv.zst puzzle file - min_rating: Minimum puzzle rating to include - max_rating: Maximum puzzle rating to include - themes: List of themes to filter by - max_puzzles: Maximum number of puzzles to load - """ - self.position_tokenizer = PostionTokenizer() - self.move_tokenizer = MoveTokenizer() - self.puzzles = [] - - print(f"Loading puzzles from {puzzle_path}...") - - with zstd.open(puzzle_path, "rt", encoding="utf-8") as f: - reader = csv.DictReader(f) - for i, row in enumerate(reader): - if max_puzzles and i >= max_puzzles: - break - - puzzle_rating = int(row["Rating"]) - puzzle_themes = row["Themes"].split() - - if min_rating and puzzle_rating < min_rating: - continue - if max_rating and puzzle_rating > max_rating: - continue - if themes and not any(theme in puzzle_themes for theme in themes): - continue - - moves = row["Moves"].split() - if len(moves) < 2: - continue - - self.puzzles.append( - { - "puzzle_id": row["PuzzleId"], - "fen": row["FEN"], - "moves": moves, - "rating": puzzle_rating, - "themes": puzzle_themes, - "game_url": row["GameUrl"], - } - ) - - print(f"Total puzzles loaded: {len(self.puzzles)}") - - def __len__(self): - return len(self.puzzles) - - def __getitem__(self, idx): - """Returns a complete puzzle with starting position and full solution.""" - puzzle = self.puzzles[idx] - - # Starting position - board = chess.Board(puzzle["fen"]) - position_tokens = self.position_tokenizer.encode(board) - - # Encode solution moves - solution_tokens = [] - for move_uci in puzzle["moves"]: - try: - move_token = self.move_tokenizer.encode(move_uci) - solution_tokens.append(move_token) - except ValueError: - solution_tokens.append(0) - - return { - "puzzle_id": puzzle["puzzle_id"], - "position": torch.tensor(position_tokens, dtype=torch.long), - "solution": torch.tensor(solution_tokens, dtype=torch.long), - "fen": puzzle["fen"], - "moves_uci": puzzle["moves"], - "rating": puzzle["rating"], - "themes": puzzle["themes"], - "is_white": board.turn == chess.WHITE, - } diff --git a/chesstransformer/datasets/shard_format.py b/chesstransformer/datasets/shard_format.py deleted file mode 100644 index 7934161b6f0f611472adc5a0f2581692f2aede57..0000000000000000000000000000000000000000 --- a/chesstransformer/datasets/shard_format.py +++ /dev/null @@ -1,129 +0,0 @@ -"""On-disk record format for the flat, memory-mappable training shards. - -Shared by ``scripts/build_shards.py`` (writer), ``FlatShardDataset`` (reader) and -``scripts/verify_shards.py`` (equivalence harness), so the layout is defined exactly -once. See ``doc/dataset_shards.md`` §3 for the design rationale and the measurements -behind the choices below. - -One sample is one fixed-width row. Only the nine fields ``pos2move_v2_trainer.py`` -actually reads are stored; everything else ``HDF5ChessDataset`` returns is dropped. - -The legal-move mask is the whole design problem: ``(64, 73)`` bool is 4,672 bytes and -would dominate the record 20:1. It is stored instead as a fixed-width list of at most -``LEGAL_CAP`` flat ``from_square * 73 + plane`` indices (129 bytes), which is what makes -one memmap row per sample — and therefore trivial rank/worker slicing — possible. The -mask is rebuilt on GPU by :func:`~chesstransformer.datasets.flat_shard_dataset.scatter_legal_planes`. - -Fixed-width was chosen over CSR (~72 B/sample, no cap) deliberately: CSR is ~28 % smaller -and is what Megatron's ``IndexedDataset`` does, but it needs a custom ragged collate, and -the 1.4 GB it saves is on a dataset that already fits in page cache. The cap is not a -correctness risk because the *target* move's index is always written first (see -``LEGAL_CAP`` below), so clipping can only ever drop alternative legal moves, never the -label. Observed legal-move counts over 400 real positions: mean 33.9, p99.9 = 53, max 53. -""" - -import numpy as np - -NUM_ACTION_PLANES = 73 -NUM_SQUARES = 64 - -#: Number of legal-move indices stored per sample. Sits well above the observed max of -#: 53. The builder counts overflows and prints the rate; if it ever climbs above ~0.01 % -#: raise this to 96 and rebuild. -LEGAL_CAP = 64 - -#: Flat action index space is ``[0, 4672)``. Unused slots in ``legal_idx`` are filled with -#: ``PAD_ACTION`` (== 4672), one past the end, so a GPU ``scatter_`` can write padding into -#: a scratch column that is then sliced off. Writing padding as 0 instead would silently -#: mark square a1 / plane 0 legal on every single sample. -PAD_ACTION = NUM_SQUARES * NUM_ACTION_PLANES - -#: Packed record layout. Offsets are explicit rather than auto-computed so that both -#: ``uint16`` fields land on even offsets — an unaligned memmap view of ``legal_idx`` -#: would force numpy into a slow per-element copy on every batch gather. -#: -#: ========== ====== ========================================================= -#: offset dtype field -#: ========== ====== ========================================================= -#: 0-63 u1×64 position board tokens, vocab 0-12 -#: 64-191 u2×64 legal_idx flat legal actions, target first, PAD-filled -#: 192 u1 legal_cnt number of valid entries in legal_idx -#: 193 u1 from_square target move source square, 0-63 -#: 194 u1 action_plane target move AlphaZero plane, 0-72 -#: 195 u1 castling_rights 4-bit mask, 0-15 -#: 196 u1 en_passant_file 0-7 = file a-h, 8 = none -#: 197 u1 is_white side to move -#: 198 i1 result 0 = draw, 1 = white win, 2 = black win (as in the HDF5) -#: 199 u1 (pad) keeps move_number 2-byte aligned -#: 200-201 u2 move_number ply index, max observed 601 -#: ========== ====== ========================================================= -RECORD_DTYPE = np.dtype( - { - "names": [ - "position", - "legal_idx", - "legal_cnt", - "from_square", - "action_plane", - "castling_rights", - "en_passant_file", - "is_white", - "result", - "move_number", - ], - "formats": [ - (np.uint8, NUM_SQUARES), - (np.uint16, LEGAL_CAP), - np.uint8, - np.uint8, - np.uint8, - np.uint8, - np.uint8, - np.uint8, - np.int8, - np.uint16, - ], - "offsets": [0, 64, 192, 193, 194, 195, 196, 197, 198, 200], - "itemsize": 202, - } -) - -RECORD_BYTES = RECORD_DTYPE.itemsize - -#: Bumped whenever the layout above changes in a way that makes old shards unreadable. -#: ``FlatShardDataset`` refuses to load a directory built by a different version. -FORMAT_VERSION = 1 - - -def dtype_to_meta() -> dict: - """Serialise :data:`RECORD_DTYPE` into ``meta.json``. - - Stored so a shard directory is self-describing: a reader can reconstruct the exact - layout it was written with instead of trusting that this module never changed. - """ - return { - "names": list(RECORD_DTYPE.names), - "formats": [ - ( - [RECORD_DTYPE[n].subdtype[0].str, RECORD_DTYPE[n].subdtype[1][0]] - if RECORD_DTYPE[n].subdtype - else RECORD_DTYPE[n].str - ) - for n in RECORD_DTYPE.names - ], - "offsets": [RECORD_DTYPE.fields[n][1] for n in RECORD_DTYPE.names], - "itemsize": RECORD_BYTES, - } - - -def dtype_from_meta(meta: dict) -> np.dtype: - """Rebuild a record dtype from what ``meta.json`` recorded.""" - formats = [tuple(f) if isinstance(f, list) else f for f in meta["formats"]] - return np.dtype( - { - "names": list(meta["names"]), - "formats": formats, - "offsets": list(meta["offsets"]), - "itemsize": int(meta["itemsize"]), - } - ) diff --git a/chesstransformer/distributed_muon.py b/chesstransformer/distributed_muon.py deleted file mode 100644 index 55ce071f3b13659a3cbd37e3b82cd3fda5354d5f..0000000000000000000000000000000000000000 --- a/chesstransformer/distributed_muon.py +++ /dev/null @@ -1,222 +0,0 @@ -"""Muon with Newton-Schulz distributed across ranks, plus its schedules. - -Under plain DDP every rank all-reduces to the *same* gradient and then every rank runs the -*same* Newton-Schulz iteration on it. That is pure redundant compute: at world size N, -N-1 copies of the NS work are thrown away, and every rank stores a full momentum buffer. - -The fix is to partition the work — but the partition axis is the whole point. NS is -``X @ X.T`` plus a global spectral-norm division, so it needs the *complete* matrix. -Measured on a 64x32 weight, orthogonalizing per-shard and concatenating gives a **52-58 % -wrong update** at world size 2-4, and nothing raises: a row-slice of a 2D matrix is still a -2D matrix. That is the ZeRO-2 trap, and it is why sharding *inside* a tensor is off limits -here even though it is perfectly safe for elementwise optimizers like AdamW. - -So this partitions by **whole parameter**, following nanochat's ``MuonAdamW`` -(https://github.com/karpathy/nanochat, ``nanochat/optim.py``): params of a given shape are -stacked, the K of them are divided into contiguous chunks across ranks, each rank runs NS -only on the complete matrices it owns, and one ``all_gather`` per shape bucket republishes -the results. Momentum state exists only for owned params, so it is sharded too. - -**Communication note, stated honestly.** nanochat does not use DDP: it ``reduce_scatter``s -gradients inside the optimizer, so grad-sync and state-sharding share one collective and -the total wire cost equals what DDP's all-reduce would have been. This class runs *on top -of* DDP, which has already all-reduced the gradients, so the ``all_gather`` here is -**additional** traffic — bytes DDP did not previously move. It buys NS compute (÷N) and -momentum memory (÷N) at the cost of one param-sized gather per step. On a fast interconnect -that is a clear win; on PCIe it may not be. ``scripts/bench_distributed_muon.py`` measures -it rather than assuming. - -**Measured so far (gloo/CPU, preset 46m, 121 2D tensors, 16-core box):** - -=========== =========== ================== -world size step time momentum state -=========== =========== ================== -1 243 ms 177.0 MiB/rank -2 638 ms 89.0 MiB/rank -4 491 ms 45.0 MiB/rank -=========== =========== ================== - -The memory result is the designed one and is exact: state divides by world size. **The step -time is currently a regression**, and the honest reading is that this configuration has not -been shown to be a compute win. Three things confound the CPU numbers -- gloo is far slower -relative to compute than NCCL, N ranks on one 16-core box contend for the same cores so the -"NS compute / N" never materialises, and the benchmark is pure optimizer with no forward or -backward, so the all_gather is 100 % of the measured time instead of a few percent of a real -step. It still should not be reported as a win until multi-GPU says so. - -The structural fix is the fused variant, which is why nanochat does not use DDP at all: it -``reduce_scatter``s gradients inside the optimizer, so grad-sync and state-sharding share one -collective and the total wire cost equals DDP's all-reduce -- the ``all_gather`` stops being -*extra*. Doing that here means excluding the Muon params from DDP's reducer -(``DistributedDataParallel._set_params_and_buffers_to_ignore_for_model``) and doing the -reduce-scatter in ``step()``. That is the next step, and it is what turns this from "memory -win, compute unproven" into a pure win. -""" - -import math - -import torch -import torch.distributed as dist - -# Reuse torch's own kernels rather than reimplementing the algorithm: it makes this -# optimizer numerically identical to torch.optim.Muon by construction, which is exactly -# what tests/test_distributed_muon.py asserts. Private, so guarded. -try: - from torch.optim._muon import _adjust_lr, _zeropower_via_newtonschulz -except ImportError as exc: # pragma: no cover - raise ImportError( - "DistributedMuon reuses torch.optim._muon internals; needs a torch with " - "torch.optim.Muon (2.9+)." - ) from exc - -#: Params smaller than this stay replicated: every rank computes them redundantly and no -#: collective is issued. For Pos2MoveV2-large that is 9 of 13 shape buckets holding 0.2M of -#: 156.4M params — distributing them would cost 9 extra collectives to save nothing. -DEFAULT_MIN_DISTRIBUTED_NUMEL = 65_536 - - -def muon_momentum(step: int, total_steps: int, warmup: int = 400, - warmdown_ratio: float = 0.2, lo: float = 0.85, - hi: float = 0.97, end: float = 0.90) -> float: - """Momentum schedule: warm up 0.85 -> 0.97, then down to 0.90 during LR warmdown. - - Muon's momentum controls how much history the orthogonalized direction carries. Early - on the gradient is changing fast and a long memory averages over a moving target, so it - starts low; late in training a slightly *shorter* memory helps the run settle, which is - why it comes back down rather than staying pinned at the peak. Schedule follows - nanochat's ``get_muon_momentum``. - """ - if step < warmup: - frac = step / max(1, warmup) - return (1 - frac) * lo + frac * hi - warmdown_iters = max(1, round(warmdown_ratio * total_steps)) - warmdown_start = total_steps - warmdown_iters - if step >= warmdown_start: - progress = min(1.0, (step - warmdown_start) / warmdown_iters) - return hi * (1 - progress) + end * progress - return hi - - -def muon_weight_decay(step: int, total_steps: int, base_wd: float) -> float: - """Cosine-decay weight decay to zero over the run, as nanochat's ``get_weight_decay``.""" - return base_wd * 0.5 * (1 + math.cos(math.pi * min(1.0, step / max(1, total_steps)))) - - -class DistributedMuon(torch.optim.Optimizer): - """Drop-in for ``torch.optim.Muon`` that splits NS work and momentum across ranks. - - Assumes gradients are already synchronized (DDP has all-reduced them), so every rank - starts from an identical gradient and only the *work* is divided. With no process group - initialized it degenerates to exactly ``torch.optim.Muon``. - """ - - def __init__(self, params, lr=1e-3, weight_decay=0.1, momentum=0.95, nesterov=True, - ns_coefficients=(3.4445, -4.7750, 2.0315), eps=1e-7, ns_steps=5, - adjust_lr_fn=None, min_distributed_numel=DEFAULT_MIN_DISTRIBUTED_NUMEL): - defaults = dict(lr=lr, weight_decay=weight_decay, momentum=momentum, - nesterov=nesterov, ns_coefficients=ns_coefficients, eps=eps, - ns_steps=ns_steps, adjust_lr_fn=adjust_lr_fn) - super().__init__(params, defaults) - - self.world_size = dist.get_world_size() if dist.is_initialized() else 1 - self.rank = dist.get_rank() if dist.is_initialized() else 0 - self.min_distributed_numel = min_distributed_numel - self._plan = [self._plan_group(g) for g in self.param_groups] - - owned = sum(len(b["owned"]) for p in self._plan for b in p["buckets"]) - total = sum(len(g["params"]) for g in self.param_groups) - self.owned_param_count, self.total_param_count = owned, total - - def _plan_group(self, group): - """Bucket a group's params by shape and assign contiguous chunks to ranks. - - Contiguous rather than strided so that ``all_gather_into_tensor`` — which lays rank - i's contribution at output[i*chunk:(i+1)*chunk] — reassembles the bucket in order - with no extra permutation. - """ - by_shape: dict[tuple, list] = {} - for p in group["params"]: - if p.ndim != 2: - raise ValueError(f"DistributedMuon handles 2D params only, got {p.ndim}D") - by_shape.setdefault(tuple(p.shape), []).append(p) - - buckets = [] - for shape, plist in sorted(by_shape.items(), key=lambda kv: -kv[1][0].numel() * len(kv[1])): - k = len(plist) - distributed = (self.world_size > 1 - and plist[0].numel() >= self.min_distributed_numel) - if not distributed: - # Replicated: every rank updates every param, no collective. - buckets.append(dict(shape=shape, params=plist, owned=plist, - offset=0, chunk=k, distributed=False)) - continue - chunk = math.ceil(k / self.world_size) - start = self.rank * chunk - owned = plist[start:start + chunk] # may be short on the last rank - buckets.append(dict(shape=shape, params=plist, owned=owned, - offset=start, chunk=chunk, distributed=True)) - return dict(buckets=buckets) - - @torch.no_grad() - def step(self, closure=None): - loss = None - if closure is not None: - with torch.enable_grad(): - loss = closure() - - for group, plan in zip(self.param_groups, self._plan): - lr, wd = group["lr"], group["weight_decay"] - momentum, nesterov = group["momentum"], group["nesterov"] - for bucket in plan["buckets"]: - for p in bucket["owned"]: - if p.grad is None: - continue - self._update_one(p, lr, wd, momentum, nesterov, group) - for bucket in plan["buckets"]: - if bucket["distributed"]: - self._publish(bucket) - return loss - - def _update_one(self, p, lr, wd, momentum, nesterov, group): - """Exactly torch.optim.Muon's ``_single_tensor_muon`` body, for one param.""" - grad = p.grad - if grad.ndim != 2: - raise ValueError("Param gradient must be a 2D matrix") - state = self.state[p] - if "momentum_buffer" not in state: - state["momentum_buffer"] = torch.zeros_like(p) - buf = state["momentum_buffer"] - buf.lerp_(grad, 1 - momentum) - update = grad.lerp(buf, momentum) if nesterov else buf - update = _zeropower_via_newtonschulz( - update, group["ns_coefficients"], group["ns_steps"], group["eps"]) - adjusted_lr = _adjust_lr(lr, group["adjust_lr_fn"], p.shape) - p.mul_(1 - lr * wd) - p.add_(update, alpha=-adjusted_lr) - - def _publish(self, bucket): - """One all_gather per shape bucket to give every rank the updated params. - - Zero-padding when K does not divide world_size: the tail slots are gathered and - discarded, which costs a little bandwidth and keeps the collective's shape uniform. - """ - plist, chunk, shape = bucket["params"], bucket["chunk"], bucket["shape"] - k, ws = len(plist), self.world_size - ref = plist[0] - local = torch.zeros(chunk, *shape, dtype=ref.dtype, device=ref.device) - for i, p in enumerate(bucket["owned"]): - local[i].copy_(p) - out = torch.empty(chunk * ws, *shape, dtype=ref.dtype, device=ref.device) - dist.all_gather_into_tensor(out, local) - for i in range(k): - plist[i].copy_(out[i]) - - def sharding_summary(self) -> str: - parts = [] - for plan in self._plan: - for b in plan["buckets"]: - tag = "dist" if b["distributed"] else "repl" - parts.append(f"{tuple(b['shape'])}x{len(b['params'])}:{tag}") - return (f"DistributedMuon rank {self.rank}/{self.world_size}: owns " - f"{self.owned_param_count}/{self.total_param_count} params | " - + " ".join(parts)) diff --git a/chesstransformer/introspection/__init__.py b/chesstransformer/introspection/__init__.py deleted file mode 100644 index 6f9090bab576afaa3fb3ccd3686e504f5fec0ffd..0000000000000000000000000000000000000000 --- a/chesstransformer/introspection/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Model introspection: attention capture, logit lens, occlusion saliency.""" - -from chesstransformer.introspection.analyze import PositionAnalyzer, load_model - -__all__ = ["PositionAnalyzer", "load_model"] diff --git a/chesstransformer/introspection/analyze.py b/chesstransformer/introspection/analyze.py deleted file mode 100644 index 9624f9e05f4b78ba9a72a54e3d14d6dd1d4209f5..0000000000000000000000000000000000000000 --- a/chesstransformer/introspection/analyze.py +++ /dev/null @@ -1,450 +0,0 @@ -"""Per-position introspection of a Pos2MoveV2 network. - -Everything here is read-only with respect to the model: attention maps are -recomputed from the captured layer inputs using the module's own projections, -so the numbers match what SDPA saw during the real forward pass. - -Produced per position: - * policy over legal moves (probability, raw logit, action plane) - * value head output, plus the value/policy read off *every* layer - (logit lens) so you can see at which depth the model makes up its mind - * full attention tensor (L, H, 67, 67) - * attention rollout (Abnar & Zuidema 2020) over the layer stack - * occlusion saliency: remove one piece, measure the swing in value and in - the probability of the move the model wanted to play - * 1-ply child values, i.e. what the value head says about the position - *after* each legal move — the fastest way to spot policy/value disagreement -""" - -from __future__ import annotations - -import json -import math -import zlib -from base64 import b64encode -from dataclasses import dataclass -from pathlib import Path - -import chess -import numpy as np -import torch -from safetensors import safe_open - -from chesstransformer.models.tokenizer import PostionTokenizer -from chesstransformer.models.tokenizer.alphazero_move_encoder import ( - NUM_ACTION_PLANES, - move_to_action_plane, -) -from chesstransformer.models.transformer.pos2move_v2 import Pos2MoveV2 - -BOARD_SQUARES = 64 -CONTEXT_SIZE = 67 -STATE_TOKEN_NAMES = ["castling", "en_passant", "player"] - - -def load_model(model_dir: str | Path, device: str = "cpu", use_ema: bool = False): - """Load a Pos2MoveV2 checkpoint in fp32 (no compile, no bf16). - - Introspection wants clean numbers more than it wants speed, and the model - is small enough that fp32 eager is instant either way. - """ - model_dir = Path(model_dir) - - config_path = model_dir / "model_config.json" - if not config_path.exists(): - config_path = model_dir.parent.parent / "model_config.json" - if not config_path.exists(): - raise FileNotFoundError(f"No model_config.json found for {model_dir}") - with open(config_path) as f: - config = json.load(f) - - model = Pos2MoveV2(**config) - - weights = model_dir / "model.safetensors" - if not weights.exists(): - raise FileNotFoundError(f"No model.safetensors in {model_dir}") - with safe_open(str(weights), framework="pt", device="cpu") as f: - state_dict = {k: f.get_tensor(k) for k in f.keys()} - state_dict = {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()} - model.load_state_dict(state_dict) - - if use_ema: - ema_path = model_dir / "ema_state.pt" - if not ema_path.exists(): - raise FileNotFoundError(f"No ema_state.pt in {model_dir}") - ema_state = torch.load(str(ema_path), map_location="cpu", weights_only=True) - ema_state = {k.replace("_orig_mod.", ""): v for k, v in ema_state.items()} - model.load_state_dict(ema_state, strict=False) - - model.eval() - return model.float().to(device), config - - -def encode_board(board: chess.Board, tokenizer: PostionTokenizer): - """Same encoding the bots use: 64 piece tokens + castling/ep/player.""" - tokens = tokenizer.encode(board) - castling = 0 - if board.has_kingside_castling_rights(chess.WHITE): - castling |= 1 - if board.has_queenside_castling_rights(chess.WHITE): - castling |= 2 - if board.has_kingside_castling_rights(chess.BLACK): - castling |= 4 - if board.has_queenside_castling_rights(chess.BLACK): - castling |= 8 - ep_file = chess.square_file(board.ep_square) if board.has_legal_en_passant() else 8 - return tokens, int(board.turn), castling, ep_file - - -@dataclass -class _Capture: - """Residual stream and attention input for one layer.""" - - attn_input: torch.Tensor # normed input handed to the attention module - output: torch.Tensor # residual stream leaving the layer - - -class PositionAnalyzer: - def __init__( - self, - model: Pos2MoveV2, - device: str = "cpu", - max_moves: int = 64, - saliency: bool = True, - ): - self.model = model - self.device = device - self.tokenizer = PostionTokenizer() - self.max_moves = max_moves - self.saliency = saliency - self.n_layers = len(model.transformer_layers) - self.n_heads = model.transformer_layers[0].attn.num_heads - - # ── raw forward helpers ──────────────────────────────────────────── - @torch.no_grad() - def _forward_batch(self, boards: list[chess.Board]): - enc = [encode_board(b, self.tokenizer) for b in boards] - tokens = torch.tensor([e[0] for e in enc], dtype=torch.long, device=self.device) - player = torch.tensor([e[1] for e in enc], dtype=torch.long, device=self.device) - castling = torch.tensor([e[2] for e in enc], dtype=torch.long, device=self.device) - ep = torch.tensor([e[3] for e in enc], dtype=torch.long, device=self.device) - return self.model(tokens, player, castling, ep) - - @torch.no_grad() - def _forward_tokens(self, tokens, player, castling, ep): - return self.model(tokens, player, castling, ep) - - @torch.no_grad() - def _forward_with_capture(self, board: chess.Board): - """One forward pass, keeping every layer's input and output.""" - captures: list[_Capture] = [] - pending: dict[int, torch.Tensor] = {} - handles = [] - - def make_pre_hook(idx): - def hook(_module, args): - pending[idx] = args[0].detach() - - return hook - - def make_post_hook(idx): - def hook(_module, _args, output): - captures.append(_Capture(attn_input=pending[idx], output=output.detach())) - - return hook - - for i, layer in enumerate(self.model.transformer_layers): - handles.append(layer.attn.register_forward_pre_hook(make_pre_hook(i))) - handles.append(layer.register_forward_hook(make_post_hook(i))) - - try: - tokens, player, castling, ep = encode_board(board, self.tokenizer) - out = self._forward_tokens( - torch.tensor([tokens], dtype=torch.long, device=self.device), - torch.tensor([player], dtype=torch.long, device=self.device), - torch.tensor([castling], dtype=torch.long, device=self.device), - torch.tensor([ep], dtype=torch.long, device=self.device), - ) - finally: - for h in handles: - h.remove() - - return out, captures - - @torch.no_grad() - def _attention_probs(self, layer_idx: int, attn_input: torch.Tensor) -> torch.Tensor: - """Recompute softmax attention for one layer: (H, 67, 67). - - Mirrors ChessGroupedQueryAttention.forward up to the softmax — SDPA - adds the chess-relation bias to the *scaled* scores, so we do too. - """ - attn = self.model.transformer_layers[layer_idx].attn - x = attn_input - b, t, _ = x.shape - - q = attn.q_proj(x).view(b, t, attn.num_heads, attn.head_dim).transpose(1, 2) - k = attn.k_proj(x).view(b, t, attn.num_kv_groups, attn.head_dim).transpose(1, 2) - q = attn.q_norm(q) - k = attn.k_norm(k) - k = k.repeat_interleave(attn.group_size, dim=1) - - scores = (q @ k.transpose(-2, -1)) / math.sqrt(attn.head_dim) - scores = scores + attn.bias_table[:, attn.rel_idx].unsqueeze(0) - return torch.softmax(scores, dim=-1)[0] - - # ── analysis ─────────────────────────────────────────────────────── - def analyze(self, board: chess.Board, include_attention: bool = True) -> dict: - (move_logits, value), captures = self._forward_with_capture(board) - logits = move_logits[0].float() # (64, 73) - value = float(value[0].item()) - - result: dict = { - "fen": board.fen(), - "turn": "w" if board.turn else "b", - "fullmove": board.fullmove_number, - "check": board.is_check(), - "pieces": [ - (board.piece_at(sq).symbol() if board.piece_at(sq) else None) - for sq in range(64) - ], - "value": value, - } - - legal = list(board.legal_moves) - result["legal_count"] = len(legal) - if not legal: - result["policy"] = {"moves": [], "entropy": 0.0, "top1_prob": 0.0} - result["terminal"] = board.result() - return result - - result.update(self._policy_block(board, logits, legal)) - result.update(self._depth_block(captures, logits, board, legal)) - - if include_attention: - result["attention"] = self._attention_block(captures) - - if self.saliency: - result["saliency"] = self._saliency_block(board, value, result) - - return result - - def _policy_block(self, board: chess.Board, logits: torch.Tensor, legal) -> dict: - planes = [ - move_to_action_plane(m.from_square, m.to_square, m.promotion) for m in legal - ] - idx = torch.tensor( - [m.from_square * NUM_ACTION_PLANES + p for m, p in zip(legal, planes)], - dtype=torch.long, - ) - flat = logits.reshape(-1).cpu() - legal_logits = flat[idx] - probs = torch.softmax(legal_logits, dim=0) - - # Illegal mass: how much of the raw 64x73 softmax the model spends on - # moves that do not exist. A cheap sanity signal for a broken head. - full_probs = torch.softmax(flat, dim=0) - legal_mass = float(full_probs[idx].sum()) - - order = torch.argsort(probs, descending=True) - moves = [] - for rank, i in enumerate(order.tolist()): - m = legal[i] - moves.append( - { - "uci": m.uci(), - "san": board.san(m), - "from": m.from_square, - "to": m.to_square, - "plane": planes[i], - "prob": float(probs[i]), - "logit": float(legal_logits[i]), - "rank": rank, - "capture": board.is_capture(m), - "check": board.gives_check(m), - } - ) - - p = probs[probs > 0] - entropy = float(-(p * p.log()).sum()) - return { - "policy": { - "moves": moves[: self.max_moves], - "n_moves": len(moves), - "entropy": entropy, - "max_entropy": math.log(len(legal)), - "top1_prob": moves[0]["prob"], - "legal_mass": legal_mass, - } - } - - @torch.no_grad() - def _depth_block(self, captures, final_logits, board, legal) -> dict: - """Logit lens: decode value + policy from every layer's residual.""" - norm = self.model.final_norm - value_by_layer = [] - top_by_layer = [] - write_norms = [] - - planes = [ - move_to_action_plane(m.from_square, m.to_square, m.promotion) for m in legal - ] - idx = torch.tensor( - [m.from_square * NUM_ACTION_PLANES + p for m, p in zip(legal, planes)], - dtype=torch.long, - device=self.device, - ) - final_probs = torch.softmax(final_logits.reshape(-1)[idx.cpu()], dim=0) - final_top = int(torch.argmax(final_probs)) - - prev = None - for cap in captures: - x = norm(cap.output) - state = x[:, -3:, :].mean(dim=1) - value_by_layer.append(float(self.model.value_head(state)[0].item())) - - lens_logits = self.model.move_head(x[:, :64, :])[0].reshape(-1)[idx] - lens_probs = torch.softmax(lens_logits.float(), dim=0) - best = int(torch.argmax(lens_probs)) - top_by_layer.append( - { - "uci": legal[best].uci(), - "san": board.san(legal[best]), - "prob": float(lens_probs[best]), - "final_move_prob": float(lens_probs[final_top]), - "agrees": best == final_top, - } - ) - - out = cap.output - write_norms.append( - float((out - prev).norm().item()) if prev is not None else float(out.norm().item()) - ) - prev = out - - return { - "depth": { - "value_by_layer": value_by_layer, - "top_by_layer": top_by_layer, - "residual_write_norm": write_norms, - } - } - - @torch.no_grad() - def _attention_block(self, captures) -> dict: - """Full (L, H, 67, 67) attention, u8-quantised per row, deflated.""" - maps = [] - for i, cap in enumerate(captures): - maps.append(self._attention_probs(i, cap.attn_input).cpu()) - attn = torch.stack(maps) # (L, H, 67, 67) - - rollout = self._rollout(attn) - - # u8 per row, companded through a square root: attention rows are long - # tails of small weights, and linear u8 would quantise those to 20-30% - # relative error. sqrt spreads the error evenly across magnitudes. - row_max = attn.amax(dim=-1, keepdim=True).clamp(min=1e-9) - quant = ((attn / row_max).sqrt() * 255).round().clamp(0, 255).to(torch.uint8).numpy() - payload = zlib.compress(quant.tobytes(), 6) - - return { - "shape": list(attn.shape), - "scale": row_max.squeeze(-1).flatten().numpy().astype(np.float32).tolist(), - "data": b64encode(payload).decode("ascii"), - "rollout": [round(v, 5) for v in rollout.tolist()], - } - - @staticmethod - def _rollout(attn: torch.Tensor) -> torch.Tensor: - """Attention rollout: how much of each token the output actually sees. - - Head-averaged, residual-corrected (0.5*A + 0.5*I), multiplied through - the stack, then read from the three game-state token rows — those are - what the value head consumes. - """ - a = attn.mean(dim=1) # (L, T, T) - eye = torch.eye(a.shape[-1]) - joint = None - for layer in a: - m = 0.5 * layer + 0.5 * eye - m = m / m.sum(dim=-1, keepdim=True) - joint = m if joint is None else m @ joint - return joint[-3:, :].mean(dim=0) - - @torch.no_grad() - def _saliency_block(self, board: chess.Board, base_value: float, result: dict) -> dict: - """Occlusion: delete one piece at a time, measure what moves. - - Kings are left in place (an occluded king is not a chess position the - model has ever seen). Everything runs as one batch. - """ - top = result["policy"]["moves"][0] - top_idx = top["from"] * NUM_ACTION_PLANES + top["plane"] - - squares = [ - sq - for sq in range(64) - if board.piece_at(sq) is not None and board.piece_at(sq).piece_type != chess.KING - ] - value_delta = [0.0] * 64 - policy_delta = [0.0] * 64 - if not squares: - return {"value_delta": value_delta, "policy_delta": policy_delta, "squares": []} - - tokens, player, castling, ep = encode_board(board, self.tokenizer) - base = torch.tensor(tokens, dtype=torch.long).repeat(len(squares), 1) - for row, sq in enumerate(squares): - base[row, sq] = 0 - n = len(squares) - move_logits, values = self._forward_tokens( - base.to(self.device), - torch.full((n,), player, dtype=torch.long, device=self.device), - torch.full((n,), castling, dtype=torch.long, device=self.device), - torch.full((n,), ep, dtype=torch.long, device=self.device), - ) - - # Probability of the top move under the *full* 64x73 softmax: occlusion - # changes the legal move set, so a legal-masked comparison would not be - # measuring the same quantity across rows. - flat = move_logits.float().reshape(n, -1).cpu() - probs = torch.softmax(flat, dim=1)[:, top_idx] - - ref_logits, _ = self._forward_batch([board]) - ref_prob = float(torch.softmax(ref_logits[0].float().reshape(-1), dim=0)[top_idx]) - - for row, sq in enumerate(squares): - value_delta[sq] = float(values[row].item()) - base_value - policy_delta[sq] = float(probs[row]) - ref_prob - - return { - "value_delta": [round(v, 5) for v in value_delta], - "policy_delta": [round(v, 5) for v in policy_delta], - "squares": squares, - "top_move": top["uci"], - "ref_prob": ref_prob, - } - - @torch.no_grad() - def child_values(self, board: chess.Board, moves: list[dict]) -> None: - """Fill in the value of the position *after* each candidate move. - - Stored from the mover's point of view (the raw head is side-to-move - POV, so it gets negated) — directly comparable to ``value``. - """ - if not moves: - return - boards = [] - terminal = {} - for i, m in enumerate(moves): - b = board.copy(stack=False) - b.push(chess.Move.from_uci(m["uci"])) - if b.is_checkmate(): - terminal[i] = 1.0 - elif b.is_stalemate() or b.is_insufficient_material(): - terminal[i] = 0.0 - boards.append(b) - - _, values = self._forward_batch(boards) - for i, m in enumerate(moves): - m["child_value"] = ( - terminal[i] if i in terminal else -float(values[i].item()) - ) diff --git a/chesstransformer/introspection/viewer.html b/chesstransformer/introspection/viewer.html deleted file mode 100644 index 6721dc955379954e8be105a9dc56ecb45d94abae..0000000000000000000000000000000000000000 --- a/chesstransformer/introspection/viewer.html +++ /dev/null @@ -1,860 +0,0 @@ -Pos2MoveV2 Glass Box - - - - - - - -
-
-

Model introspectionGlass Box

-
-
- -
- -
-
-
-
- -
-
-
-
-
-
- -
-
- -
-
Legal moves — policy vs. value
-
-
- -
-
Where the answer forms
- -
-
-
- -
-
- Attention - - - - - - - - -
-
-
- -
0max
-
Rows are queries (the token doing the looking), columns are keys. The last three rows/columns are the castling, en-passant and side-to-move tokens. Click a cell to select that square on the board.
-
-
-
All heads, layer click to select
-
-
Relation bias — head learned, position-independent
-
-
-
-
- -
- How to read this / how it was made -
-
-

Policy vs. value disagreement

-

Every legal move carries its policy probability and the child value — the value head's verdict on the position after that move, from the mover's side. A move the policy loves but the value dislikes (or vice versa) is where search and network fight each other.

-
-
-

Where the answer forms

-

The value and policy are decoded from every layer's residual stream through the final norm and the real heads (a logit lens). If the top move is already locked in by layer 6 and nothing moves after, the last ten layers are not doing policy work.

-
-
-

Occlusion saliency

-

Each non-king piece is deleted in turn and the position re-evaluated. The square shows the swing in value, or in the probability of the move the model wanted. Big swings mark the pieces the verdict actually rests on.

-
-
-

Attention and rollout

-

Attention is recomputed from each layer's captured input using the model's own projections and its chess-relation bias, then checked against the real forward pass. Rollout multiplies the head-averaged, residual-corrected maps through the stack and reads the game-state token rows.

-
-
-

-
-
- -
- - - diff --git a/chesstransformer/models/__init__.py b/chesstransformer/models/__init__.py deleted file mode 100644 index 5f1c61c6771a75a9b8f3c160f8125e14d6894905..0000000000000000000000000000000000000000 --- a/chesstransformer/models/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""This module contains all the models.""" diff --git a/chesstransformer/models/tokenizer/__init__.py b/chesstransformer/models/tokenizer/__init__.py deleted file mode 100644 index d8441ec6110d9a064a3db5a735a46057825307b6..0000000000000000000000000000000000000000 --- a/chesstransformer/models/tokenizer/__init__.py +++ /dev/null @@ -1,93 +0,0 @@ -from tokenizers import Tokenizer -from tokenizers import models, pre_tokenizers, trainers, processors, normalizers -from .move_tokenizer import MoveTokenizer -from .position_tokenizer import PostionTokenizer - - -def create_bpe_tokenizer( - vocab_size: int = 2000, -) -> tuple[Tokenizer, trainers.BpeTrainer]: - """ - Create a BPE tokenizer for chess moves. - - The tokenizer uses Byte-Pair Encoding (BPE) with ByteLevel pre-tokenization - to handle the unique structure of chess moves. The token is used to - explicitly separate each move, ensuring clear move boundaries. - - Special tokens included: - - : Padding token - - : Start of sequence token - - : End of sequence token - - : Move separator token - - <1-0>: White wins - - <0-1>: Black wins - - <1/2-1/2>: Draw - - : Unknown token - - Args: - vocab_size: Size of the vocabulary (default: 2000) - - Returns: - A Tokenizer object and trainer - """ - - # Initialize a tokenizer with BPE model - encoder = Tokenizer(models.BPE(unk_token="")) - encoder.normalizer = normalizers.Sequence([]) # No normalization needed for chess moves - - # remove the white space pre-tokenizer - encoder.pre_tokenizer = pre_tokenizers.Whitespace() - - # Setup trainer with special tokens, including space - trainer = trainers.BpeTrainer( - vocab_size=vocab_size, - special_tokens=[ - "", - "", - "", - "<1-0>", - "<0-1>", - "<1/2-1/2>", - "", - "", - ], - show_progress=True, - min_frequency=2, - initial_alphabet=[ - "a", - "b", - "c", - "d", - "e", - "f", - "g", - "h", - "1", - "2", - "3", - "4", - "5", - "6", - "7", - "8", - "q", - "k", - "r", - "b", - "n", # Piece notations - ], - ) - - # Add post-processing to add special tokens - encoder.post_processor = processors.TemplateProcessing( - single=" $A ", - special_tokens=[ - ("", 1), - ("", 2), - ], - ) - - return encoder, trainer - - -__all__ = ["create_bpe_tokenizer", "MoveTokenizer", "PostionTokenizer"] diff --git a/chesstransformer/models/tokenizer/alphazero_move_encoder.py b/chesstransformer/models/tokenizer/alphazero_move_encoder.py deleted file mode 100644 index 69fda46f509655dbe6978ce8417a4dd3597de0cc..0000000000000000000000000000000000000000 --- a/chesstransformer/models/tokenizer/alphazero_move_encoder.py +++ /dev/null @@ -1,127 +0,0 @@ -"""AlphaZero-style action encoding for chess moves. - -Encodes moves as (from_square, action_plane) pairs using the 8×8×73 -representation from the AlphaZero paper (Silver et al., 2018). - -The 73 action planes decompose as: - 0–55: Queen-type moves — 8 directions × 7 distances - 56–63: Knight moves — 8 L-shaped jumps - 64–72: Underpromotions — 3 directions × 3 piece types (knight/bishop/rook) - -Queen promotions are encoded as regular queen-type moves (distance-1 to the -last rank). Underpromotions get their own dedicated planes. -""" - -import chess -import torch - -NUM_ACTION_PLANES = 73 - -# Direction vectors (file_delta, rank_delta) for queen-type moves -QUEEN_DIRECTIONS = [ - (0, 1), # N - (1, 1), # NE - (1, 0), # E - (1, -1), # SE - (0, -1), # S - (-1, -1), # SW - (-1, 0), # W - (-1, 1), # NW -] - -# Knight jump offsets (file_delta, rank_delta) -KNIGHT_JUMPS = [ - (1, 2), (2, 1), (2, -1), (1, -2), - (-1, -2), (-2, -1), (-2, 1), (-1, 2), -] - -# Underpromotion piece types (queen promotion is a regular queen-type move) -UNDERPROMO_PIECES = [chess.KNIGHT, chess.BISHOP, chess.ROOK] - -# Pre-compute knight jump lookup for O(1) detection -_KNIGHT_JUMP_INDEX = {(df, dr): i for i, (df, dr) in enumerate(KNIGHT_JUMPS)} - - -def move_to_action_plane(from_sq: int, to_sq: int, promotion: int | None = None) -> int: - """Convert a chess move to its action plane index (0–72). - - Args: - from_sq: Source square (0–63, python-chess ordering). - to_sq: Destination square (0–63). - promotion: Promotion piece type (chess.QUEEN, chess.KNIGHT, etc.) or None. - - Returns: - Action plane index in [0, 72]. - """ - df = (to_sq % 8) - (from_sq % 8) - dr = (to_sq // 8) - (from_sq // 8) - - # ── Underpromotion ─────────────────────────────────────────────────── - if promotion is not None and promotion != chess.QUEEN: - # Direction: file delta ∈ {-1, 0, +1} → index 0, 1, 2 - dir_idx = df + 1 - piece_idx = UNDERPROMO_PIECES.index(promotion) - return 64 + dir_idx * 3 + piece_idx - - # ── Knight move ────────────────────────────────────────────────────── - knight_idx = _KNIGHT_JUMP_INDEX.get((df, dr)) - if knight_idx is not None: - return 56 + knight_idx - - # ── Queen-type move (includes queen promotions) ────────────────────── - distance = max(abs(df), abs(dr)) - dir_f = (df // distance) if df != 0 else 0 - dir_r = (dr // distance) if dr != 0 else 0 - dir_idx = QUEEN_DIRECTIONS.index((dir_f, dir_r)) - return dir_idx * 7 + (distance - 1) - - -def action_to_move(from_sq: int, plane: int) -> tuple[int, int | None]: - """Decode an action plane back to (to_square, promotion_piece | None). - - For queen-type moves landing on promotion ranks, the caller must check - whether the source piece is a pawn and add ``chess.QUEEN`` promotion. - - Args: - from_sq: Source square (0–63). - plane: Action plane index (0–72). - - Returns: - (to_sq, promotion_piece) — promotion_piece is set only for underpromotions. - """ - from_file = from_sq % 8 - from_rank = from_sq // 8 - - if plane < 56: - # Queen-type move - dir_idx = plane // 7 - distance = plane % 7 + 1 - df, dr = QUEEN_DIRECTIONS[dir_idx] - to_file = from_file + df * distance - to_rank = from_rank + dr * distance - return to_rank * 8 + to_file, None - - if plane < 64: - # Knight move - df, dr = KNIGHT_JUMPS[plane - 56] - to_file = from_file + df - to_rank = from_rank + dr - return to_rank * 8 + to_file, None - - # Underpromotion - promo_idx = plane - 64 - dir_idx = promo_idx // 3 - piece_idx = promo_idx % 3 - df = dir_idx - 1 # 0→-1, 1→0, 2→+1 - to_file = from_file + df - to_rank = 7 if from_rank == 6 else 0 # white promotes to rank 8, black to rank 1 - return to_rank * 8 + to_file, UNDERPROMO_PIECES[piece_idx] - - -def build_legal_moves_planes(board: chess.Board) -> torch.Tensor: - """Build a (64, 73) boolean mask of legal moves in action-plane format.""" - mask = torch.zeros(64, NUM_ACTION_PLANES, dtype=torch.bool) - for move in board.legal_moves: - plane = move_to_action_plane(move.from_square, move.to_square, move.promotion) - mask[move.from_square, plane] = True - return mask diff --git a/chesstransformer/models/tokenizer/move_tokenizer.py b/chesstransformer/models/tokenizer/move_tokenizer.py deleted file mode 100644 index 63907ff5b5057734920062c8065c8ddde7b8450a..0000000000000000000000000000000000000000 --- a/chesstransformer/models/tokenizer/move_tokenizer.py +++ /dev/null @@ -1,38 +0,0 @@ -import json -from pathlib import Path - -DATA_DIR = Path(__file__).parents[2] / "data" - - -class MoveTokenizer: - def __init__(self, vocab_path=DATA_DIR / "tokenizer_models/chess_moves_vocab.json"): - with open(vocab_path, "r") as f: - self.vocab = json.load(f) - self.inv_vocab = {v: k for k, v in self.vocab.items()} - - def encode(self, move: str) -> int: - """Encode a chess move string into a token ID. - Args: - move: A string representing a chess move in UCI format (e.g., "e2e4", "g1f3"). - Returns: - An integer token ID representing the move. - """ - if move not in self.vocab: - raise ValueError(f"Move '{move}' not in vocabulary.") - return self.vocab[move] - - def decode(self, token_id: int) -> str: - """Decode a token ID back into a chess move string. - Args: - token_id: An integer token ID representing the move. - Returns: - A string representing a chess move in UCI format. - """ - if token_id not in self.inv_vocab: - raise ValueError(f"Token ID '{token_id}' not in vocabulary.") - return self.inv_vocab[token_id] - - @property - def vocab_size(self) -> int: - """Return the size of the vocabulary.""" - return len(self.vocab) diff --git a/chesstransformer/models/tokenizer/position_tokenizer.py b/chesstransformer/models/tokenizer/position_tokenizer.py deleted file mode 100644 index 7ef254ca372c2484b0b45bf52000a5b7a809b727..0000000000000000000000000000000000000000 --- a/chesstransformer/models/tokenizer/position_tokenizer.py +++ /dev/null @@ -1,88 +0,0 @@ -import chess - -_PIECE_TOKEN = { - (chess.PAWN, chess.WHITE): 1, (chess.KNIGHT, chess.WHITE): 2, - (chess.BISHOP, chess.WHITE): 3, (chess.ROOK, chess.WHITE): 4, - (chess.QUEEN, chess.WHITE): 5, (chess.KING, chess.WHITE): 6, - (chess.PAWN, chess.BLACK): 7, (chess.KNIGHT, chess.BLACK): 8, - (chess.BISHOP, chess.BLACK): 9, (chess.ROOK, chess.BLACK): 10, - (chess.QUEEN, chess.BLACK): 11, (chess.KING, chess.BLACK): 12, -} - - -class PostionTokenizer: - """A simple tokenizer for chess board positions. - Each square on the board is represented by a token ID based on the piece occupying it. - Empty squares are represented by the token ID 0. - The board is represented as an 8x8 grid, flattened into a list of 64 tokens. - """ - - def __init__(self): - self.vocab = { - "P": 1, - "N": 2, - "B": 3, - "R": 4, - "Q": 5, - "K": 6, - "p": 7, - "n": 8, - "b": 9, - "r": 10, - "q": 11, - "k": 12, - ".": 0, - } - self.inv_vocab = {v: k for k, v in self.vocab.items()} - - def encode(self, board: chess.Board) -> list[int]: - """Encode a chess.Board object into a list of token IDs. - The board is represented as an 8x8 grid, flattened into a list of 64 tokens. - - Args: - board: A chess.Board object - - Returns: - List of token IDs representing the board position - """ - result = [0] * 64 - for sq, piece in board.piece_map().items(): - result[sq] = _PIECE_TOKEN[(piece.piece_type, piece.color)] - return result - - def decode(self, token_ids: list[int]) -> chess.Board: - """Decode a list of token IDs back into a chess board string. - Args: - token_ids: List of token IDs representing the board position - Returns: - A chess.Board object - """ - chars = [self.inv_vocab[token_id] for token_id in token_ids] - rows = ["".join(chars[i * 8 : (i + 1) * 8]) for i in range(8)][::-1] # Reverse to get the correct order - board_str = "\n".join(rows) - board = self._ascii2board(board_str) - return board - - def _ascii2board(self, ascii_board: str) -> chess.Board: - """Convert an ASCII board representation back to a chess.Board object. - Args: - ascii_board: String representation of the board (8 lines of 8 characters) - Returns: - A chess.Board object - """ - board = chess.Board.empty() - rows = ascii_board.split("\n") - for rank in range(8): - file = 0 - for char in rows[7 - rank]: # Reverse the order of ranks - if char in self.vocab and char != ".": - square = chess.square(file, rank) - piece = chess.Piece.from_symbol(char) - board.set_piece_at(square, piece) - file += 1 - return board - - @property - def vocab_size(self) -> int: - """Return the size of the vocabulary.""" - return len(self.vocab) diff --git a/chesstransformer/models/tokenizer/train_bpe_tokenizer.py b/chesstransformer/models/tokenizer/train_bpe_tokenizer.py deleted file mode 100644 index 5212e8ddad45b66cf22bd812af6fc4f6335bd5fe..0000000000000000000000000000000000000000 --- a/chesstransformer/models/tokenizer/train_bpe_tokenizer.py +++ /dev/null @@ -1,94 +0,0 @@ -from pathlib import Path -import argparse - -from chesstransformer.models.tokenizer import create_bpe_tokenizer - - -def arg_parser(): - parser = argparse.ArgumentParser(description="Train a BPE tokenizer for chess moves.") - parser.add_argument( - "--vocab_size", - type=int, - default=2000, - help="Size of the vocabulary (default: 2000)", - ) - parser.add_argument( - "--output_dir", - type=str, - help="Directory to save the trained tokenizer", - required=True, - ) - parser.add_argument( - "--dataset_path", - type=str, - help="Path to the lichess dataset file (PGN format)", - required=True, - ) - - parser.add_argument( - "--num_samples", - type=int, - default=100000, - help="Number of games to sample for training (default: 100000)", - ) - - parser.add_argument( - "--notation", - type=str, - choices=["uci", "san"], - default="uci", - help="Notation format for moves (default: uci)", - ) - - args = parser.parse_args() - return args - - -def main(): - args = arg_parser() - vocab_size = args.vocab_size - output_dir = Path(args.output_dir) - dataset_path = Path(args.dataset_path) - num_samples = args.num_samples - notation = args.notation - - output_dir.mkdir(parents=True, exist_ok=True) - - print(f"Creating BPE tokenizer with vocab size {vocab_size}...") - tokenizer, trainer = create_bpe_tokenizer(vocab_size=vocab_size) - - print(f"Loading dataset from {dataset_path}...") - from chesstransformer.datasets.lichess import extract_games_optimized - - games = extract_games_optimized(dataset_path, num_games=num_samples) - - print(f"Extracting moves in {notation} notation...") - print("Using token to separate moves...") - if notation == "uci": - move_sequences = ("".join([move.uci() for move in game.mainline_moves()]) for game in games) - elif notation == "san": - move_sequences = ( - "".join( - [ - (lambda board, move: (board.san(move), board.push(move))[0])(board, move) - for board in [game.board()] - for move in game.mainline_moves() - ] - ) - for game in games - ) - else: - raise ValueError(f"Unsupported notation: {notation}") - - print(f"Training tokenizer on {num_samples} games...") - tokenizer.train_from_iterator(move_sequences, trainer=trainer) - - tokenizer_path = output_dir / f"bpe_tokenizer_vocab{vocab_size}.json" - print(f"Saving tokenizer to {tokenizer_path}...") - tokenizer.save(str(tokenizer_path)) - - print("Tokenizer training complete.") - - -if __name__ == "__main__": - main() diff --git a/chesstransformer/models/transformer/__init__.py b/chesstransformer/models/transformer/__init__.py deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 diff --git a/chesstransformer/models/transformer/attention.py b/chesstransformer/models/transformer/attention.py deleted file mode 100644 index 9ab0951b2f45417c9b8c04401acad5b4830153a5..0000000000000000000000000000000000000000 --- a/chesstransformer/models/transformer/attention.py +++ /dev/null @@ -1,228 +0,0 @@ -"""This module implements attention mechanisms for LLMs.""" - -import torch -import torch.nn as nn -import torch.nn.functional as F - -from chesstransformer.models.transformer.rope import RoPEEmbedding - - -class MultiHeadAttention(nn.Module): - def __init__( - self, d_in, d_out, num_heads, context_length, qkv_bias=False, dropout=0.0, mask_future=True, apply_rope=False - ): - super().__init__() - assert d_out % num_heads == 0, "d_out must be divisible by num_heads" - self.num_heads = num_heads - self.d_out = d_out - self.d_head = d_out // num_heads - self.mask_future = mask_future - self.W_query = nn.Linear(d_in, d_out, bias=qkv_bias) - self.W_key = nn.Linear(d_in, d_out, bias=qkv_bias) - self.W_value = nn.Linear(d_in, d_out, bias=qkv_bias) - self.out_proj = nn.Linear(d_out, d_out) - self.dropout = nn.Dropout(dropout) - self.apply_rope = apply_rope - - if self.apply_rope: - self.rope = RoPEEmbedding(dim=self.d_head, max_position_embeddings=context_length) - - self.register_buffer("mask", torch.triu(torch.ones(context_length, context_length), diagonal=1)) - - def forward(self, x): - """ - Computes multi-head self-attention. - - Args: - x: Input tensor of shape (batch_size, seq_len, d_in) - - Returns: - Output tensor of shape (batch_size, seq_len, d_out) - """ - bz, nb_tockens, _ = x.shape - - # Linear projections - keys = self.W_key(x) - values = self.W_value(x) - queries = self.W_query(x) - - # Reshape for multi-head attention - keys = keys.view(bz, nb_tockens, self.num_heads, self.d_head).transpose(1, 2) - values = values.view(bz, nb_tockens, self.num_heads, self.d_head).transpose(1, 2) - queries = queries.view(bz, nb_tockens, self.num_heads, self.d_head).transpose(1, 2) - - if self.apply_rope: - keys = self.rope(keys) - queries = self.rope(values) - - # Compute attention scores - attention_scores = queries @ keys.transpose(2, 3) # (batch_size, num_heads, seq_len, seq_len) - - if self.mask_future: - # Apply mask - mask_bool = self.mask.bool()[:nb_tockens, :nb_tockens] - attention_scores = attention_scores.masked_fill(mask_bool, -torch.inf) - - # Compute attention weights - attention_weights = F.softmax(attention_scores / keys.shape[-1] ** 0.5, dim=-1) - attention_weights = self.dropout(attention_weights) - - # apply attention weights to values - context_vec = (attention_weights @ values).transpose(1, 2).contiguous() - - # Merge heads - context_vec = context_vec.view(bz, nb_tockens, self.d_out) - context_vec = self.out_proj(context_vec) - return context_vec - - -class PyTorchMultiHeadAttention(nn.Module): - def __init__(self, d_in, d_out, num_heads, dropout=0.0, qkv_bias=False, mask_future=True, apply_rope=False): - super().__init__() - - assert d_out % num_heads == 0, "d_out is indivisible by num_heads" - - self.num_heads = num_heads - self.head_dim = d_out // num_heads - self.d_out = d_out - self.mask_future = mask_future - self.apply_rope = apply_rope - - self.qkv = nn.Linear(d_in, 3 * d_out, bias=qkv_bias) - self.proj = nn.Linear(d_out, d_out) - self.dropout = dropout - self.rope = None # Placeholder for RoPE, if needed - if self.apply_rope: - self.rope = RoPEEmbedding(dim=self.head_dim) - - def forward(self, x): - batch_size, num_tokens, embed_dim = x.shape - - # (b, num_tokens, embed_dim) --> (b, num_tokens, 3 * embed_dim) - qkv = self.qkv(x) - - # (b, num_tokens, 3 * embed_dim) --> (b, num_tokens, 3, num_heads, head_dim) - qkv = qkv.view(batch_size, num_tokens, 3, self.num_heads, self.head_dim) - - # (b, num_tokens, 3, num_heads, head_dim) --> (3, b, num_heads, num_tokens, head_dim) - qkv = qkv.permute(2, 0, 3, 1, 4) - - # (3, b, num_heads, num_tokens, head_dim) -> 3 times (b, num_heads, num_tokens, head_dim) - queries, keys, values = qkv - - if self.apply_rope and self.rope is not None: - keys = self.rope(keys) - queries = self.rope(queries) - - use_dropout = 0.0 if not self.training else self.dropout - - context_vec = nn.functional.scaled_dot_product_attention( - queries, keys, values, attn_mask=None, dropout_p=use_dropout, is_causal=self.mask_future - ) - - # Combine heads, where self.d_out = self.num_heads * self.head_dim - context_vec = context_vec.transpose(1, 2).contiguous().view(batch_size, num_tokens, self.d_out) - - context_vec = self.proj(context_vec) - - return context_vec - - -class GroupedQueryAttention(nn.Module): - """ - Multi-head self-attention with grouped keys and values. - This implementation allows multiple attention heads to share the same keys and values, - reducing the number of parameters and computational cost. - - It works by dividing the attention heads into groups, where each group shares a set of keys and values. - - Example: - If there are 8 attention heads and 4 key-value groups, then each group will be shared by 2 attention heads. - - Args: - d_in: Input feature dimension - d_out: Output feature dimension - num_heads: Number of attention heads - num_kv_groups: Number of key-value groups (must divide num_heads) - dropout: Dropout probability - qkv_bias: Whether to include bias terms in the linear projections - mask_future: Whether to apply causal masking to prevent attention to future tokens - apply_rope: Whether to apply Rotary Positional Embeddings (RoPE) - Returns: - Output tensor of shape (batch_size, seq_len, d_out) - """ - - def __init__( - self, d_in, d_out, num_heads, num_kv_groups, dropout=0.0, qkv_bias=False, mask_future=True, apply_rope=False - ): - super().__init__() - - assert d_out % num_heads == 0, "d_out is indivisible by num_heads" - assert num_heads % num_kv_groups == 0, "num_heads is indivisible by num_kv_groups" - - self.num_heads = num_heads - self.num_kv_groups = num_kv_groups - self.head_dim = d_out // num_heads - self.d_out = d_out - - self.q_proj = nn.Linear(d_in, d_out, bias=qkv_bias) - self.k_proj = nn.Linear(d_in, num_kv_groups * self.head_dim, bias=qkv_bias) - self.v_proj = nn.Linear(d_in, num_kv_groups * self.head_dim, bias=qkv_bias) - self.group_size = num_heads // num_kv_groups - self.num_kv_groups = num_kv_groups - - self.proj = nn.Linear(d_out, d_out, bias=False) - self.dropout = nn.Dropout(dropout) - - self.mask_future = mask_future - self.apply_rope = apply_rope - if self.apply_rope: - self.rope = RoPEEmbedding(dim=self.head_dim) - - def forward(self, x): - batch_size, num_tokens, embed_dim = x.shape - - queries = self.q_proj(x) - keys = self.k_proj(x) - values = self.v_proj(x) - - queries = queries.view(batch_size, num_tokens, self.num_heads, self.head_dim).transpose(1, 2) - keys_new = keys.view(batch_size, num_tokens, self.num_kv_groups, self.head_dim).transpose(1, 2) - values_new = values.view(batch_size, num_tokens, self.num_kv_groups, self.head_dim).transpose(1, 2) - - keys = keys_new.repeat_interleave(self.group_size, dim=1) - values = values_new.repeat_interleave(self.group_size, dim=1) - - if self.apply_rope: - keys = self.rope(keys) - queries = self.rope(queries) - - use_dropout = 0.0 if not self.training else self.dropout.p - - context_vec = F.scaled_dot_product_attention( - queries, keys, values, attn_mask=None, dropout_p=use_dropout, is_causal=self.mask_future - ) - - context_vec = context_vec.transpose(1, 2).contiguous() - context_vec = context_vec.view(batch_size, num_tokens, self.d_out) - context_vec = self.proj(context_vec) - - return context_vec - - -if __name__ == "__main__": - # Simple test - batch_size = 2 - seq_len = 16 - d_in = 64 - d_out = 64 - num_heads = 8 - num_kv_groups = 4 - - x = torch.randn(batch_size, seq_len, d_in) - - attn = GroupedQueryAttention(d_in, d_out, num_heads, num_kv_groups, apply_rope=True) - output = attn(x) - - print("Input shape:", x.shape) - print("Output shape:", output.shape) diff --git a/chesstransformer/models/transformer/gpt.py b/chesstransformer/models/transformer/gpt.py deleted file mode 100644 index f46b5607b8674f4d5aae32d450545b57e5066985..0000000000000000000000000000000000000000 --- a/chesstransformer/models/transformer/gpt.py +++ /dev/null @@ -1,79 +0,0 @@ -"""This module implements GPT model architecture.""" - -import torch -import torch.nn as nn -from ..transformer.attention import MultiHeadAttention -from ..transformer.utils import LayerNorm, GELU - - -class FeedForward(nn.Module): - def __init__(self, cfg): - super().__init__() - self.layers = nn.Sequential( - nn.Linear(cfg["embed_dim"], 4 * cfg["embed_dim"]), - GELU(), - nn.Linear(4 * cfg["embed_dim"], cfg["embed_dim"]), - ) - - def forward(self, x): - return self.layers(x) - - -class TransformerBlock(nn.Module): - def __init__(self, cfg): - super().__init__() - self.att = MultiHeadAttention( - d_in=cfg["embed_dim"], - d_out=cfg["embed_dim"], - num_heads=cfg["num_heads"], - context_length=cfg["context_size"], - dropout=cfg["dropout"], - qkv_bias=cfg["qkv_bias"], - ) - self.feed_forward = FeedForward(cfg) - self.norm1 = LayerNorm(cfg["embed_dim"]) - self.norm2 = LayerNorm(cfg["embed_dim"]) - self.dropout_shortcut = nn.Dropout(cfg["dropout"]) - - def forward(self, x): - shortcut = x - x = self.norm1(x) - x = self.att(x) - x = self.dropout_shortcut(x) - x = x + shortcut - - shortcut = x - x = self.norm2(x) - x = self.feed_forward(x) - x = self.dropout_shortcut(x) - x = x + shortcut - - return x - - -class GPT2Model(nn.Module): - def __init__(self, cfg): - super().__init__() - self.token_embedding = nn.Embedding(cfg["vocab_size"], cfg["embed_dim"]) - self.position_embedding = nn.Embedding(cfg["context_size"], cfg["embed_dim"]) - self.dropout_embed = nn.Dropout(cfg["dropout"]) - self.transfomer_blocks = nn.Sequential(*[TransformerBlock(cfg) for _ in range(cfg["num_layers"])]) - self.final_norm = LayerNorm(cfg["embed_dim"]) - self.lm_head = nn.Linear(cfg["embed_dim"], cfg["vocab_size"], bias=False) - - def forward(self, x): - bz, sq_len = x.size() - - token_emb = self.token_embedding(x) # (bz, sq_len, embed_dim) - - positions = torch.arange(sq_len, device=x.device) - pos_emb = self.position_embedding(positions) # (sq_len, embed_dim) - - x = token_emb + pos_emb # (bz, sq_len, embed_dim) - x = self.dropout_embed(x) - - x = self.transfomer_blocks(x) - x = self.final_norm(x) - - logits = self.lm_head(x) # (bz, sq_len, vocab_size) - return logits diff --git a/chesstransformer/models/transformer/pos2move_v2.py b/chesstransformer/models/transformer/pos2move_v2.py deleted file mode 100644 index 8a96e1968d8e5b0dc8fc80fd991eacc62f88d25f..0000000000000000000000000000000000000000 --- a/chesstransformer/models/transformer/pos2move_v2.py +++ /dev/null @@ -1,311 +0,0 @@ -import torch -import torch.nn as nn -import torch.nn.functional as F - -NUM_ACTION_PLANES = 73 -BOARD_SQUARES = 64 -EXTRA_TOKENS = 3 # castling, en_passant, player -CONTEXT_SIZE = BOARD_SQUARES + EXTRA_TOKENS # 67 - - -def build_chess_relation_index(context_size: int = CONTEXT_SIZE) -> torch.Tensor: - """Precompute (T, T) relation index between every pair of tokens. - - Categories (8 total): - 0: same square / same token - 1: same file - 2: same rank - 3: same diagonal - 4: knight-reachable - 5: king-adjacent (Chebyshev <= 1) - 6: nearby (Manhattan <= 3) - 7: far - Game-state tokens (>= 64) get category 0 toward themselves and - a dedicated "global" category 7 toward all board squares. - """ - rel = torch.zeros(context_size, context_size, dtype=torch.long) - for i in range(context_size): - for j in range(context_size): - if i == j: - rel[i, j] = 0 - continue - if i >= BOARD_SQUARES or j >= BOARD_SQUARES: - # Any pair involving a game-state token: "global" bucket - rel[i, j] = 7 - continue - fi, ri = i % 8, i // 8 - fj, rj = j % 8, j // 8 - df, dr = abs(fi - fj), abs(ri - rj) - if df == 0: - rel[i, j] = 1 - elif dr == 0: - rel[i, j] = 2 - elif df == dr: - rel[i, j] = 3 - elif {df, dr} == {1, 2}: - rel[i, j] = 4 - elif df <= 1 and dr <= 1: - rel[i, j] = 5 - elif df + dr <= 3: - rel[i, j] = 6 - else: - rel[i, j] = 7 - return rel - - -_RELATION_INDEX: torch.Tensor = build_chess_relation_index() - - -class ReluSquared(nn.Module): - def forward(self, x): - return F.relu(x) ** 2 - -class ChessGroupedQueryAttention(nn.Module): - def __init__( - self, d_in, d_out, num_heads, num_kv_groups, context_size, dropout=0.0, qkv_bias=False - ): - super().__init__() - - assert d_out % num_heads == 0, "d_out is indivisible by num_heads" - assert num_heads % num_kv_groups == 0, "num_heads is indivisible by num_kv_groups" - - self.num_heads = num_heads - self.num_kv_groups = num_kv_groups - self.head_dim = d_out // num_heads - self.d_out = d_out - - self.q_proj = nn.Linear(d_in, d_out, bias=qkv_bias) - self.k_proj = nn.Linear(d_in, num_kv_groups * self.head_dim, bias=qkv_bias) - self.v_proj = nn.Linear(d_in, num_kv_groups * self.head_dim, bias=qkv_bias) - self.group_size = num_heads // num_kv_groups - - self.proj = nn.Linear(d_out, d_out, bias=False) - self.dropout = dropout - - self.q_norm = nn.RMSNorm(self.head_dim) - self.k_norm = nn.RMSNorm(self.head_dim) - - # Chess-geometry relative bias: 8 relation categories per head - # Massively fewer params than fully-learned (H, T, T) bias. - self.num_relations = 8 - self.bias_table = nn.Parameter(torch.zeros(num_heads, self.num_relations)) - self.register_buffer("rel_idx", _RELATION_INDEX, persistent=False) - - - def forward(self, x): - batch_size, num_tokens, embed_dim = x.shape - - queries = self.q_proj(x) - keys = self.k_proj(x) - values = self.v_proj(x) - - queries = queries.view(batch_size, num_tokens, self.num_heads, self.head_dim).transpose(1, 2) - keys_new = keys.view(batch_size, num_tokens, self.num_kv_groups, self.head_dim).transpose(1, 2) - values_new = values.view(batch_size, num_tokens, self.num_kv_groups, self.head_dim).transpose(1, 2) - - queries = self.q_norm(queries) - keys_new = self.k_norm(keys_new) - - # Expand K/V to full head count. At this tiny sequence length (67) the - # repeat_interleave is cheaper than SDPA's native enable_gqa path, which - # falls back to a slower kernel here (measured ~20% slower). - keys = keys_new.repeat_interleave(self.group_size, dim=1) - values = values_new.repeat_interleave(self.group_size, dim=1) - - # Build additive chess-geometry bias from the compact (H, 8) table. - # Shape: (1, H, T, T) so SDPA broadcasts it across the batch. - attn_bias = self.bias_table[:, self.rel_idx].unsqueeze(0) - - context_vec = F.scaled_dot_product_attention( - queries, keys, values, - attn_mask=attn_bias, - dropout_p=self.dropout if self.training else 0.0, - is_causal=False, - ) - - context_vec = context_vec.transpose(1, 2).contiguous() - context_vec = context_vec.view(batch_size, num_tokens, self.d_out) - context_vec = self.proj(context_vec) - - return context_vec - -class MLP(nn.Module): - def __init__(self, d_in, d_hidden, d_out, dropout=0.0): - super().__init__() - self.fc1 = nn.Linear(d_in, d_hidden) - self.act = ReluSquared() - self.fc2 = nn.Linear(d_hidden, d_out) - self.dropout = nn.Dropout(dropout) - - def forward(self, x): - x = self.fc1(x) - x = self.act(x) - x = self.dropout(x) - x = self.fc2(x) - return x - -class ChessTransformerLayer(nn.Module): - def __init__(self, dim, nb_heads, qkv_bias, context_size, dropout=0.1, layer_drop=0.0): - super().__init__() - self.attn = ChessGroupedQueryAttention( - d_in=dim, - d_out=dim, - num_heads=nb_heads, - num_kv_groups=nb_heads // 2, - context_size=context_size, - dropout=dropout, - qkv_bias=qkv_bias, - ) - self.mlp = MLP(dim, dim * 4, dim, dropout=dropout) - self.norm1 = nn.RMSNorm(dim) - self.norm2 = nn.RMSNorm(dim) - self.layer_drop = layer_drop - - def forward(self, x): - # Stochastic depth: with prob `layer_drop`, skip the entire layer. - # Applied independently to attn and mlp branches (sub-layer LayerDrop). - if self.training and self.layer_drop > 0.0: - # Per-sample keep mask would be more standard, but per-layer scalar matches your old behavior. - keep_attn = torch.empty(1, device=x.device, dtype=x.dtype).bernoulli_(1.0 - self.layer_drop) - keep_mlp = torch.empty(1, device=x.device, dtype=x.dtype).bernoulli_(1.0 - self.layer_drop) - x = x + keep_attn * self.attn(self.norm1(x)) - x = x + keep_mlp * self.mlp(self.norm2(x)) - else: - x = x + self.attn(self.norm1(x)) - x = x + self.mlp(self.norm2(x)) - return x - -class Pos2MoveV2(nn.Module): - def __init__( - self, - vocab_size: int = 13, - embed_dim: int = 512, - nb_transformer_layers: int = 2, - num_heads: int = 8, - dropout: float = 0.1, - kvq_bias: bool = False, - layer_drop: float = 0.0, - value_bounded: bool = False, - value_clamp: bool = False, - ): - super().__init__() - - self.token_embedding = nn.Embedding(vocab_size, embed_dim) - self.position_embedding = nn.Embedding(67, embed_dim) # 64 squares + 3 extra tokens - # Static position indices, kept as a buffer so we don't rebuild the - # arange (and a host->device copy) on every forward pass. - self.register_buffer("pos_index", torch.arange(67), persistent=False) - self.castling_embedding = nn.Embedding(16, embed_dim) # 4-bit bitmask: 0-15 - self.en_passant_embedding = nn.Embedding(9, embed_dim) # 8 files + no en passant (8) - self.player_embedding = nn.Embedding(2, embed_dim) # White or Black - - # Linearly increasing layer drop rate: deeper layers drop more. - # This is the "Deep Networks with Stochastic Depth" schedule. - drop_rates = [layer_drop * i / max(1, nb_transformer_layers - 1) - for i in range(nb_transformer_layers)] - - self.transformer_layers = nn.ModuleList( - [ - ChessTransformerLayer( - dim=embed_dim, - nb_heads=num_heads, - qkv_bias=kvq_bias, - context_size=67, # Max sequence length (64 squares + 3 extra tokens) - dropout=dropout, - layer_drop=drop_rates[i], - ) - for i in range(nb_transformer_layers) - ] - ) - - self.final_norm = nn.RMSNorm(embed_dim) - - policy_hidden = embed_dim // 2 - self.move_head = nn.Sequential( - nn.Linear(embed_dim, policy_hidden), - nn.GELU(), - nn.Linear(policy_hidden, NUM_ACTION_PLANES), - ) - - # Deeper value head: D → D//4 → GELU → 1 - # value_bounded appends a tanh so the output cannot leave the target's - # [-1, 1] range. Kept off by default: the shipped v2.1 weights were - # trained without it, and squashing them post-hoc changes their scale. - # The Tanh lands at index 3, so the Linear state-dict keys (0.*, 2.*) - # are identical either way and checkpoints stay interchangeable. - value_hidden = embed_dim // 4 - value_layers = [ - nn.Linear(embed_dim, value_hidden), - nn.GELU(), - nn.Linear(value_hidden, 1), - ] - if value_bounded: - value_layers.append(nn.Tanh()) - elif value_clamp: - # Minimal alternative to tanh for weights already trained unbounded: - # a hard clamp leaves every in-range output untouched and only edits - # the semantically impossible ones (a leaf "better than won"). v2.1 - # emits those on 0.76% of positions, reaching 1.039 -- and since MCTS - # maximises over leaf values, that tail is precisely what it chases. - # MEASURED 2026-08-19: on v2.1 this is a NO-OP -- the chosen move was - # identical on 25/25 opening positions at both 4000 and 8000 sims. A - # 4% excursion is too small to steer the search; it mattered for the - # cp-trained head only because that one reached 1.211. Don't re-run. - # Kept for unbounded heads that overshoot more; prefer value_bounded - # (tanh) when training a head from scratch. - value_layers.append(nn.Hardtanh(-1.0, 1.0)) - self.value_head = nn.Sequential(*value_layers) - - self._init_weights(nb_transformer_layers) - - def _init_weights(self, nb_layers: int): - """GPT-2 style init with depth-scaled residual projections. - - - All Linear/Embedding: N(0, 0.02) - - Residual projections (attn out + mlp out): scaled by 1/sqrt(2*N) - to keep residual stream variance bounded with depth. - """ - for module in self.modules(): - if isinstance(module, nn.Linear): - nn.init.normal_(module.weight, mean=0.0, std=0.02) - if module.bias is not None: - nn.init.zeros_(module.bias) - elif isinstance(module, nn.Embedding): - nn.init.normal_(module.weight, mean=0.0, std=0.02) - - # Scale down the projections that write into the residual stream - scale = (2 * nb_layers) ** -0.5 - for layer in self.transformer_layers: - with torch.no_grad(): - layer.attn.proj.weight.mul_(scale) - layer.mlp.fc2.weight.mul_(scale) - - def forward(self, board_tokens, player_token, castling_token, en_passant_token): - batch_size = board_tokens.size(0) - - token_emb = self.token_embedding(board_tokens) # (B, 64, D) - pos_emb = self.position_embedding(self.pos_index) # (67, D) - castling_emb = self.castling_embedding(castling_token).unsqueeze(1) # (B, 1, D) - en_passant_emb = self.en_passant_embedding(en_passant_token).unsqueeze(1) # (B, 1, D) - player_emb = self.player_embedding(player_token).unsqueeze(1) # (B, 1, D) - - x = token_emb + pos_emb[:64] # Add positional embedding to board tokens - x = torch.cat([ - x, - castling_emb + pos_emb[64], - en_passant_emb + pos_emb[65], - player_emb + pos_emb[66], - ], dim=1) # (B, 67, D) - - for layer in self.transformer_layers: - x = layer(x) - - x = self.final_norm(x) - - state_token = x[:, -3:, :].mean(dim=1) # Average the last 3 game-state tokens: (B, D) - - board_tokens_out = x[:, :64, :] # (B, 64, D) - move_logits = self.move_head(board_tokens_out) # (B, 64, NUM_ACTION_PLANES) - value_pred = self.value_head(state_token) # (B, 1) - - return move_logits, value_pred diff --git a/chesstransformer/models/transformer/position2move.py b/chesstransformer/models/transformer/position2move.py deleted file mode 100644 index d5d7a449837a225fb74020b7783c2e49d95be982..0000000000000000000000000000000000000000 --- a/chesstransformer/models/transformer/position2move.py +++ /dev/null @@ -1,329 +0,0 @@ -import torch -from torch import nn -import torch.nn.functional as F - -from chesstransformer.models.transformer.attention import GroupedQueryAttention - - -class RMSNorm(nn.Module): - """Root Mean Square Layer Normalization. - - More efficient than LayerNorm as it doesn't compute mean. - Used in Llama, Mistral, and other modern transformers. - """ - - def __init__(self, dim: int, eps: float = 1e-6): - super().__init__() - self.eps = eps - self.weight = nn.Parameter(torch.ones(dim)) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - # x: (batch, seq, dim) - rms = torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps) - return x * rms * self.weight - - -class SwiGLUFeedForward(nn.Module): - """SwiGLU Feed-Forward Network. - - Combines Swish activation with Gated Linear Units. - Better performance than standard GELU FFN. - Used in Llama 2, PaLM, and other modern transformers. - """ - - def __init__(self, embed_dim: int, hidden_dim: int = None, dropout: float = 0.0): - super().__init__() - # Default hidden_dim is ~2.67x embed_dim (compensates for extra params from gate) - hidden_dim = hidden_dim or int(embed_dim * 8 / 3) - # Round to nearest multiple of 64 for efficiency - hidden_dim = ((hidden_dim + 63) // 64) * 64 - - self.w1 = nn.Linear(embed_dim, hidden_dim, bias=False) # Up projection - self.w2 = nn.Linear(hidden_dim, embed_dim, bias=False) # Down projection - self.w3 = nn.Linear(embed_dim, hidden_dim, bias=False) # Gate projection - self.dropout = nn.Dropout(dropout) - - def forward(self, x: torch.Tensor) -> torch.Tensor: - # SwiGLU: w2(SiLU(w1(x)) * w3(x)) - return self.dropout(self.w2(F.silu(self.w1(x)) * self.w3(x))) - - -# Keep old FeedForward for backward compatibility -class FeedForward(nn.Module): - def __init__(self, embed_dim): - super().__init__() - self.layers = nn.Sequential( - nn.Linear(embed_dim, 4 * embed_dim), - nn.GELU(approximate="tanh"), - nn.Linear(4 * embed_dim, embed_dim), - ) - - def forward(self, x): - return self.layers(x) - - -class TransformerBlock(nn.Module): - def __init__( - self, - embed_dim, - num_heads, - num_kv_groups, - context_length, - dropout, - qkv_bias, - mask_future=False, - apply_rope=True, - use_swiglu=True, - ): - super().__init__() - self.att = GroupedQueryAttention( - d_in=embed_dim, - d_out=embed_dim, - num_heads=num_heads, - num_kv_groups=num_kv_groups, - dropout=dropout, - qkv_bias=qkv_bias, - mask_future=mask_future, - apply_rope=apply_rope, - ) - # Use SwiGLU by default, fallback to standard FFN - if use_swiglu: - self.feed_forward = SwiGLUFeedForward(embed_dim, dropout=dropout) - else: - self.feed_forward = FeedForward(embed_dim) - - # Use RMSNorm instead of LayerNorm - self.norm1 = RMSNorm(embed_dim) - self.norm2 = RMSNorm(embed_dim) - self.dropout_shortcut = nn.Dropout(dropout) - - def forward(self, x): - shortcut = x - x = self.norm1(x) - x = self.att(x) - x = self.dropout_shortcut(x) - x = x + shortcut - - shortcut = x - x = self.norm2(x) - x = self.feed_forward(x) - x = self.dropout_shortcut(x) - x = x + shortcut - - return x - - -class Position2MoveModel(nn.Module): - def __init__( - self, - vocab_size: int = 13, - move_vocab_size: int = 1856, - embed_dim: int = 512, - nb_transformer_layers: int = 8, - num_heads: int = 8, - num_kv_groups: int = 4, - dropout: float = 0.1, - kvq_bias: bool = False, - mask_future: bool = False, - rope: bool = True, - use_swiglu: bool = True, - use_col_row_emb: bool = False, - ): - super().__init__() - # Learnable CLS token for classification (instead of mean pooling) - self.cls_token = nn.Parameter(torch.randn(1, 1, embed_dim) * 0.02) - - # Board piece embeddings - self.token_embedding = nn.Embedding(vocab_size, embed_dim) - if not rope: - self.position_embedding = nn.Embedding(64, embed_dim) # 64 squares - self.player_embedding = nn.Embedding(2, embed_dim) # 2 players: white and black - - self.use_col_row_emb = use_col_row_emb - - if use_col_row_emb: - # Optional column and row embeddings for board squares - self.col_embedding = nn.Embedding(8, embed_dim) - self.row_embedding = nn.Embedding(8, embed_dim) - - # Additional game state embeddings - # Castling rights: 4 binary flags (white_king, white_queen, black_king, black_queen) - self.castling_embedding = nn.Embedding(16, embed_dim) # 2^4 = 16 combinations - - # En passant: 9 values (files a-h = 0-7, none = 8) - self.en_passant_embedding = nn.Embedding(9, embed_dim) - - # Halfmove clock: bucketed into ranges for 50-move rule awareness - # Buckets: 0, 1-5, 6-10, 11-20, 21-30, 31-40, 41-50, 50+ - self.halfmove_embedding = nn.Embedding(8, embed_dim) - - self.dropout = nn.Dropout(dropout) - self.transformer_blocks = nn.Sequential( - *[ - TransformerBlock( - embed_dim=embed_dim, - num_heads=num_heads, - num_kv_groups=num_kv_groups, - context_length=64 + 3 + 1, # 64 squares + 3 game state tokens + 1 CLS - dropout=dropout, - qkv_bias=kvq_bias, - mask_future=mask_future, - apply_rope=rope, - use_swiglu=use_swiglu, - ) - for _ in range(nb_transformer_layers) - ] - ) - # Final RMSNorm - self.norm = RMSNorm(embed_dim) - - self.lm_head = nn.Linear(embed_dim, move_vocab_size, bias=False) - - self._init_weights() - - def _init_weights(self): - torch.nn.init.normal_(self.token_embedding.weight, mean=0.0, std=0.02) - if hasattr(self, "position_embedding"): - torch.nn.init.normal_(self.position_embedding.weight, mean=0.0, std=0.02) - if self.use_col_row_emb: - torch.nn.init.normal_(self.col_embedding.weight, mean=0.0, std=0.02) - torch.nn.init.normal_(self.row_embedding.weight, mean=0.0, std=0.02) - - torch.nn.init.normal_(self.player_embedding.weight, mean=0.0, std=0.02) - torch.nn.init.normal_(self.castling_embedding.weight, mean=0.0, std=0.02) - torch.nn.init.normal_(self.en_passant_embedding.weight, mean=0.0, std=0.02) - torch.nn.init.normal_(self.halfmove_embedding.weight, mean=0.0, std=0.02) - - # init the q, k, v, and output projection layers using xavier initialization - for layer in self.transformer_blocks: - if isinstance(layer.att, GroupedQueryAttention): - torch.nn.init.xavier_uniform_(layer.att.q_proj.weight) - if layer.att.q_proj.bias is not None: - torch.nn.init.zeros_(layer.att.q_proj.bias) - torch.nn.init.xavier_uniform_(layer.att.k_proj.weight) - if layer.att.k_proj.bias is not None: - torch.nn.init.zeros_(layer.att.k_proj.bias) - torch.nn.init.xavier_uniform_(layer.att.v_proj.weight) - if layer.att.v_proj.bias is not None: - torch.nn.init.zeros_(layer.att.v_proj.bias) - torch.nn.init.xavier_uniform_(layer.att.proj.weight) - - # Initialize SwiGLU layers - if isinstance(layer.feed_forward, SwiGLUFeedForward): - torch.nn.init.xavier_uniform_(layer.feed_forward.w1.weight) - torch.nn.init.xavier_uniform_(layer.feed_forward.w2.weight) - torch.nn.init.xavier_uniform_(layer.feed_forward.w3.weight) - - torch.nn.init.xavier_uniform_(self.lm_head.weight) - - def _bucket_halfmove(self, halfmove: torch.Tensor) -> torch.Tensor: - """Convert halfmove clock values to bucket indices. - - Buckets: 0, 1-5, 6-10, 11-20, 21-30, 31-40, 41-50, 50+ - Uses searchsorted to avoid torch.where (better for MPS compilation). - """ - # Define bucket boundaries - boundaries = torch.tensor([1, 6, 11, 21, 31, 41, 51], device=halfmove.device) - # searchsorted gives us the bucket index directly - # Values less than 1 -> bucket 0 - # Values in [1, 6) -> bucket 1 - # Values in [6, 11) -> bucket 2, etc. - buckets = torch.searchsorted(boundaries, halfmove.float(), right=False) - buckets = torch.clamp(buckets, 0, 7) - return buckets.long() - - def forward(self, x, is_white, castling_rights=None, en_passant_file=None, halfmove_clock=None): - """ - Args: - x: Tensor of shape (batch_size, 64) containing token IDs for each square. - is_white: Tensor of shape (batch_size,) indicating if the player to move is white (True) or black (False). - castling_rights: Tensor of shape (batch_size,) with values 0-15 encoding 4 binary flags. - Bit 0: white kingside, Bit 1: white queenside, - Bit 2: black kingside, Bit 3: black queenside. - If None, defaults to all castling allowed (15). - en_passant_file: Tensor of shape (batch_size,) with values 0-7 for files a-h, or 8 for none. - If None, defaults to no en passant (8). - halfmove_clock: Tensor of shape (batch_size,) with halfmove clock values (0-100+). - If None, defaults to 0. - Returns: - logits: Tensor of shape (batch_size, move_vocab_size) containing - the logits for the next move prediction at each position. - """ - batch_size, seq_len = x.size() - assert seq_len == 64, "Input sequence length must be 64 (8x8 chess board)." - - device = x.device - - # Default values if not provided - if castling_rights is None: - castling_rights = torch.full((batch_size,), 15, dtype=torch.long, device=device) - if en_passant_file is None: - en_passant_file = torch.full((batch_size,), 8, dtype=torch.long, device=device) - if halfmove_clock is None: - halfmove_clock = torch.zeros(batch_size, dtype=torch.long, device=device) - - positions = torch.arange(seq_len, device=device).unsqueeze(0).expand(batch_size, -1) - token_emb = self.token_embedding(x) # (batch_size, 64, embed_dim) - if hasattr(self, "position_embedding"): - pos_emb = self.position_embedding(positions) # (batch_size, 64, embed_dim) - else: - pos_emb = torch.zeros_like(token_emb) # Fallback if RoPE is used - - player_ids = is_white.long().unsqueeze(1).expand(-1, seq_len) # (batch_size, 64) - - player_emb = self.player_embedding(player_ids) # (batch_size, 64, embed_dim) - - board_emb = token_emb + pos_emb + player_emb # (batch_size, 64, embed_dim) - - if self.use_col_row_emb: - cols = (positions % 8).long() # (batch_size, 64) - rows = (positions // 8).long() # (batch_size, 64) - col_emb = self.col_embedding(cols) # (batch_size, 64, embed_dim) - row_emb = self.row_embedding(rows) # (batch_size, 64, embed_dim) - board_emb = board_emb + col_emb + row_emb # (batch_size, 64, embed_dim) - - # Create game state tokens - castling_emb = self.castling_embedding(castling_rights.long()) # (batch_size, embed_dim) - en_passant_emb = self.en_passant_embedding(en_passant_file.long()) # (batch_size, embed_dim) - halfmove_bucket = self._bucket_halfmove(halfmove_clock.long()) - halfmove_emb = self.halfmove_embedding(halfmove_bucket) # (batch_size, embed_dim) - - # Stack game state tokens: (batch_size, 3, embed_dim) - game_state_tokens = torch.stack([castling_emb, en_passant_emb, halfmove_emb], dim=1) - - # Expand CLS token for batch: (batch_size, 1, embed_dim) - cls_tokens = self.cls_token.expand(batch_size, -1, -1) - - # Concatenate: [CLS] + board + game_state: (batch_size, 68, embed_dim) - x = torch.cat([cls_tokens, board_emb, game_state_tokens], dim=1) - x = self.dropout(x) - - x = self.transformer_blocks(x) # (batch_size, 68, embed_dim) - x = self.norm(x) # (batch_size, 68, embed_dim) - - # Use CLS token output for classification (instead of mean pooling) - x = x[:, 0, :] # (batch_size, embed_dim) - - logits = self.lm_head(x) # (batch_size, move_vocab_size) - return logits - - -if __name__ == "__main__": - # Example usage - model = Position2MoveModel() - batch_size = 2 - dummy_input = torch.randint(0, 13, (batch_size, 64)) # batch_size=2, seq_len=64 - is_white = torch.tensor([1, 0]) # First sample is white to move, second is black - - # With game state info - castling_rights = torch.tensor([15, 3]) # First: all castling, Second: only white can castle - en_passant_file = torch.tensor([8, 4]) # First: no EP, Second: EP on file e (4) - halfmove_clock = torch.tensor([0, 25]) # Halfmove counters - - # Forward pass with all info - logits = model(dummy_input, is_white, castling_rights, en_passant_file, halfmove_clock) - print("Output shape:", logits.shape) # Should be (2, move_vocab_size) - - # Also works without game state (backward compatible) - logits_simple = model(dummy_input, is_white) - print("Output shape (simple):", logits_simple.shape) diff --git a/chesstransformer/models/transformer/rope.py b/chesstransformer/models/transformer/rope.py deleted file mode 100644 index 50b3d53d96629911ce2999f052c2f5716020a95a..0000000000000000000000000000000000000000 --- a/chesstransformer/models/transformer/rope.py +++ /dev/null @@ -1,104 +0,0 @@ -"""This module implements Rotary Positional Embeddings (RoPE) as described in -the paper "RoFormer: Enhanced Transformer with Rotary Position Embedding" (Su et al., 2021). -""" - -import torch -import torch.nn as nn - - -class RoPEEmbedding(nn.Module): - """Rotary Positional Embedding module. - - This module applies rotary positional embeddings to the input tensor. - Works with input shape (batch, num_heads, seq_len, head_dim). - """ - - def __init__(self, dim: int, base: int = 10_000, max_position_embeddings: int = 2048): - """Initialize the RoPE embedding module. - - Args: - dim (int): Dimension of each attention head (head_dim). - base (int): Base for the frequency computation. Lower values = faster rotation. - Default 10,000 works well for long sequences. For short sequences - like chess (67 tokens), consider lower values like 1,000. - max_position_embeddings (int): Maximum number of position embeddings. - """ - super(RoPEEmbedding, self).__init__() - self.dim = dim - self.base = base - - # Compute inverse frequencies - inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim)) - - # Compute position encodings for all positions - position = torch.arange(max_position_embeddings, dtype=torch.float) - # (max_pos, dim/2) - idx_theta = torch.einsum("i, j -> i j", position, inv_freq) - - # Duplicate for both halves: (max_pos, dim) - idx_theta2 = torch.cat([idx_theta, idx_theta], dim=-1) - - # Shape: (1, 1, max_pos, dim) for broadcasting with (batch, heads, seq, dim) - self.register_buffer("cos_cached", idx_theta2.cos()[None, None, :, :], persistent=False) - self.register_buffer("sin_cached", idx_theta2.sin()[None, None, :, :], persistent=False) - - def _neg_half(self, x: torch.Tensor): - """Rotate tensor by swapping and negating halves. - - For RoPE, we need to compute: [-x2, x1] where x = [x1, x2] - This implements the rotation matrix multiplication efficiently. - - Args: - x (torch.Tensor): Input tensor of shape (..., dim). - - Returns: - torch.Tensor: Rotated tensor. - """ - d_2 = self.dim // 2 - x1 = x[..., :d_2] - x2 = x[..., d_2:] - return torch.cat([-x2, x1], dim=-1) - - def forward(self, x: torch.Tensor): - """Apply RoPE to the input tensor. - - Args: - x (torch.Tensor): Input tensor of shape (batch, num_heads, seq_len, head_dim). - - Returns: - torch.Tensor: Tensor with RoPE applied, same shape as input. - """ - # x shape: (batch, num_heads, seq_len, head_dim) - seq_len = x.shape[2] # Get seq_len from the correct dimension - - # Slice cached values to sequence length: (1, 1, seq_len, dim) - cos = self.cos_cached[:, :, :seq_len, :].to(x.device) - sin = self.sin_cached[:, :, :seq_len, :].to(x.device) - - # Apply rotary embedding: x * cos + rotate(x) * sin - x_rotated = self._neg_half(x) - return x * cos + x_rotated * sin - - -if __name__ == "__main__": - # Test with chess-like dimensions - batch_size = 2 - num_heads = 8 - seq_len = 67 # 64 squares + 3 game state tokens - head_dim = 64 - - rope = RoPEEmbedding(dim=head_dim, base=10_000, max_position_embeddings=128) - x = torch.randn(batch_size, num_heads, seq_len, head_dim) - - output = rope(x) - print(f"Input shape: {x.shape}") - print(f"Output shape: {output.shape}") - - # Verify positions are encoded differently - # Two different positions should produce different outputs - x_same = torch.ones(1, 1, 10, head_dim) - out = rope(x_same) - print(f"\nPosition encoding test (should be different):") - print(f" Position 0 norm: {out[0, 0, 0].norm():.4f}") - print(f" Position 5 norm: {out[0, 0, 5].norm():.4f}") - print(f" Position 0 vs 5 cosine sim: {torch.cosine_similarity(out[0, 0, 0], out[0, 0, 5], dim=0):.4f}") diff --git a/chesstransformer/models/transformer/utils.py b/chesstransformer/models/transformer/utils.py deleted file mode 100644 index 895616d7974df70f3c7951f4ec542339eb69e223..0000000000000000000000000000000000000000 --- a/chesstransformer/models/transformer/utils.py +++ /dev/null @@ -1,46 +0,0 @@ -"""Utility functions for models.""" - -import torch -import torch.nn as nn - - -class LayerNorm(nn.Module): - """Implements Layer Normalization""" - - def __init__(self, dim, eps=1e-5): - super().__init__() - self.eps = eps - self.gamma = nn.Parameter(torch.ones(dim)) - self.beta = nn.Parameter(torch.zeros(dim)) - - def forward(self, x): - """ - Forward pass of layer normalization - Args: - x: Input tensor of shape (batch_size, seq_length, dim) - Returns: - out: Layer-normalized tensor of the same shape as input - """ - - mean = x.mean(-1, keepdim=True) - var = x.var(-1, keepdim=True, unbiased=False) - x_hat = (x - mean) / torch.sqrt(var + self.eps) - out = self.gamma * x_hat + self.beta - return out - - -class GELU(nn.Module): - """Implements the GELU activation function""" - - def __init__(self): - super().__init__() - - def forward(self, x): - """ - Forward pass of GELU activation - Args: - x: Input tensor - Returns: - out: Tensor after applying GELU activation - """ - return 0.5 * x * (1 + torch.tanh(torch.sqrt(torch.tensor(2.0 / torch.pi)) * (x + 0.044715 * torch.pow(x, 3)))) diff --git a/chesstransformer/optimizer.py b/chesstransformer/optimizer.py deleted file mode 100644 index 2a4dd38f763b11f7da3c92abf7630367d703d872..0000000000000000000000000000000000000000 --- a/chesstransformer/optimizer.py +++ /dev/null @@ -1,206 +0,0 @@ -"""Combined AdamW + Muon optimizer. - -The two underlying optimizers are kept as separate ``torch.optim`` instances -internally; this class is a thin wrapper that exposes the standard -``torch.optim.Optimizer`` interface (``step``, ``zero_grad``, ``param_groups``, -``state_dict`` / ``load_state_dict``) so that LR schedulers, gradient -accumulation, and HuggingFace ``Accelerator`` treat it as a single optimizer. - -Routing rule (when constructed from an ``nn.Module``): - -* parameters whose name contains an ``embedding_keyword`` → AdamW (low LR) -* parameters whose name contains a ``head_keyword`` → AdamW (no decay) -* remaining parameters with ``ndim >= 2`` → Muon -* remaining parameters with ``ndim < 2`` (biases/norms) → AdamW (no decay) -""" - -from __future__ import annotations - -from typing import Iterable - -import torch -from torch import nn -from torch.optim import AdamW, Muon, Optimizer - - -class AdamWMuon(Optimizer): - """Wrapper that drives an inner ``AdamW`` and ``Muon`` in lock-step. - - Parameters - ---------- - model: - ``nn.Module`` whose parameters will be auto-routed by name. - lr: - Base AdamW learning rate (used for the ``other`` 1D parameter group). - lr_embedding, lr_head: - Per-group AdamW LR overrides. Default to ``lr``. - lr_muon: - Muon LR for ≥2D body weights. Default ``= 3 * lr`` (Muon tolerates a - higher LR than AdamW because updates are orthogonalised). - weight_decay: - AdamW weight decay applied to the embedding group. Heads and 1D - params get ``0.0`` by convention. - weight_decay_muon: - Muon weight decay. Default = ``weight_decay``. - embedding_keywords / head_keywords: - Substrings used to classify parameters by ``named_parameters`` key. - """ - - def __init__( - self, - model: nn.Module, - *, - lr: float = 3e-4, - lr_embedding: float | None = None, - lr_head: float | None = None, - lr_muon: float | None = None, - weight_decay: float = 0.1, - weight_decay_muon: float | None = None, - betas: tuple[float, float] = (0.9, 0.95), - eps: float = 1e-8, - muon_momentum: float = 0.95, - muon_nesterov: bool = True, - muon_ns_steps: int = 5, - embedding_keywords: Iterable[str] = ("embedding", "cls_token"), - head_keywords: Iterable[str] = ("lm_head", "value_head"), - ) -> None: - if not isinstance(model, nn.Module): - raise TypeError( - f"AdamWMuon expects an nn.Module to auto-route parameters by name, " - f"got {type(model).__name__}." - ) - - lr_embedding = lr if lr_embedding is None else lr_embedding - lr_head = lr if lr_head is None else lr_head - lr_muon = 3.0 * lr if lr_muon is None else lr_muon - weight_decay_muon = weight_decay if weight_decay_muon is None else weight_decay_muon - - embedding_keywords = tuple(embedding_keywords) - head_keywords = tuple(head_keywords) - - emb_params: list[torch.Tensor] = [] - head_params: list[torch.Tensor] = [] - other_params: list[torch.Tensor] = [] - muon_params: list[torch.Tensor] = [] - - for name, param in model.named_parameters(): - if not param.requires_grad: - continue - if any(kw in name for kw in embedding_keywords): - emb_params.append(param) - elif any(kw in name for kw in head_keywords): - head_params.append(param) - elif param.ndim >= 2: - muon_params.append(param) - else: - other_params.append(param) - - adamw_groups: list[dict] = [] - if emb_params: - adamw_groups.append({ - "params": emb_params, "lr": lr_embedding, - "weight_decay": weight_decay, "name": "adamw_embedding", - }) - if other_params: - adamw_groups.append({ - "params": other_params, "lr": lr, - "weight_decay": 0.0, "name": "adamw_other", - }) - if head_params: - adamw_groups.append({ - "params": head_params, "lr": lr_head, - "weight_decay": 0.0, "name": "adamw_head", - }) - - if not adamw_groups: - raise ValueError("No AdamW-eligible parameters found in model.") - - self.adamw = AdamW(adamw_groups, lr=lr, betas=betas, eps=eps, - weight_decay=weight_decay) - - if muon_params: - self.muon: Muon | None = Muon( - [{"params": muon_params, "lr": lr_muon, - "weight_decay": weight_decay_muon, "name": "muon_body"}], - lr=lr_muon, weight_decay=weight_decay_muon, - momentum=muon_momentum, nesterov=muon_nesterov, - ns_steps=muon_ns_steps, - ) - else: - self.muon = None - - # Initialise the ``Optimizer`` base with a placeholder group so - # ``isinstance(opt, Optimizer)`` checks (Accelerate, schedulers) pass - # and ``self.state`` / ``self.defaults`` exist. We then expose the - # *inner* groups via ``param_groups`` so schedulers mutate them in - # place and both sub-optimizers see the new LR. - all_params = emb_params + other_params + head_params + muon_params - self._init_done = False - super().__init__([{"params": all_params}], defaults={"lr": lr}) - self.param_groups = self._combined_param_groups() - self._init_done = True - - # ── helpers ───────────────────────────────────────────────────────── - def _combined_param_groups(self) -> list[dict]: - groups = list(self.adamw.param_groups) - if self.muon is not None: - groups += list(self.muon.param_groups) - return groups - - # ── Optimizer API ─────────────────────────────────────────────────── - @torch.no_grad() - def step(self, closure=None): - loss = None - if closure is not None: - with torch.enable_grad(): - loss = closure() - self.adamw.step() - if self.muon is not None: - self.muon.step() - return loss - - def zero_grad(self, set_to_none: bool = True) -> None: - self.adamw.zero_grad(set_to_none=set_to_none) - if self.muon is not None: - self.muon.zero_grad(set_to_none=set_to_none) - - def state_dict(self) -> dict: - return { - "adamw": self.adamw.state_dict(), - "muon": self.muon.state_dict() if self.muon is not None else None, - } - - def load_state_dict(self, state_dict: dict) -> None: - self.adamw.load_state_dict(state_dict["adamw"]) - if self.muon is not None and state_dict.get("muon") is not None: - self.muon.load_state_dict(state_dict["muon"]) - # Re-link in case sub-optimizers rebuilt their group dicts. - self.param_groups = self._combined_param_groups() - - def add_param_group(self, param_group) -> None: - if not getattr(self, "_init_done", False): - # Called from ``Optimizer.__init__`` with the placeholder group. - super().add_param_group(param_group) - return - raise NotImplementedError( - "add_param_group is not supported on AdamWMuon after construction; " - "build a new optimizer with the full parameter set instead." - ) - - def __repr__(self) -> str: - n_emb = sum(p.numel() for g in self.adamw.param_groups - if g.get("name") == "adamw_embedding" for p in g["params"]) - n_head = sum(p.numel() for g in self.adamw.param_groups - if g.get("name") == "adamw_head" for p in g["params"]) - n_other = sum(p.numel() for g in self.adamw.param_groups - if g.get("name") == "adamw_other" for p in g["params"]) - n_muon = (sum(p.numel() for g in self.muon.param_groups for p in g["params"]) - if self.muon is not None else 0) - return ( - f"AdamWMuon(emb={n_emb:,}, other_1d={n_other:,}, " - f"head={n_head:,}, muon_2d={n_muon:,})" - ) - - -# Backwards-compat alias for the previous skeleton class. -AdamWMuonOptim = AdamWMuon \ No newline at end of file diff --git a/chesstransformer/trainers/__init__.py b/chesstransformer/trainers/__init__.py deleted file mode 100644 index 522d991ec55e20cf8bd642f5cd2ba2efc92dac8c..0000000000000000000000000000000000000000 --- a/chesstransformer/trainers/__init__.py +++ /dev/null @@ -1,11 +0,0 @@ - - -__all__ = [ - "SelfPlayTrainer", - "SelfPlayEngine", - "GameRecord", - "MoveRecord", - "OpeningPositionSampler", - "compute_rewards", - "COMMON_OPENINGS", -] diff --git a/chesstransformer/trainers/moveseq2moveseq_trainer.py b/chesstransformer/trainers/moveseq2moveseq_trainer.py deleted file mode 100644 index a468f4b41b028e55c5c9eb7d5958817228f0de48..0000000000000000000000000000000000000000 --- a/chesstransformer/trainers/moveseq2moveseq_trainer.py +++ /dev/null @@ -1,342 +0,0 @@ -from pathlib import Path -from datetime import datetime - -from tqdm.auto import tqdm -import torch -import accelerate -from torch.utils.data import DataLoader -from torch.utils.data import random_split -from chesstransformer.datasets import LichessSimpleUciDataset -from chesstransformer.models.transformer.gpt import GPT2Model - - -ROOT_PATH = Path(__file__).parents[1] - - -def get_next_run_number(log_dir="logs"): - """Get the next run number by checking existing run directories.""" - log_path = Path(log_dir) - if not log_path.exists(): - return 1 - - # Find all directories that match the pattern "run_XXX" - existing_runs = [d.name for d in log_path.iterdir() if d.is_dir() and d.name.startswith("run_")] - - if not existing_runs: - return 1 - - # Extract run numbers and find the maximum - run_numbers = [] - for run_name in existing_runs: - try: - num = int(run_name.split("_")[1]) - run_numbers.append(num) - except (IndexError, ValueError): - continue - - return max(run_numbers) + 1 if run_numbers else 1 - - -def main(): - # Load the full dataset with LichessSimpleUciDataset - print("Loading dataset...") - full_dataset = LichessSimpleUciDataset( - dataset_path=ROOT_PATH.parents[1] / "data/Lichess Rated Games 2017.pgn.zst", - vocab_path=ROOT_PATH / "data/tokenizer_models/uci_vocab.json", - num_samples=1_000_000, # Load all available games - ) - - vocab_size = len(full_dataset.vocab) - print(f"Vocabulary size: {vocab_size}") - - # Split the dataset into training, validation, and test sets - val = 20_000 - test = 20_000 - train_size = len(full_dataset) - val - test - train_dataset, val_dataset, test_dataset = random_split( - full_dataset, - [train_size, val, test], - generator=torch.Generator().manual_seed(42), - ) - - print(f"Train size: {len(train_dataset)}") - print(f"Validation size: {len(val_dataset)}") - print(f"Test size: {len(test_dataset)}") - - def collate_fn(batch): - max_length = max(item["input_ids"].shape[0] for item in batch) - input_ids = torch.full((len(batch), max_length), fill_value=-100, dtype=torch.long) - target_ids = torch.full((len(batch), max_length), fill_value=-100, dtype=torch.long) - legal_moves_mask = torch.zeros((len(batch), max_length, vocab_size), dtype=torch.float32) - - for i, item in enumerate(batch): - length = item["input_ids"].shape[0] - input_ids[i, :length] = item["input_ids"] - target_ids[i, :length] = item["target_ids"] - legal_moves_mask[i, :length, :] = item["legal_moves_mask"] - - if max_length > config["context_size"]: - input_ids = input_ids[:, : config["context_size"]] - target_ids = target_ids[:, : config["context_size"]] - legal_moves_mask = legal_moves_mask[:, : config["context_size"], :] - - return { - "input_ids": input_ids, - "target_ids": target_ids, - "legal_moves_mask": legal_moves_mask, - } - - train_dl = DataLoader(train_dataset, batch_size=8, shuffle=True, collate_fn=collate_fn, drop_last=True) - val_dl = DataLoader(val_dataset, batch_size=8, shuffle=False, collate_fn=collate_fn) - test_dl = DataLoader(test_dataset, batch_size=8, shuffle=False, collate_fn=collate_fn) - - config = { - "vocab_size": vocab_size, - "context_size": 256, - "embed_dim": 512, - "num_heads": 8, - "num_layers": 8, - "dropout": 0.1, - "qkv_bias": False, - } - - model = GPT2Model(config) - print(model) - - # Generate unique run identifier - run_number = get_next_run_number("logs") - timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") - run_name = f"run_{run_number:03d}_{timestamp}" - - print(f"Starting training run: {run_name}") - - # Gradient accumulation settings - gradient_accumulation_steps = 8 # Effective batch size = 16 * 4 = 64 - - # Initialize accelerator with logging and gradient accumulation - accelerator = accelerate.Accelerator( - log_with="tensorboard", - project_dir=f"logs/{run_name}", - mixed_precision="fp16" if torch.cuda.is_available() else "no", - gradient_accumulation_steps=gradient_accumulation_steps, - ) - device = accelerator.device - print(f"Using device: {device}") - print(f"Gradient accumulation steps: {gradient_accumulation_steps}") - print(f"Effective batch size: {16 * gradient_accumulation_steps}") - model.to(device) - - # Initialize TensorBoard tracker - accelerator.init_trackers( - project_name="chess_transformer", - config={ - **config, - "run_name": run_name, - "run_number": run_number, - "timestamp": timestamp, - "learning_rate": 1e-3, - "weight_decay": 1e-1, - "num_epochs": 10, - "batch_size": 16, - "gradient_accumulation_steps": 8, - "effective_batch_size": 128, - "warmup_steps": 1000, - }, - ) - - optimizer = torch.optim.AdamW(model.parameters(), lr=5e-4, weight_decay=1e-1) - - # Calculate total training steps (accounting for gradient accumulation) - num_epochs = 10 - total_steps = (len(train_dl) // gradient_accumulation_steps) * num_epochs - warmup_steps = 1000 - - print(f"Total training steps: {total_steps}") - print(f"Warmup steps: {warmup_steps}") - - # Create linear scheduler with warmup - def get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps): - def lr_lambda(current_step): - if current_step < num_warmup_steps: - # Linear warmup - return float(current_step) / float(max(1, num_warmup_steps)) - # Linear decay - return max( - 0.0, float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps)) - ) - - return torch.optim.lr_scheduler.LambdaLR(optimizer, lr_lambda) - - scheduler = get_linear_schedule_with_warmup(optimizer, warmup_steps, total_steps) - - model, optimizer, train_dl, val_dl, scheduler = accelerator.prepare(model, optimizer, train_dl, val_dl, scheduler) - criterion = torch.nn.CrossEntropyLoss(ignore_index=-100) - - best_val_loss = float("inf") - global_step = 0 - - for epoch in range(num_epochs): - model.train() - total_loss = 0.0 - total_llm_loss = 0.0 - total_l2_loss = 0.0 - - loader = tqdm(train_dl, desc=f"Epoch {epoch + 1}/{num_epochs}") - for batch_idx, batch in enumerate(loader): - # Accelerate automatically handles gradient accumulation context - with accelerator.accumulate(model): - inputs = batch["input_ids"].to(device) - targets = batch["target_ids"].to(device) - legal_moves_mask = batch["legal_moves_mask"].to(device) - - logits = model(inputs) - - llm_loss = criterion(logits.flatten(0, 1), targets.flatten()) - - probas = torch.nn.functional.softmax(logits, dim=-1) - - ilegal_moves_probas = probas * (1 - legal_moves_mask) - l2_loss = torch.sum(ilegal_moves_probas**2, dim=-1).mean() - loss = llm_loss + 10 * l2_loss - - loader.set_postfix({"llm_loss": llm_loss.item(), "l2_loss": l2_loss.item(), "total_loss": loss.item()}) - - accelerator.backward(loss) - optimizer.step() - scheduler.step() # Update learning rate - optimizer.zero_grad() - - total_loss += loss.item() - total_llm_loss += llm_loss.item() - total_l2_loss += l2_loss.item() - - # Log step metrics only on sync steps (when gradients are actually applied) - if accelerator.sync_gradients: - # Get current learning rate - current_lr = scheduler.get_last_lr()[0] - - accelerator.log( - { - "train/step_loss": loss.item(), - "train/step_llm_loss": llm_loss.item(), - "train/step_l2_loss": l2_loss.item(), - "train/learning_rate": current_lr, - }, - step=global_step, - ) - - global_step += 1 - - avg_train_loss = total_loss / len(train_dl) - avg_train_llm_loss = total_llm_loss / len(train_dl) - avg_train_l2_loss = total_l2_loss / len(train_dl) - print(f"Epoch {epoch + 1}/{num_epochs}, Training Loss: {avg_train_loss:.4f}") - - # Validation - model.eval() - total_val_loss = 0.0 - total_val_llm_loss = 0.0 - total_val_l2_loss = 0.0 - with torch.no_grad(): - for batch in val_dl: - inputs = batch["input_ids"].to(device) - targets = batch["target_ids"].to(device) - legal_moves_mask = batch["legal_moves_mask"].to(device) - - logits = model(inputs) - - llm_loss = criterion(logits.flatten(0, 1), targets.flatten()) - - probas = torch.nn.functional.softmax(logits, dim=-1) - ilegal_moves_probas = probas * (1 - legal_moves_mask) - l2_loss = torch.sum(ilegal_moves_probas**2, dim=-1).mean() - loss = llm_loss + l2_loss - - total_val_loss += loss.item() - total_val_llm_loss += llm_loss.item() - total_val_l2_loss += l2_loss.item() - - avg_val_loss = total_val_loss / len(val_dl) - avg_val_llm_loss = total_val_llm_loss / len(val_dl) - avg_val_l2_loss = total_val_l2_loss / len(val_dl) - print(f"Epoch {epoch + 1}/{num_epochs}, Validation Loss: {avg_val_loss:.4f}") - - # Log epoch metrics - accelerator.log( - { - "train/epoch_loss": avg_train_loss, - "train/epoch_llm_loss": avg_train_llm_loss, - "train/epoch_l2_loss": avg_train_l2_loss, - "val/epoch_loss": avg_val_loss, - "val/epoch_llm_loss": avg_val_llm_loss, - "val/epoch_l2_loss": avg_val_l2_loss, - "epoch": epoch + 1, - }, - step=global_step, - ) - - # Save the best model - if avg_val_loss < best_val_loss: - best_val_loss = avg_val_loss - unwrapped_model = accelerator.unwrap_model(model) - torch.save(unwrapped_model.state_dict(), ROOT_PATH / "models/best_model.pth") - print(f"Best model saved with validation loss: {best_val_loss:.4f}") - - # Log best metrics - accelerator.log( - { - "best/val_loss": best_val_loss, - "best/epoch": epoch + 1, - }, - step=global_step, - ) - - # Testing - model.eval() - total_test_loss = 0.0 - total_test_llm_loss = 0.0 - total_test_l2_loss = 0.0 - with torch.no_grad(): - for batch in test_dl: - inputs = batch["input_ids"].to(device) - targets = batch["target_ids"].to(device) - legal_moves_mask = batch["legal_moves_mask"].to(device) - - logits = model(inputs) - - llm_loss = criterion(logits.flatten(0, 1), targets.flatten()) - - probas = torch.nn.functional.softmax(logits, dim=-1) - ilegal_moves_probas = probas * (1 - legal_moves_mask) - l2_loss = torch.sum(ilegal_moves_probas**2, dim=-1).mean() - loss = llm_loss + l2_loss - - total_test_loss += loss.item() - total_test_llm_loss += llm_loss.item() - total_test_l2_loss += l2_loss.item() - - avg_test_loss = total_test_loss / len(test_dl) - avg_test_llm_loss = total_test_llm_loss / len(test_dl) - avg_test_l2_loss = total_test_l2_loss / len(test_dl) - print(f"Test Loss: {avg_test_loss:.4f}") - - # Log test metrics - accelerator.log( - { - "test/loss": avg_test_loss, - "test/llm_loss": avg_test_llm_loss, - "test/l2_loss": avg_test_l2_loss, - }, - step=global_step, - ) - - # End tracking - accelerator.end_training() - print(f"\nTraining complete! Run: {run_name}") - print(f"TensorBoard logs saved to 'logs/{run_name}/'") - print("To view logs, run: tensorboard --logdir=logs") - print(f"To view this run only: tensorboard --logdir=logs/{run_name}") - - -if __name__ == "__main__": - main() diff --git a/chesstransformer/trainers/pos2move_v2_trainer.py b/chesstransformer/trainers/pos2move_v2_trainer.py deleted file mode 100644 index ca89f7857d0b22778ef085d11ac28a0235a2ece9..0000000000000000000000000000000000000000 --- a/chesstransformer/trainers/pos2move_v2_trainer.py +++ /dev/null @@ -1,1128 +0,0 @@ -#!/usr/bin/env python3 -"""Training script for Pos2MoveV2. - -Trains the v2 transformer with GQA + QK-norm + chess-geometry attention bias, -AlphaZero-style 64×73 action output and value head on HDF5 chess datasets. - -Usage: - python src/chesstransformer/trainers/pos2move_v2_trainer.py --data data/elite_db.h5 -""" - -from pathlib import Path -from datetime import datetime -import argparse -import json -import os -import random -import shutil -import sys - -# Make the checkout runnable without installing the package. `uv run` installs it into the -# venv, so this never fires locally -- but a bare `git clone` on Kaggle or a rented box has -# no chesstransformer on sys.path and every import below fails. scripts/build_shards.py, -# scripts/verify_shards.py and tests/conftest.py already do this; the trainer did not, which -# is exactly where it was first hit. -sys.path.insert(0, str(Path(__file__).resolve().parents[2])) - -import numpy as np -import torch -from torch.nn import functional as F -from torch.utils.data import DataLoader, Subset, random_split -from torch.optim.lr_scheduler import LambdaLR -from tqdm.auto import tqdm -import accelerate -from accelerate.utils import broadcast_object_list, set_seed - -from chesstransformer.datasets.flat_shard_dataset import ( - FlatShardDataset, - make_dataloader as make_shard_dataloader, - scatter_legal_planes, - worker_init_fn as shard_worker_init_fn, -) -from chesstransformer.datasets.h5_lichess_dataset import HDF5ChessDataset -from chesstransformer.distributed_muon import ( - DistributedMuon, - muon_momentum, - muon_weight_decay, -) -from chesstransformer.models.tokenizer.position_tokenizer import PostionTokenizer -from chesstransformer.models.transformer.pos2move_v2 import Pos2MoveV2, NUM_ACTION_PLANES - - -#: Model sizes. DDP replicates weights *and* optimizer state on every rank. -#: -#: The static column is **measured**, not derived: one optimizer step then -#: torch.cuda.memory_allocated(), on a 16 GB card. It comes out at ~8.4 bytes/param, not -#: the ~18 a generic "fp32 master + two Adam moments + grads" estimate gives, because the -#: optimizer is split -- 2D params go to Muon, which keeps a single momentum buffer, and -#: the AdamW params (norms, biases, embeddings' non-2D parts) are a small remainder. -#: An earlier version of this table used the 18 B/param estimate and overstated xl by 2.3x. -#: -#: Activations dominate and scale with micro-batch: measured ~76 MB/sample for `large` -#: under torch.compile (~90 MB uncompiled). That is what actually decides whether a config -#: fits, so the static column alone is not a fit test. -#: -#: ===== ============ ======== ============= ============================================= -#: name dim x layers params static/rank notes -#: ===== ============ ======== ============= ============================================= -#: base 256 x 16 11.7 M 0.10 GB anything -#: 46m 512 x 16 46.5 M 0.35 GB anything -#: large 768 x 24 156.4 M 1.23 GB measured 8.5 GB/rank total at micro-batch 96 -#: on a T4; micro-batch 128 fits, 160 OOMs on 16 GB -#: xl 1536 x 32 832.8 M ~6.4 GB extrapolated. Static alone would fit a 40 GB -#: card under DDP; whether activations do is -#: unmeasured -- measure before assuming FSDP. -#: ===== ============ ======== ============= ============================================= -#: -#: `xl` is deliberately oversized as a sharding/scaling testbed. It is not a bid for -#: playing strength -- 46M already lost its head-to-head against v2.1 at 44.8%. -PRESETS = { - "base": {"embed_dim": 256, "num_layers": 16, "num_heads": 8}, - "46m": {"embed_dim": 512, "num_layers": 16, "num_heads": 8}, - "large": {"embed_dim": 768, "num_layers": 24, "num_heads": 12}, - "xl": {"embed_dim": 1536, "num_layers": 32, "num_heads": 16}, -} - -torch.set_float32_matmul_precision('high') - - -def rank0_print(*a, **kw): - """print() on the main process only. - - Keyed off the RANK env var rather than accelerator.is_main_process so it also works - before the Accelerator is constructed -- dataset loading logs before that point. N - ranks echoing the same line is noise; N ranks echoing *different* lines is a - debugging trap, and the dataset banners are exactly where they would differ. - """ - if int(os.environ.get("RANK", 0)) == 0: - print(*a, **kw) - - -def resolve_precision(requested: str) -> str: - """Pick a mixed-precision mode this GPU can actually run. - - bf16 needs compute capability 8.0 (Ampere). Kaggle's T4 is Turing, 7.5 -- so the - trainer's bf16 default silently does not apply there, and a run that looks fine is - quietly not using tensor cores as intended. Fall back to fp16 (which Turing does have - tensor cores for) and say so, rather than let the first multi-GPU session discover it. - """ - # Accelerate spells "no mixed precision" as "no"; "fp32" is not a value it accepts. - # Passing it through raises ValueError, which means --precision fp32 has never worked - # and a CPU-only box (where the old code forced "fp32") could never start at all. - if not torch.cuda.is_available() or os.environ.get("ACCELERATE_USE_CPU"): - return "no" - if requested == "fp32": - return "no" - if requested == "bf16" and not torch.cuda.is_bf16_supported(): - cap = torch.cuda.get_device_capability(0) - rank0_print(f"WARNING: {torch.cuda.get_device_name(0)} is compute capability " - f"{cap[0]}.{cap[1]}; bf16 needs 8.0+. Falling back to fp16 " - f"(Accelerate adds a GradScaler). Pass --precision fp32 to opt out.") - return "fp16" - return requested - - -def unpack_batch(batch, device): - """Normalise a batch from either data path into the tensors the loss expects. - - The shard loader ships the legal mask as a ``(B, 64)`` uint16 index list — 64 KB per - batch of 512 against 2.4 MB for the dense ``(64, 73)`` bool mask — so the mask is - rebuilt here, on device, after the H2D copy. Doing it in the dataset would put the - 2.4 MB straight back on the wire and undo the entire point of the shard format. - """ - if "legal_idx" in batch: - legal_planes = scatter_legal_planes(batch["legal_idx"].to(device, non_blocking=True)) - else: - legal_planes = batch["legal_moves_planes"].to(device, non_blocking=True) - return { - "board": batch["position"].to(device, non_blocking=True).long(), - "player": batch["is_white"].to(device, non_blocking=True).long(), - "castling": batch["castling_rights"].to(device, non_blocking=True).long(), - "en_passant": batch["en_passant_file"].to(device, non_blocking=True).long(), - "from_sq": batch["from_square"].to(device, non_blocking=True).long(), - "action_plane": batch["action_plane"].to(device, non_blocking=True).long(), - "legal_planes": legal_planes, - # Narrow on the wire (int8/int16 out of the shard), widened here so both data - # paths hand compute_loss exactly the same dtypes. - "result": batch["result"].to(device, non_blocking=True).long(), - # Must stay bool: compute_loss uses it as a *mask* (`target_value[white_win & - # is_white]`). An int tensor there would silently become fancy indexing and - # scatter the value targets onto the wrong rows. - "is_white": batch["is_white"].to(device, non_blocking=True).bool(), - "move_number": batch["move_number"].to(device, non_blocking=True).long(), - } - - -def get_next_run_number(log_dir: str) -> int: - log_path = Path(log_dir) - if not log_path.exists(): - return 1 - run_numbers = [] - for d in log_path.iterdir(): - if d.is_dir() and d.name.startswith("run_"): - try: - run_numbers.append(int(d.name.split("_")[1])) - except (IndexError, ValueError): - continue - return max(run_numbers, default=0) + 1 - - -def point_project_config_at(project_config, run_dir) -> None: - """Move both project_dir and logging_dir onto the resolved run directory. - - Not ``set_directories(run_dir)``: that fills logging_dir only when it is None, and it is - not. ``ProjectConfiguration.__post_init__`` already defaulted it to whatever project_dir - the Accelerator was built with -- here the *parent*, logs/pos2move_v2, because the run - name is not known until after the process group exists (see main()). Moving project_dir - alone leaves the TensorBoard writer on the parent, where it appends the project name, so - every run's events pile into one shared logs/pos2move_v2/pos2move_v2 instead of landing - in the run directory beside that run's checkpoints. - """ - project_config.project_dir = str(run_dir) - project_config.logging_dir = str(run_dir) - - -def compute_loss( - move_logits, - value, - from_sq, - action_plane, - legal_moves_planes, - result, - is_white, - move_number, - value_loss_weight, - value_rampup_halfmoves=40, - label_smoothing: float = 0.0, -): - """Total loss = (label-smoothed) policy CE + value MSE. - - Returns - ------- - total_loss : scalar tensor (the only thing that gets backprop'd) - metrics : dict of detached scalar tensors for logging - - ce : standard cross-entropy on the full action space - - legal_ce : cross-entropy after masking to legal moves only - - value_loss : weighted MSE on the value head - - acc : top-1 accuracy on the full action space - - legal_acc : top-1 accuracy after masking to legal moves only - """ - B = move_logits.size(0) - - # Flatten (B, 64, 73) -> (B, 64*73). Upcast to fp32 for loss stability under bf16. - flat_logits = move_logits.reshape(B, -1).float() - flat_target = from_sq * NUM_ACTION_PLANES + action_plane - flat_mask = legal_moves_planes.reshape(B, -1).float() - - # ── Policy loss: label-smoothed CE over LEGAL moves only ──────────── - if label_smoothing > 0: - eps = label_smoothing - legal_count = flat_mask.sum(dim=-1, keepdim=True).clamp(min=1.0) - smooth = eps / legal_count - target_dist = flat_mask * smooth - idx = flat_target.unsqueeze(1) - target_dist.scatter_add_(1, idx, torch.full_like(idx, 1.0 - eps, dtype=target_dist.dtype)) - log_pred = F.log_softmax(flat_logits, dim=-1) - policy_loss = F.kl_div(log_pred, target_dist, reduction="batchmean") - else: - policy_loss = F.cross_entropy(flat_logits, flat_target) - - # ── Value loss: per-sample MSE, ramped up by move number ──────────── - target_value = torch.zeros_like(value) - white_win = result == 1 - black_win = result == 2 - target_value[white_win & is_white] = 1.0 - target_value[white_win & ~is_white] = -1.0 - target_value[black_win & is_white] = -1.0 - target_value[black_win & ~is_white] = 1.0 - - progress = (move_number.float() / value_rampup_halfmoves).clamp(max=1.0) - per_sample_value_loss = (value.float() - target_value) ** 2 - value_loss = (progress * per_sample_value_loss).mean() - - total_loss = policy_loss + value_loss_weight * value_loss - - # ── Metrics (no grad) ─────────────────────────────────────────────── - with torch.no_grad(): - ce_metric = F.cross_entropy(flat_logits, flat_target) - - masked_logits = flat_logits.masked_fill(flat_mask == 0, float("-inf")) - legal_ce_metric = F.cross_entropy(masked_logits, flat_target) - - preds = flat_logits.argmax(dim=-1) - acc = (preds == flat_target).float().mean() - - legal_preds = masked_logits.argmax(dim=-1) - legal_acc = (legal_preds == flat_target).float().mean() - - metrics = { - "ce": ce_metric, - "legal_ce": legal_ce_metric, - "value_loss": value_loss.detach(), - "acc": acc, - "legal_acc": legal_acc, - } - return total_loss, metrics - - -def create_lr_scheduler(optimizer, warmup_steps, total_steps, final_lr_ratio, - schedule="linear", warmdown_ratio=0.2): - """Build the LR multiplier schedule. - - ``wsd`` -- warmup, then **stable at peak**, then a linear warmdown over the final - ``warmdown_ratio`` of the run (nanochat's ``get_lr_multiplier``). ``linear`` -- warmup - then decay across the entire remainder, which is what this trainer used to do. - - WSD is the default for two reasons. It decouples the horizon from the schedule: peak LR - is held flat, so a run can be stopped or extended at any point in the stable phase and - only the warmdown re-run, where a decay-from-peak schedule bakes ``total_steps`` into - every step it takes. And it is the phase structure Muon's momentum schedule was designed - against -- momentum warms down *during the LR warmdown*, which only exists here. - - Note the asymmetry in defaults, which is deliberate: the CLI defaults to ``wsd`` for new - runs, but this function defaults to ``linear``. scheduler_config dicts persisted in - checkpoints from before this change carry no ``schedule`` key, and are replayed through - here on resume -- so the function default is what those runs get. Defaulting it to - ``wsd`` would silently change the LR shape of an in-flight run at the point it resumed. - """ - warmup_steps = max(1, warmup_steps) - total_steps = max(warmup_steps + 1, total_steps) - warmdown = max(1, round(warmdown_ratio * total_steps)) - - def lr_lambda(step): - if step < warmup_steps: - return float(step + 1) / float(warmup_steps) - if schedule == "wsd": - if step <= total_steps - warmdown: - return 1.0 - progress = max(0.0, min(1.0, (total_steps - step) / warmdown)) - return progress * 1.0 + (1 - progress) * final_lr_ratio - progress = (step - warmup_steps + 1) / float(max(1, total_steps - warmup_steps)) - return 1.0 - (1.0 - final_lr_ratio) * min(1.0, progress) - - return LambdaLR(optimizer, lr_lambda) - - -def save_trainer_state(checkpoint_dir, data_pass, global_step, best_val_loss, scheduler_config=None): - # "epoch" is written alongside "data_pass" only so a checkpoint from this trainer still - # loads in anything that predates the step paradigm. Nothing here reads it back. - state = {"data_pass": data_pass, "epoch": data_pass, - "global_step": global_step, "best_val_loss": best_val_loss} - if scheduler_config: - state["scheduler_config"] = scheduler_config - with (Path(checkpoint_dir) / "trainer_state.json").open("w") as f: - json.dump(state, f) - - -def load_trainer_state(checkpoint_dir): - path = Path(checkpoint_dir) / "trainer_state.json" - if not path.exists(): - return None - with path.open() as f: - return json.load(f) - - -# ── EMA helpers ────────────────────────────────────────────────────────── -# EMA state is kept in fp32 to avoid bf16 precision loss on the -# (1 - decay) * param update term (which is ~0.001 * param at decay=0.999 -# and would round to zero for many small values in bf16). - -def create_ema_state(model): - return {name: p.data.detach().float().clone() for name, p in model.named_parameters()} - - -@torch.no_grad() -def update_ema(model, ema_state, decay): - for name, param in model.named_parameters(): - # Cast live param to fp32 for the lerp; ema_state stays fp32. - ema_state[name].lerp_(param.data.float(), 1.0 - decay) - - -def swap_ema_weights(model, ema_state): - # Backup current (compute-dtype) weights into ema_state, load EMA weights - # into the model — cast to the model's dtype on the way in. - for name, param in model.named_parameters(): - tmp = param.data.detach().float().clone() - param.data.copy_(ema_state[name].to(param.dtype)) - ema_state[name].copy_(tmp) - - -def save_ema_state(ema_state, path): - torch.save(ema_state, path) - - -def load_ema_state(path, device): - return torch.load(path, map_location=device, weights_only=True) - - -def get_raw_model(model, accelerator): - m = accelerator.unwrap_model(model) - if hasattr(m, "_orig_mod"): - m = m._orig_mod - return m - - -def cleanup_old_checkpoints(checkpoint_dir, max_checkpoints): - checkpoints = sorted( - [d for d in Path(checkpoint_dir).iterdir() if d.is_dir() and d.name.startswith("checkpoint_step_")], - key=lambda x: int(x.name.split("_")[-1]), - ) - while len(checkpoints) > max_checkpoints: - shutil.rmtree(checkpoints.pop(0)) - -def main(): - default_data = Path(__file__).parents[3] / "data" / "elite_db.h5" - - parser = argparse.ArgumentParser(description="Train Pos2MoveV2 (clean)") - # Data - parser.add_argument("--data", type=str, default=str(default_data)) - parser.add_argument("--shards", type=str, default=None, - help="Directory of flat shards from scripts/build_shards.py. Bypasses " - "--data/--min-elo/--sample-weighting entirely: the sampling " - "distribution is frozen into the shard at build time.") - parser.add_argument("--min-elo", type=int, default=None) - parser.add_argument("--max-elo", type=int, default=None) - parser.add_argument("--sample-weighting", type=str, default="middlegame", choices=["uniform", "middlegame"]) - parser.add_argument("--skip-opening-plies", type=int, default=0) - parser.add_argument("--max-val-samples", type=int, default=50_000, - help="Cap on val/test size. The HDF5 path has always applied this; " - "the shard path needs it too since a reserved shard is much larger.") - # Training - parser.add_argument("--batch-size", type=int, default=1024) - parser.add_argument("--grad-accum", type=int, default=4) - parser.add_argument("--epochs", type=int, default=None, - help="DEPRECATED and ignored. Training length is --max-steps. Kept so " - "existing invocations do not hard-fail; it warns and does nothing.") - parser.add_argument("--lr", type=float, default=1e-3) - parser.add_argument("--lr-muon", type=float, default=2e-3) - parser.add_argument("--lr-embedding", type=float, default=4e-4) - parser.add_argument("--lr-head", type=float, default=None) - parser.add_argument("--warmup-steps", type=int, default=2000) - parser.add_argument("--final-lr-ratio", type=float, default=0.05) - parser.add_argument("--lr-schedule", type=str, default="wsd", choices=["wsd", "linear"], - help="'wsd' = warmup / stable at peak / linear warmdown over the last " - "--warmdown-ratio of the run. 'linear' = the previous behaviour, " - "decay from peak across the whole remainder.") - parser.add_argument("--warmdown-ratio", type=float, default=0.2, - help="Fraction of the run spent decaying, for --lr-schedule wsd. Muon's " - "momentum warmdown is aligned to the same window.") - parser.add_argument("--max-grad-norm", type=float, default=1.0) - parser.add_argument("--weight-decay", type=float, default=0.1) - # Loss weights - parser.add_argument("--value-loss-weight", type=float, default=5.0) - parser.add_argument("--label-smoothing", type=float, default=0.1) - # Model - parser.add_argument("--preset", type=str, default="base", choices=list(PRESETS), - help="Model size. See PRESETS for per-GPU DDP memory. Individual " - "--embed-dim/--num-layers/--num-heads override the preset.") - parser.add_argument("--embed-dim", type=int, default=None) - parser.add_argument("--num-layers", type=int, default=None) - parser.add_argument("--num-heads", type=int, default=None) - parser.add_argument("--dropout", type=float, default=0.05) - parser.add_argument("--layer-drop", type=float, default=0.1, - help="Stochastic depth rate. Linearly scales from 0 (first layer) to this value (last layer). Try 0.1.") # Checkpointing - parser.add_argument("--max-steps", type=int, default=50_000, - help="Total optimizer steps to train for. This is THE training-length " - "knob: it bounds the loop and sets the LR decay horizon, and it " - "means the same thing on both data paths and at any world size.") - parser.add_argument("--save-every", type=int, default=None, - help="DEPRECATED and ignored (was epoch-based checkpointing). " - "Use --save-steps.") - parser.add_argument("--save-steps", type=int, default=5000) - parser.add_argument("--eval-steps", type=int, default=1000, - help="Validate every N optimizer steps. Val loss selects the best " - "checkpoint, so this sets the resolution of that choice. 0 " - "disables periodic validation (a final one still runs).") - parser.add_argument("--max-checkpoints", type=int, default=5) - parser.add_argument("--resume-from", type=str, default=None) - # EMA - parser.add_argument("--ema-decay", type=float, default=0.999) - # Muon - parser.add_argument("--distributed-muon", action=argparse.BooleanOptionalAction, default=True, - help="Partition Newton-Schulz across ranks by whole parameter, so the " - "NS work and momentum state are divided instead of every rank " - "redundantly computing the same thing. No-op at world size 1.") - parser.add_argument("--muon-schedules", action=argparse.BooleanOptionalAction, default=True, - help="Schedule Muon momentum (0.85->0.97, down to 0.90 during warmdown) " - "and cosine-decay its weight decay to zero, as nanochat does.") - # Misc - parser.add_argument("--seed", type=int, default=42) - parser.add_argument("--precision", type=str, default="bf16", choices=["bf16", "fp16", "fp32"]) - parser.add_argument("--num-workers", type=int, default=12) - # store_true with default=True could never be turned off. BooleanOptionalAction - # gives a real --no-compile, which CPU/gloo testing and debugging both need. - parser.add_argument("--compile", action=argparse.BooleanOptionalAction, default=True) - parser.add_argument("--compile-mode", type=str, default="default", - choices=["default", "reduce-overhead", "max-autotune"]) - parser.add_argument("--compile-order", type=str, default="auto", - choices=["auto", "before-prepare", "after-prepare"], - help="Whether torch.compile runs before or after accelerator.prepare(). " - "'auto' = before on a single process (the ordering the 2.2x " - "single-GPU speedup was measured with), after under DDP so " - "Dynamo's DDPOptimizer engages. See the note at the call site.") - args = parser.parse_args() - - # Epochs are gone as a unit of training length. They were never comparable between the - # two data paths — the HDF5 dataset is indexed by *game* (738 optimizer steps/epoch) and - # the shard dataset by *sample* (11,495 for elite_k16, 50,505 for full_k4) — so the same - # --epochs N bought a 15-68x different amount of training, LR decay horizon and - # validation cadence depending only on which --data/--shards flag you passed. - for dead, replacement in (("epochs", "--max-steps"), ("save_every", "--save-steps")): - if getattr(args, dead) is not None: - rank0_print(f"WARNING: --{dead.replace('_', '-')} is deprecated and ignored; " - f"use {replacement}.") - if args.max_steps <= 0: - parser.error("--max-steps must be > 0") - - # Preset supplies the geometry; an explicit flag always wins over it. - preset = PRESETS[args.preset] - for flag, key in (("embed_dim", "embed_dim"), ("num_layers", "num_layers"), - ("num_heads", "num_heads")): - if getattr(args, flag) is None: - setattr(args, flag, preset[key]) - - set_seed(args.seed) - random.seed(args.seed) - np.random.seed(args.seed) - torch.manual_seed(args.seed) - torch.cuda.manual_seed_all(args.seed) - - # ── Logging ────────────────────────────────────────────────────────── - # The run directory has to be decided by ONE rank and told to the others. Every rank - # scanning logs/ for the next free run number is a race: they can pick the same number - # (two ranks writing one run) or different ones (N runs, N-1 of them silently empty), - # and mkdir(exist_ok=False) then crashes whichever rank loses. The timestamp in the - # name makes independent derivation impossible too -- ranks start milliseconds apart. - # - # Ordering note: the Accelerator must exist before the broadcast (it is what sets up - # the process group), but init_trackers needs the run dir. Hence build it against the - # parent, then point it at the resolved run dir with set_directories(). - log_dir = Path("logs") / "pos2move_v2" - log_dir.mkdir(parents=True, exist_ok=True) - - precision = resolve_precision(args.precision) - accelerator = accelerate.Accelerator( - log_with="tensorboard", - project_dir=str(log_dir), - mixed_precision=precision, - gradient_accumulation_steps=args.grad_accum, - ) - - if accelerator.is_main_process: - run_number = get_next_run_number(str(log_dir)) - run_name = f"run_{run_number:03d}_{datetime.now().strftime('%Y%m%d_%H%M%S')}" - else: - run_name = None - run_name = broadcast_object_list([run_name], from_process=0)[0] - - log_path = log_dir / run_name - checkpoint_dir = log_path / "checkpoints" - if accelerator.is_main_process: - checkpoint_dir.mkdir(parents=True, exist_ok=False) - # Every rank must see the directory before anyone writes a checkpoint into it. - accelerator.wait_for_everyone() - point_project_config_at(accelerator.project_configuration, log_path) - - # ── Dataset ────────────────────────────────────────────────────────── - use_shards = args.shards is not None - if use_shards: - # Flat memmap shards: the replay, tokenize and legal-move enumeration were all - # paid once at build time, and the val/test split is by whole shard (== whole - # game range) rather than by sample, so no game straddles the split. - train_set = FlatShardDataset(args.shards, "train") - val_set = FlatShardDataset(args.shards, "val") - test_set = FlatShardDataset(args.shards, "test") - - # Whole reserved shards hold far more than validation needs (478k samples at - # K=16). Cap them the way the HDF5 path does, with a fixed seed so val loss stays - # comparable across runs — it is what selects the best checkpoint. - def cap(ds, name): - if len(ds) <= args.max_val_samples: - return ds - g = np.random.default_rng(0xC0FFEE) - keep = np.sort(g.choice(len(ds), size=args.max_val_samples, replace=False)) - rank0_print(f" {name}: capped {len(ds):,} -> {args.max_val_samples:,} samples") - return Subset(ds, keep.tolist()) - - val_set = cap(val_set, "val") - test_set = cap(test_set, "test") - - # The shard loaders bypass accelerator.prepare() (see the note at prepare()), so - # rank splitting is NOT automatic here the way it is for the HDF5 path -- it has to - # be asked for. Without this every rank draws the identical batches from the same - # seeded RandomSampler, and DDP degenerates into N ranks computing one gradient N - # times: the loss curve looks healthy, the effective batch never grows, and the - # extra GPUs buy nothing. - # This is exactly why the Accelerator is constructed above the dataset section: - # DistributedSampler requires an initialised process group, and the Accelerator is - # what initialises it. Building the loaders first raises "Default process group has - # not been initialized". - world_size = accelerator.num_processes - train_loader = make_shard_dataloader(train_set, batch_size=args.batch_size, shuffle=True, - num_workers=args.num_workers, drop_last=True, - seed=args.seed, distributed=world_size > 1) - # Val/test are deliberately NOT sharded. Each rank evaluates the whole (capped) - # set and therefore computes an identical val loss, so best-model selection agrees - # on every rank by construction and needs no gather or padding-trim. The cost is - # N x redundant work on <=10k samples -- about two seconds -- against a class of - # bug where ranks disagree about which checkpoint is best and race to write it. - val_loader = make_shard_dataloader(val_set, batch_size=args.batch_size, shuffle=False, - num_workers=args.num_workers) - test_loader = make_shard_dataloader(test_set, batch_size=args.batch_size, shuffle=False, - num_workers=args.num_workers) - vocab_size = PostionTokenizer().vocab_size - rank0_print(f"Shards: {args.shards} (K={train_set.meta['k']}, " - f"mode={train_set.meta['sample_mode']}, seed={train_set.meta['seed']})") - else: - dataset = HDF5ChessDataset( - hdf5_path=args.data, - min_elo=args.min_elo, - max_elo=args.max_elo, - sample_weighting=args.sample_weighting, - skip_opening_plies=args.skip_opening_plies, - ) - - val_size = min(int(0.1 * len(dataset)), args.max_val_samples) - test_size = min(int(0.1 * len(dataset)), args.max_val_samples) - train_size = len(dataset) - val_size - test_size - train_set, val_set, test_set = random_split(dataset, [train_size, val_size, test_size]) - - # pin_memory lets the H2D copy run on the DMA engine and overlap with compute; - # without it `.to(device, non_blocking=True)` is silently synchronous. - train_loader = DataLoader(train_set, batch_size=args.batch_size, shuffle=True, - num_workers=args.num_workers, drop_last=True, - persistent_workers=True, prefetch_factor=4, pin_memory=True, - worker_init_fn=shard_worker_init_fn) - val_loader = DataLoader(val_set, batch_size=args.batch_size, shuffle=False, - num_workers=args.num_workers, pin_memory=True, - worker_init_fn=shard_worker_init_fn) - test_loader = DataLoader(test_set, batch_size=args.batch_size, shuffle=False, - num_workers=args.num_workers, pin_memory=True, - worker_init_fn=shard_worker_init_fn) - vocab_size = dataset.position_tokenizer.vocab_size - - rank0_print(f"Train: {len(train_set):,} | Val: {len(val_set):,} | Test: {len(test_set):,}") - - # ── Model ──────────────────────────────────────────────────────────── - model_config = { - "vocab_size": vocab_size, - "embed_dim": args.embed_dim, - "nb_transformer_layers": args.num_layers, - "num_heads": args.num_heads, - "dropout": args.dropout, - "kvq_bias": False, - "layer_drop": args.layer_drop, - } - if accelerator.is_main_process: - with (log_path / "model_config.json").open("w") as f: - json.dump(model_config, f, indent=2) - - # Effective batch scales with world size: every rank contributes its own micro-batch - # to the same all-reduced gradient. Reporting it without num_processes understates the - # real batch by N, which is exactly the number linear LR scaling is derived from. - effective_bs = args.batch_size * args.grad_accum * accelerator.num_processes - rank0_print(f"Effective batch size: {effective_bs} (micro={args.batch_size} × " - f"accum={args.grad_accum} × ranks={accelerator.num_processes})") - accelerator.init_trackers( - project_name="pos2move_v2", - config={ - "batch_size": args.batch_size, - "grad_accum": args.grad_accum, - "effective_batch_size": effective_bs, - "max_steps": args.max_steps, - "lr": args.lr, - "weight_decay": args.weight_decay, - "value_loss_weight": args.value_loss_weight, - **model_config, - }, - ) - - device = accelerator.device - rank0_print(f"Device: {device} | Precision: {precision} | Logging to: {log_path}") - - model = Pos2MoveV2(**model_config) - total_params = sum(p.numel() for p in model.parameters()) - rank0_print(f"Model parameters: {total_params:,}") - model.to(device) - - # torch.compile vs accelerator.prepare() ordering is not cosmetic under DDP. - # - # Dynamo's DDPOptimizer (torch._dynamo.backends.distributed, on by default) splits the - # graph at DDP's gradient all-reduce bucket boundaries so the collectives can overlap - # with backward compute. Its own docs: "DDPOptimizer applies when dynamo compiles - # models wrapped in DistributedDataParallel". Compiling first gives DDP(OptimizedModule) - # -- the wrap happens outside the compiled graph, DDPOptimizer never sees a DDP module, - # and the overlap is lost. Compiling after prepare() gives compile(DDP(model)), which is - # the shape it wants. - # - # Single process has no buckets to align to, so 'before' is kept there: it is the - # ordering the measured 2.2x speedup and the compile-time numbers come from. - compile_order = args.compile_order - if compile_order == "auto": - compile_order = "after-prepare" if accelerator.num_processes > 1 else "before-prepare" - - def maybe_compile(m, when): - if args.compile and compile_order == when: - rank0_print(f"torch.compile (mode={args.compile_mode}, {when})") - return torch.compile(m, mode=args.compile_mode, dynamic=False) # shapes are static - return m - - model = maybe_compile(model, "before-prepare") - - # ── Optimizer (Muon for 2D weights, AdamW for embeddings/heads/1D) ── - lr_emb = args.lr_embedding or args.lr - lr_head = args.lr_head or args.lr - - muon_params = [] - adamw_emb_params = [] - adamw_head_params = [] - adamw_other_params = [] - - for name, param in model.named_parameters(): - if "embedding" in name: - adamw_emb_params.append(param) - elif "move_head" in name or "value_head" in name: - adamw_head_params.append(param) - elif param.ndim == 2: - muon_params.append(param) - else: - adamw_other_params.append(param) - - rank0_print(f"LR: emb={lr_emb:.2e} | muon={args.lr_muon:.2e} | head={lr_head:.2e}") - rank0_print( - f"Params: emb={sum(p.numel() for p in adamw_emb_params):,} | " - f"muon={sum(p.numel() for p in muon_params):,} | " - f"adamw_other={sum(p.numel() for p in adamw_other_params):,} | " - f"head={sum(p.numel() for p in adamw_head_params):,}" - ) - - # DistributedMuon degenerates to exactly torch.optim.Muon at world size 1 (verified in - # tests/test_distributed_muon.py), so there is one code path rather than two. - muon_cls = DistributedMuon if args.distributed_muon else torch.optim.Muon - muon_optimizer = muon_cls( - muon_params, - lr=args.lr_muon, - momentum=0.95, - weight_decay=args.weight_decay, - ) - if args.distributed_muon and accelerator.num_processes > 1: - rank0_print(muon_optimizer.sharding_summary().split(" | ")[0]) - adamw_optimizer = torch.optim.AdamW([ - {"params": adamw_emb_params, "lr": lr_emb, "weight_decay": args.weight_decay}, - {"params": adamw_other_params, "lr": args.lr, "weight_decay": 0.0}, - {"params": adamw_head_params, "lr": lr_head, "weight_decay": 0.0}, - ]) - - if use_shards: - # The shard loaders are deliberately kept out of prepare(). They run with - # batch_size=None and a BatchSampler so that a whole index list reaches - # __getitem__ in one call; Accelerate reads batch_size=None as "this iterable - # already yields batches" and would re-shard at the wrong granularity. Rank - # splitting is done by the DistributedSampler inside make_shard_dataloader, and - # the H2D copy by unpack_batch. - model, muon_optimizer, adamw_optimizer = accelerator.prepare( - model, muon_optimizer, adamw_optimizer - ) - else: - model, muon_optimizer, adamw_optimizer, train_loader, val_loader, test_loader = accelerator.prepare( - model, muon_optimizer, adamw_optimizer, train_loader, val_loader, test_loader - ) - - model = maybe_compile(model, "after-prepare") - - # ── EMA ────────────────────────────────────────────────────────────── - use_ema = args.ema_decay > 0 - ema_state = None - if use_ema: - ema_state = create_ema_state(get_raw_model(model, accelerator)) - rank0_print(f"EMA enabled (decay={args.ema_decay})") - - # ── Resume ─────────────────────────────────────────────────────────── - best_val_loss = float("inf") - start_pass = 0 - global_step = 0 - trainer_state = None - - if args.resume_from: - trainer_state = load_trainer_state(args.resume_from) - if trainer_state: - # "epoch" is the pre-step-paradigm key; read it so old checkpoints still resume. - start_pass = trainer_state.get("data_pass", trainer_state.get("epoch", 0)) + 1 - global_step = trainer_state["global_step"] - best_val_loss = trainer_state["best_val_loss"] - - # ── Scheduler ──────────────────────────────────────────────────────── - total_steps = args.max_steps - scheduler_config = { - "warmup_steps": args.warmup_steps, - "total_steps": total_steps, - "final_lr_ratio": args.final_lr_ratio, - "schedule": args.lr_schedule, - "warmdown_ratio": args.warmdown_ratio, - } - if trainer_state and "scheduler_config" in trainer_state: - # A resume keeps the schedule it started with, so the LR curve stays continuous. - # That means --max-steps still bounds the *loop* but no longer sets the LR horizon, - # and the two can silently disagree. Say so rather than let it be discovered later. - scheduler_config = trainer_state["scheduler_config"] - resumed_total = scheduler_config.get("total_steps") - if resumed_total != args.max_steps: - rank0_print(f"WARNING: resuming with the checkpoint's LR schedule " - f"(total_steps={resumed_total:,}) while --max-steps={args.max_steps:,} " - f"bounds the loop. The LR decays over {resumed_total:,} steps regardless.") - total_steps = resumed_total - - # An "epoch" is not comparable between the two data paths: the HDF5 dataset is indexed - # by *game* (738 optimizer steps/epoch) and the shard dataset by *sample* (11.5k for - # elite_k16, 50.5k for full_k4). So --epochs N silently buys a 15-68x longer LR decay - # on shards, and epoch-end validation fires that much less often. Print both so the - # schedule is never a surprise, and say so out loud when --max-steps is not pinning it. - steps_per_pass = len(train_loader) // max(1, args.grad_accum) - samples_seen = args.max_steps * effective_bs - warmdown_note = (f"warmdown {round(args.warmdown_ratio * total_steps):,} | " - if args.lr_schedule == "wsd" else "") - rank0_print(f"Schedule: {total_steps:,} optimizer steps | {args.lr_schedule} | " - f"warmup {args.warmup_steps:,} | {warmdown_note}" - f"eval every {args.eval_steps:,} | save every {args.save_steps:,}") - rank0_print(f" one pass over the training data = {steps_per_pass:,} steps/rank " - f"({args.max_steps / max(1, steps_per_pass):.2f} passes, " - f"{samples_seen:,} samples consumed)") - - muon_scheduler = create_lr_scheduler(muon_optimizer, **scheduler_config) - adamw_scheduler = create_lr_scheduler(adamw_optimizer, **scheduler_config) - accelerator.register_for_checkpointing(muon_scheduler, adamw_scheduler) - - if args.resume_from: - accelerator.load_state(args.resume_from) - if use_ema: - ema_path = Path(args.resume_from) / "ema_state.pt" - if ema_path.exists(): - ema_state = load_ema_state(ema_path, device) - rank0_print(f"Restored EMA state from {ema_path}") - else: - ema_state = create_ema_state(get_raw_model(model, accelerator)) - rank0_print("EMA state not found in checkpoint, re-initialized from model") - rank0_print(f"Resumed from {args.resume_from} (step {global_step:,}/{args.max_steps:,}, " - f"data pass {start_pass})") - - # ── Validation ─────────────────────────────────────────────────────── - # Runs on the --eval-steps counter. It used to run only at epoch end, which was a fine - # cadence on the HDF5 path (738 steps/epoch) and a bad one on shards (11,495 steps for - # elite_k16, 50,505 for full_k4) — the dataset index is a sample there, not a game. Val - # loss selects the best checkpoint, so that gap mattered. Hence the step paradigm. - - def run_validation(): - """Evaluate on val_loader (under EMA weights if enabled). Restores train mode.""" - model.eval() - unwrapped = get_raw_model(model, accelerator) - if use_ema: - swap_ema_weights(unwrapped, ema_state) - - # No cross-rank reduction here on purpose: val_loader is replicated, not sharded, - # so every rank walks the identical set and arrives at the identical number. That - # is what keeps best-model selection consistent across ranks without a gather. - sums = dict(loss=0.0, ce=0.0, legal_ce=0.0, value=0.0, correct=0, legal_correct=0, total=0) - with torch.no_grad(): - for batch in tqdm(val_loader, desc="Validation", leave=False, - disable=not accelerator.is_main_process): - b = unpack_batch(batch, device) - move_logits, value = model(b["board"], b["player"], b["castling"], b["en_passant"]) - loss, metrics = compute_loss( - move_logits, value, - b["from_sq"], b["action_plane"], - b["legal_planes"], b["result"], b["is_white"], b["move_number"], - args.value_loss_weight, - ) - B = move_logits.size(0) - sums["loss"] += loss.item() * B - sums["ce"] += metrics["ce"].item() * B - sums["legal_ce"] += metrics["legal_ce"].item() * B - sums["value"] += metrics["value_loss"].item() * B - sums["correct"] += int(metrics["acc"].item() * B) - sums["legal_correct"] += int(metrics["legal_acc"].item() * B) - sums["total"] += B - - if use_ema: - swap_ema_weights(unwrapped, ema_state) - model.train() - - n = max(1, sums["total"]) - return { - "val/loss": sums["loss"] / n, - "val/ce": sums["ce"] / n, - "val/legal_ce": sums["legal_ce"] / n, - "val/value_loss": sums["value"] / n, - "val/accuracy": sums["correct"] / n, - "val/legal_accuracy": sums["legal_correct"] / n, - } - - def record_validation(vals, data_pass, extra_log=None, label=""): - """Log, print, and update best-model selection. Returns True if it was a new best.""" - nonlocal best_val_loss - log_dict = dict(extra_log or {}) - log_dict.update(vals) - if use_ema: - log_dict["val/ema_loss"] = vals["val/loss"] - log_dict["val/ema_accuracy"] = vals["val/accuracy"] - accelerator.log(log_dict, step=global_step) - - ema_tag = " (EMA)" if use_ema else "" - rank0_print(f"{label}val_loss={vals['val/loss']:.4f}{ema_tag} " - f"| val_acc={vals['val/accuracy']:.4f} " - f"| val_legal_acc={vals['val/legal_accuracy']:.4f}") - - if vals["val/loss"] < best_val_loss: - best_val_loss = vals["val/loss"] - best_path = checkpoint_dir / "best_model" - accelerator.save_state(str(best_path)) - save_trainer_state(best_path, data_pass, global_step, best_val_loss, scheduler_config) - if use_ema and accelerator.is_main_process: - save_ema_state(ema_state, best_path / "ema_state.pt") - rank0_print(f" -> New best model (val_loss={vals['val/loss']:.4f})") - return True - return False - - # ── Training loop (step-driven) ────────────────────────────────────── - # The loop is bounded by optimizer steps and cycles the dataloader as many times as - # that takes. Nothing downstream keys off "epoch" any more: LR decay, validation and - # checkpointing are all on step counters, which mean the same thing whichever dataset - # is mounted and at any world size. - - def start_pass_shuffle(loader, n): - """Reshuffle for a fresh pass over the data. - - DistributedSampler needs set_epoch or every rank replays the identical order on - every pass. RandomSampler carries its generator across iterators and reshuffles on - its own, so this is a no-op there. - """ - for obj in (loader, - getattr(loader, "sampler", None), - getattr(getattr(loader, "sampler", None), "sampler", None)): - if obj is not None and hasattr(obj, "set_epoch"): - obj.set_epoch(n) - return - - def new_window(): - """Train metrics accumulated since the last validation, sample-weighted.""" - return dict(loss=0.0, ce=0.0, legal_ce=0.0, value=0.0, acc=0.0, legal_acc=0.0, n=0) - - WINDOW_KEYS = ("loss", "ce", "legal_ce", "value", "acc", "legal_acc") - - def flush_window(w): - """Average the window across ranks, not just within one. - - Each rank trains on a different slice, so these sums are rank-local: rank 0's - numbers alone are a 1/N sample of the step. Reducing sum-of-(metric x batch) and - sum-of-batch separately, then dividing, is exact regardless of how unevenly the - last batches fall -- which is why this does not need gather_for_metrics and its - padding-trim bookkeeping (that machinery also would not work here, since the shard - loaders never went through prepare()). - """ - vals = torch.tensor([w[k] for k in WINDOW_KEYS] + [float(w["n"])], - dtype=torch.float64, device=accelerator.device) - if accelerator.num_processes > 1: - vals = accelerator.reduce(vals, reduction="sum") - total = max(1.0, vals[-1].item()) - return {f"train/{'value_loss' if k == 'value' else k}": vals[i].item() / total - for i, k in enumerate(WINDOW_KEYS)} - - last_val_step = -1 - - def validate_now(window, data_pass, label_prefix): - """Flush the train window, validate, log both against the same step. - - No-ops if this step has already been validated, which happens whenever max_steps is - an exact multiple of eval_steps and the final validation lands on the same step as - the last periodic one. Worth guarding rather than tolerating: on the HDF5 path the - two calls do not even agree, because ``HDF5ChessDataset.__getitem__`` samples a - fresh ply per call, so its val set re-rolls on every pass. (The shard val set is - fixed, so shard val loss is comparable across evaluations and HDF5 val loss is not - — worth remembering when reading either curve.) - """ - nonlocal last_val_step - if global_step == last_val_step: - return - last_val_step = global_step - extra = flush_window(window) if window["n"] else {} - extra["data_pass"] = data_pass - train_tag = f"train_loss={extra['train/loss']:.4f} | " if window["n"] else "" - record_validation(run_validation(), data_pass, extra_log=extra, - label=f"{label_prefix}{train_tag}") - - model.train() - window = new_window() - data_pass = start_pass - pbar = tqdm(total=args.max_steps, initial=global_step, desc="train", unit="step", - disable=not accelerator.is_main_process) - - while global_step < args.max_steps: - start_pass_shuffle(train_loader, data_pass) - for batch in train_loader: - with accelerator.accumulate(model): - b = unpack_batch(batch, device) - board, player = b["board"], b["player"] - castling, en_passant = b["castling"], b["en_passant"] - from_sq, action_plane = b["from_sq"], b["action_plane"] - legal_planes, result = b["legal_planes"], b["result"] - is_white, move_number = b["is_white"], b["move_number"] - - move_logits, value = model(board, player, castling, en_passant) - loss, metrics = compute_loss( - move_logits, value, - from_sq, action_plane, - legal_planes, result, is_white, move_number, - args.value_loss_weight, - label_smoothing=args.label_smoothing, - ) - - accelerator.backward(loss) - if accelerator.sync_gradients and args.max_grad_norm > 0: - accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm) - if args.muon_schedules: - # Momentum is not a constant in a well-tuned Muon run: a long memory - # early averages over a fast-moving gradient, and a slightly shorter one - # late helps the run settle. Weight decay cosine-decays to zero. - mom = muon_momentum(global_step, args.max_steps, - warmdown_ratio=args.warmdown_ratio) - wdk = muon_weight_decay(global_step, args.max_steps, args.weight_decay) - for g in muon_optimizer.param_groups: - g["momentum"], g["weight_decay"] = mom, wdk - muon_optimizer.step() - adamw_optimizer.step() - if accelerator.sync_gradients: - muon_scheduler.step() - adamw_scheduler.step() - muon_optimizer.zero_grad() - adamw_optimizer.zero_grad() - - # EMA is redundant under DDP but not wrong, and that is worth stating. - # Gradients are all-reduced before the step, so every rank holds identical - # params and computes an identical EMA from an identical decay -- no drift. - # swap_ema_weights in run_validation is likewise symmetric because every - # rank validates (val_loader is replicated, not sharded). The failure mode - # to avoid is any rank taking a different branch here; sync_gradients is - # world-uniform, so none does. tests/test_distributed.py asserts it. - if use_ema and accelerator.sync_gradients: - update_ema(get_raw_model(model, accelerator), ema_state, args.ema_decay) - - bs = board.size(0) - window["loss"] += loss.item() * bs - window["ce"] += metrics["ce"].item() * bs - window["legal_ce"] += metrics["legal_ce"].item() * bs - window["value"] += metrics["value_loss"].item() * bs - window["acc"] += metrics["acc"].item() * bs - window["legal_acc"] += metrics["legal_acc"].item() * bs - window["n"] += bs - - pbar.set_postfix( - loss=f"{loss.item():.4f}", - ce=f"{metrics['ce'].item():.4f}", - acc=f"{metrics['acc'].item():.3f}", - val_l=f"{metrics['value_loss'].item():.4f}", - ) - - if not accelerator.sync_gradients: - continue - - muon_lrs = muon_scheduler.get_last_lr() - adamw_lrs = adamw_scheduler.get_last_lr() - accelerator.log( - { - "train/step_loss": loss.item(), - "train/step_ce": metrics["ce"].item(), - "train/step_legal_ce": metrics["legal_ce"].item(), - "train/step_value_loss": metrics["value_loss"].item(), - "train/step_acc": metrics["acc"].item(), - "train/step_legal_acc": metrics["legal_acc"].item(), - "train/lr_muon": muon_lrs[0], - "train/lr_emb": adamw_lrs[0], - "train/lr_head": adamw_lrs[2], - **({"train/muon_momentum": muon_optimizer.param_groups[0]["momentum"], - "train/muon_wd": muon_optimizer.param_groups[0]["weight_decay"]} - if args.muon_schedules else {}), - }, - step=global_step, - ) - - global_step += 1 - pbar.update(1) - - if args.save_steps > 0 and global_step % args.save_steps == 0: - ckpt = checkpoint_dir / f"checkpoint_step_{global_step:07d}" - accelerator.save_state(str(ckpt)) - save_trainer_state(ckpt, data_pass, global_step, best_val_loss, scheduler_config) - if use_ema and accelerator.is_main_process: - save_ema_state(ema_state, ckpt / "ema_state.pt") - if accelerator.is_main_process: - rank0_print(f"\n Saved step checkpoint at step {global_step}") - cleanup_old_checkpoints(checkpoint_dir, args.max_checkpoints) - - # Validation is on a step counter, and global_step is identical on every rank, - # so all ranks enter the collective forward together. - if args.eval_steps > 0 and global_step % args.eval_steps == 0: - validate_now(window, data_pass, - f"\nStep {global_step:,}/{args.max_steps:,}: ") - window = new_window() - - if global_step >= args.max_steps: - break - - data_pass += 1 - - pbar.close() - - # Always finish on a validation, so the final steps can still win best_model even when - # max_steps is not a multiple of eval_steps. - rank0_print(f"\nReached max-steps ({args.max_steps:,}) after {data_pass} pass(es) over the data.") - validate_now(window, data_pass, f"Final (step {global_step:,}): ") - - # ── Final test (using EMA weights) ─────────────────────────────────── - rank0_print("\nFinal test evaluation...") - model.eval() - if use_ema: - swap_ema_weights(get_raw_model(model, accelerator), ema_state) - test_loss_sum = 0.0 - test_correct = 0 - test_legal_correct = 0 - test_total = 0 - - with torch.no_grad(): - for batch in tqdm(test_loader, desc="Testing", leave=False, - disable=not accelerator.is_main_process): - b = unpack_batch(batch, device) - board, player = b["board"], b["player"] - castling, en_passant = b["castling"], b["en_passant"] - from_sq, action_plane = b["from_sq"], b["action_plane"] - legal_planes, result = b["legal_planes"], b["result"] - is_white, move_number = b["is_white"], b["move_number"] - - move_logits, value = model(board, player, castling, en_passant) - loss, metrics = compute_loss( - move_logits, value, - from_sq, action_plane, - legal_planes, result, is_white, move_number, - args.value_loss_weight, - ) - - B = move_logits.size(0) - test_loss_sum += loss.item() * B - test_correct += int(metrics["acc"].item() * B) - test_legal_correct += int(metrics["legal_acc"].item() * B) - test_total += B - - test_loss = test_loss_sum / test_total - test_acc = test_correct / test_total - test_legal_acc = test_legal_correct / test_total - - accelerator.log( - {"test/loss": test_loss, "test/accuracy": test_acc, "test/legal_accuracy": test_legal_acc}, - step=global_step, - ) - rank0_print(f"Test: loss={test_loss:.4f} | accuracy={test_acc:.4f} | legal_accuracy={test_legal_acc:.4f}") - - accelerator.end_training() - rank0_print(f"\nTraining complete. Logs: {log_path}") - - -if __name__ == "__main__": - main() diff --git a/chesstransformer/trainers/position2move_trainer.py b/chesstransformer/trainers/position2move_trainer.py deleted file mode 100644 index 8ef3c193a16362f981a5c5bb8584f86f3e1f91c0..0000000000000000000000000000000000000000 --- a/chesstransformer/trainers/position2move_trainer.py +++ /dev/null @@ -1,682 +0,0 @@ -#!/usr/bin/env python3 -""" -Training script for Position2Move transformer model. - -This script trains a transformer to predict chess moves from board positions. -Uses the new efficient HDF5 dataset format with game-based storage and random sampling. - -Usage: - python src/chesstransformer/trainers/position2move_trainer.py --data data/Lichess2017.h5 - -Options: - --data: Path to HDF5 dataset - --min-elo: Minimum average ELO for filtering games - --max-elo: Maximum average ELO for filtering games - --batch-size: Batch size (default: 32) - --epochs: Number of epochs (default: 10) - --lr: Learning rate (default: 3e-4) - --save-every: Save checkpoint every N epochs (default: 5) -""" - -from pathlib import Path -from datetime import datetime -import argparse -import copy -import random -import numpy as np -import json - -from tqdm.auto import tqdm -import torch -from torch.nn import functional as F -from torch.utils.data import DataLoader, random_split -import accelerate -from accelerate.utils import set_seed -from torch.optim.lr_scheduler import LambdaLR - -from chesstransformer.datasets.h5_lichess_dataset import HDF5ChessDataset -from chesstransformer.models.transformer.position2move import Position2MoveModel - - -def get_next_run_number(log_dir="logs"): - """Get the next run number by checking existing run directories.""" - log_path = Path(log_dir) - if not log_path.exists(): - return 1 - - existing_runs = [d.name for d in log_path.iterdir() if d.is_dir() and d.name.startswith("run_")] - - if not existing_runs: - return 1 - - run_numbers = [] - for run_name in existing_runs: - try: - num = int(run_name.split("_")[1]) - run_numbers.append(num) - except (IndexError, ValueError): - continue - - return max(run_numbers) + 1 if run_numbers else 1 - - -def compute_loss(logits, moves, legal_moves_mask, beta, legal_move_loss_weight): - llm_loss = F.cross_entropy(logits, moves) - illegal_prob = F.softmax(logits, dim=-1) * (1.0 - legal_moves_mask.float()) - legal_move_loss = torch.sum(illegal_prob**2, dim=-1).mean() - filtered_logits = torch.where(legal_moves_mask.bool(), logits, -torch.inf) - legal_move_cross_entropy = F.cross_entropy(filtered_logits, moves) - loss = beta * llm_loss + legal_move_loss_weight * legal_move_loss + (1 - beta) * legal_move_cross_entropy - return loss, llm_loss, legal_move_loss, legal_move_cross_entropy - - -def save_trainer_state(checkpoint_dir, epoch, global_step, best_val_loss, scheduler_config=None): - state = { - "epoch": epoch, - "global_step": global_step, - "best_val_loss": best_val_loss, - } - if scheduler_config: - state["scheduler_config"] = scheduler_config - state_path = Path(checkpoint_dir) / "trainer_state.json" - with state_path.open("w", encoding="utf-8") as fp: - json.dump(state, fp) - - -def load_trainer_state(checkpoint_dir): - state_path = Path(checkpoint_dir) / "trainer_state.json" - if not state_path.exists(): - return None - with state_path.open("r", encoding="utf-8") as fp: - return json.load(fp) - - -def cleanup_old_step_checkpoints(checkpoint_dir, max_checkpoints): - """Remove old step checkpoints, keeping only the most recent ones.""" - checkpoint_path = Path(checkpoint_dir) - step_checkpoints = sorted( - [d for d in checkpoint_path.iterdir() if d.is_dir() and d.name.startswith("checkpoint_step_")], - key=lambda x: int(x.name.split("_")[-1]), - ) - - # Remove oldest checkpoints if we exceed max_checkpoints - while len(step_checkpoints) > max_checkpoints: - oldest = step_checkpoints.pop(0) - import shutil - - shutil.rmtree(oldest) - print(f" Removed old checkpoint: {oldest.name}") - - -def create_linear_warmup_decay_scheduler(optimizer, warmup_steps, total_steps, final_lr_ratio): - final_lr_ratio = max(0.0, final_lr_ratio) - warmup_steps = max(1, warmup_steps) - total_steps = max(warmup_steps + 1, total_steps) - - def lr_lambda(current_step): - if current_step < warmup_steps: - return float(current_step + 1) / float(warmup_steps) - progress = (current_step - warmup_steps + 1) / float(max(1, total_steps - warmup_steps)) - return 1.0 - (1.0 - final_lr_ratio) * min(1.0, progress) - - return LambdaLR(optimizer, lr_lambda) - - -def find_best_learning_rate( - model, train_loader, accelerator, lr_min=1e-6, lr_max=1e-2, num_steps=100, beta=0.7, legal_move_loss_weight=10.0 -): - model.train() - device = accelerator.device - initial_state = copy.deepcopy(model.state_dict()) - # Use base learning rate for LR finder - optimizer = torch.optim.AdamW(model.parameters(), lr=lr_min) - multiplier = (lr_max / lr_min) ** (1 / max(num_steps - 1, 1)) - best_lr = lr_min - best_loss = float("inf") - lr = lr_min - data_iter = iter(train_loader) - - for step in range(num_steps): - try: - batch = next(data_iter) - except StopIteration: - data_iter = iter(train_loader) - batch = next(data_iter) - - optimizer.zero_grad() - positions = batch["position"].to(device) - moves = batch["move"].to(device) - is_white = batch["is_white"].to(device) - legal_moves_mask = batch["legal_moves_mask"].to(device) - castling_rights = batch["castling_rights"].to(device) - en_passant_file = batch["en_passant_file"].to(device) - halfmove_clock = batch["halfmove_clock"].to(device) - - logits = model(positions, is_white, castling_rights, en_passant_file, halfmove_clock) - loss, llm_loss, legal_move_loss, legal_move_cross_entropy = compute_loss( - logits, moves, legal_moves_mask, beta, legal_move_loss_weight - ) - - accelerator.backward(loss) - optimizer.step() - - loss_value = accelerator.gather_for_metrics(loss.detach()).mean().item() - if loss_value < best_loss: - best_loss = loss_value - best_lr = lr - - lr *= multiplier - for param_group in optimizer.param_groups: - param_group["lr"] = lr - - model.load_state_dict(initial_state) - model.zero_grad(set_to_none=True) - accelerator.free_memory() - return best_lr, best_loss - - -def main(): - default_data_path = Path(__file__).parents[2] / "data" / "Lichess2017.h5" - - parser = argparse.ArgumentParser(description="Train Position2Move Transformer") - parser.add_argument("--data", type=str, default=default_data_path, help="Path to HDF5 dataset") - parser.add_argument("--min-elo", type=int, default=None, help="Minimum average ELO for filtering games") - parser.add_argument("--max-elo", type=int, default=None, help="Maximum average ELO for filtering games") - parser.add_argument("--batch-size", type=int, default=32, help="Batch size") - parser.add_argument("--epochs", type=int, default=10, help="Number of epochs") - parser.add_argument("--lr", type=float, default=3e-4, help="Learning rate for transformers (base LR)") - parser.add_argument( - "--lr-embedding", type=float, default=None, help="Learning rate for embeddings (default: same as --lr)" - ) - parser.add_argument( - "--lr-head", type=float, default=None, help="Learning rate for output head (default: same as --lr)" - ) - parser.add_argument("--save-every", type=int, default=5, help="Save checkpoint every N epochs") - parser.add_argument("--lr-find", action="store_true", help="Run learning rate finder before training") - parser.add_argument("--lr-min", type=float, default=1e-6, help="Minimum LR for finder sweep") - parser.add_argument("--lr-max", type=float, default=1e-2, help="Maximum LR for finder sweep") - parser.add_argument("--lr-steps", type=int, default=100, help="Number of steps for LR finder sweep") - parser.add_argument("--beta", type=float, default=0.7, help="Weight for LLM loss in combined loss function") - parser.add_argument( - "--legal-move-loss-weight", - type=float, - default=10.0, - help="Weight for legal move loss in combined loss function", - ) - parser.add_argument("--random-seed", type=int, default=42, help="Random seed for reproducibility") - parser.add_argument("--warmup-steps", type=int, default=1000, help="Number of warmup steps for LR scheduler") - parser.add_argument("--final-lr-ratio", type=float, default=0.01, help="Final LR multiplier after linear decay") - parser.add_argument("--resume-from", type=str, default=None, help="Path to checkpoint directory to resume from") - parser.add_argument( - "--max-grad-norm", type=float, default=1.0, help="Maximum gradient norm for clipping (0 to disable)" - ) - parser.add_argument( - "--max_examples", type=int, default=None, help="Maximum number of examples to use from the dataset" - ) - parser.add_argument("--save-steps", type=int, default=5000, help="Save checkpoint every N steps") - parser.add_argument( - "--max-checkpoints", - type=int, - default=5, - help="Maximum number of step checkpoints to keep (excluding best model)", - ) - parser.add_argument( - "--precision", type=str, default="fp16", choices=["bf16", "fp16", "fp32"], help="Precision for training" - ) - args = parser.parse_args() - - set_seed(args.random_seed) - random.seed(args.random_seed) - np.random.seed(args.random_seed) - torch.manual_seed(args.random_seed) - torch.cuda.manual_seed_all(args.random_seed) - - # Setup dataset and dataloaders - dataset = HDF5ChessDataset( - hdf5_path=args.data, - min_elo=args.min_elo, - max_elo=args.max_elo, - ) - - MAX_VALIDATION_SAMPLES = 10000 - - val_size = min(int(0.1 * len(dataset)), MAX_VALIDATION_SAMPLES) - test_size = min(int(0.1 * len(dataset)), MAX_VALIDATION_SAMPLES) - train_size = len(dataset) - val_size - test_size - train_set, val_set, test_set = random_split(dataset, [train_size, val_size, test_size]) - - train_loader = DataLoader(train_set, batch_size=args.batch_size, shuffle=True, num_workers=12, drop_last=True) - val_loader = DataLoader(val_set, batch_size=args.batch_size, shuffle=False, num_workers=12) - test_loader = DataLoader(test_set, batch_size=args.batch_size, shuffle=False, num_workers=12) - - print(f"Train samples: {len(train_set)}, Val samples: {len(val_set)}, Test samples: {len(test_set)}") - - # Model configuration - model_config = { - "vocab_size": dataset.position_tokenizer.vocab_size, - "move_vocab_size": dataset.move_tokenizer.vocab_size, - "embed_dim": 512, - "nb_transformer_layers": 8, - "num_heads": 8, - "num_kv_groups": 4, # GQA: 8 heads / 4 groups = 2 heads per KV group - "dropout": 0.1, - "kvq_bias": False, - "mask_future": False, - "rope": True, # Use RoPE for positional encoding - "use_swiglu": True, # Use SwiGLU activation (Llama-style) - "use_col_row_emb": True, # Use separate column and row embeddings - } - - # Setup logging - log_dir = Path("logs") / "position2move" - log_dir.mkdir(parents=True, exist_ok=True) - run_number = get_next_run_number(str(log_dir)) - log_dir_full = f"run_{run_number:03d}_{datetime.now().strftime('%Y%m%d_%H%M%S')}" - log_path = log_dir / log_dir_full - log_path.mkdir(parents=True, exist_ok=False) - print(f"Logging to: {log_path}") - - # Create checkpoints directory - checkpoint_dir = log_path / "checkpoints" - checkpoint_dir.mkdir(exist_ok=True) - - # Save model config to JSON - config_path = log_path / "model_config.json" - with config_path.open("w", encoding="utf-8") as f: - json.dump(model_config, f, indent=2) - print(f"Model config saved to: {config_path}") - - precision = args.precision if torch.cuda.is_available() or torch.backends.mps.is_available() else "fp32" - print(f"Using precision: {precision}") - - accelerator = accelerate.Accelerator(log_with="tensorboard", project_dir=str(log_path), mixed_precision=precision) - - # Initialize trackers - accelerator.init_trackers( - project_name="position2move", - config={ - "batch_size": args.batch_size, - "epochs": args.epochs, - "learning_rate": args.lr, - "lr_embedding": args.lr_embedding if args.lr_embedding is not None else args.lr, - "lr_head": args.lr_head if args.lr_head is not None else args.lr, - "min_elo": args.min_elo, - "max_elo": args.max_elo, - "max_grad_norm": args.max_grad_norm, - **model_config, - "warmup_steps": args.warmup_steps, - "final_lr_ratio": args.final_lr_ratio, - "precision": args.precision, - }, - ) - - device = accelerator.device - print(f"Using device: {device}") - - model = Position2MoveModel(**model_config) - - # torch.compile has limited support on MPS backend - disable if compilation fails - if device.type == "mps": - print("Warning: Skipping torch.compile on MPS device (Mac GPU) due to backend limitations") - print("Training will proceed without compilation optimizations") - else: - try: - model = torch.compile( - model, - ) - print("Model compiled successfully") - except Exception as e: - print(f"Warning: torch.compile failed ({e}), proceeding without compilation") - - model.to(device) - - if args.lr_find: - if accelerator.is_main_process: - print("Running learning rate finder...") - best_lr, best_loss = find_best_learning_rate( - model, - train_loader, - accelerator, - lr_min=args.lr_min, - lr_max=args.lr_max, - num_steps=args.lr_steps, - beta=args.beta, - legal_move_loss_weight=args.legal_move_loss_weight, - ) - accelerator.log({"lr_finder/best_lr": best_lr, "lr_finder/best_loss": best_loss}, step=0) - args.lr = best_lr - if accelerator.is_main_process: - print(f"Best LR found: {best_lr:.6g} (loss {best_loss:.4f})") - - # Set up discriminative learning rates - lr_embedding = args.lr_embedding if args.lr_embedding is not None else args.lr - lr_head = args.lr_head if args.lr_head is not None else args.lr - lr_transformer = args.lr - - # Create parameter groups - embedding_params = [] - transformer_params = [] - head_params = [] - - # Get underlying model (unwrap from accelerator if needed) - unwrapped_model = accelerator.unwrap_model(model) - - # Categorize parameters - for name, param in unwrapped_model.named_parameters(): - if "embedding" in name: - embedding_params.append(param) - elif "lm_head" in name: - head_params.append(param) - else: - transformer_params.append(param) - - param_groups = [ - {"params": embedding_params, "lr": lr_embedding, "name": "embeddings"}, - {"params": transformer_params, "lr": lr_transformer, "name": "transformers"}, - {"params": head_params, "lr": lr_head, "name": "head"}, - ] - - if accelerator.is_main_process: - emb_count = sum(p.numel() for p in embedding_params) - trans_count = sum(p.numel() for p in transformer_params) - head_count = sum(p.numel() for p in head_params) - print(f"\nLearning rates:") - print(f" Embeddings: {lr_embedding:.6g}") - print(f" Transformers: {lr_transformer:.6g}") - print(f" Head: {lr_head:.6g}") - print(f" Param counts: Emb={emb_count:,}, Trans={trans_count:,}, Head={head_count:,}\n") - - optimizer = torch.optim.AdamW(param_groups, lr=args.lr) - model, optimizer, train_loader, val_loader, test_loader = accelerator.prepare( - model, optimizer, train_loader, val_loader, test_loader - ) - - # Check if resuming to load scheduler config from checkpoint - best_val_loss = float("inf") - start_epoch = 1 - global_step = 0 - resume_path = Path(args.resume_from) if args.resume_from else None - trainer_state = None - - if resume_path: - trainer_state = load_trainer_state(resume_path) - if trainer_state: - start_epoch = trainer_state.get("epoch", 0) + 1 - global_step = trainer_state.get("global_step", 0) - best_val_loss = trainer_state.get("best_val_loss", float("inf")) - - # Determine scheduler parameters - use saved config when resuming for consistency - has_scheduler_config = trainer_state and "scheduler_config" in trainer_state - - if has_scheduler_config: - saved_config = trainer_state["scheduler_config"] - scheduler_warmup_steps = saved_config["warmup_steps"] - scheduler_total_steps = saved_config["total_steps"] - scheduler_final_lr_ratio = saved_config["final_lr_ratio"] - if accelerator.is_main_process: - print( - f"Using scheduler config from checkpoint: warmup={scheduler_warmup_steps}, total={scheduler_total_steps}, final_lr_ratio={scheduler_final_lr_ratio}" - ) - else: - scheduler_warmup_steps = args.warmup_steps - scheduler_total_steps = max(1, len(train_loader)) * max(1, args.epochs) - scheduler_final_lr_ratio = args.final_lr_ratio - if resume_path and accelerator.is_main_process: - print( - f"Old checkpoint without scheduler_config - using new scheduler params: warmup={scheduler_warmup_steps}, total={scheduler_total_steps}" - ) - - # Store scheduler config for saving in checkpoints - scheduler_config = { - "warmup_steps": scheduler_warmup_steps, - "total_steps": scheduler_total_steps, - "final_lr_ratio": scheduler_final_lr_ratio, - } - - scheduler = create_linear_warmup_decay_scheduler( - optimizer, - warmup_steps=scheduler_warmup_steps, - total_steps=scheduler_total_steps, - final_lr_ratio=scheduler_final_lr_ratio, - ) - - # Always register scheduler for checkpointing (required for load_state to work) - accelerator.register_for_checkpointing(scheduler) - - # Load the full accelerator state (model, optimizer, scheduler) if resuming - if resume_path: - accelerator.load_state(str(resume_path)) - - # For old checkpoints without scheduler_config, the loaded scheduler state - # has a mismatched lr_lambda (old total_steps). We need to recreate it. - if not has_scheduler_config: - # Recreate scheduler with correct parameters - scheduler = create_linear_warmup_decay_scheduler( - optimizer, - warmup_steps=scheduler_warmup_steps, - total_steps=scheduler_total_steps, - final_lr_ratio=scheduler_final_lr_ratio, - ) - # Manually advance to the correct step - scheduler.last_epoch = global_step - 1 # -1 because step() will increment it - scheduler.step() # This sets it to global_step and computes correct LR - if accelerator.is_main_process: - current_lrs = scheduler.get_last_lr() - print(f" Recreated scheduler and advanced to step {global_step}") - print(f" Current LRs: emb={current_lrs[0]:.6g}, trans={current_lrs[1]:.6g}, head={current_lrs[2]:.6g}") - - if accelerator.is_main_process: - print(f"Resumed from checkpoint: {resume_path}") - print(f" Starting from epoch {start_epoch}, global_step {global_step}, best_val_loss {best_val_loss:.4f}") - - for epoch in range(start_epoch, args.epochs + 1): - # Training phase - model.train() - train_loss = 0.0 - train_llm_loss = 0.0 - train_legal_move_loss = 0.0 - train_legal_move_ce = 0.0 - - progress_bar = tqdm(train_loader, desc=f"Epoch {epoch}/{args.epochs} - Training", leave=False) - for batch in progress_bar: - optimizer.zero_grad() - positions = batch["position"] - moves = batch["move"] - is_white = batch["is_white"] - legal_moves_mask = batch["legal_moves_mask"] - castling_rights = batch["castling_rights"] - en_passant_file = batch["en_passant_file"] - halfmove_clock = batch["halfmove_clock"] - - logits = model(positions, is_white, castling_rights, en_passant_file, halfmove_clock) - loss, llm_loss, legal_move_loss, legal_move_cross_entropy = compute_loss( - logits, moves, legal_moves_mask, args.beta, args.legal_move_loss_weight - ) - - accelerator.backward(loss) - - # Gradient clipping - if args.max_grad_norm > 0: - accelerator.clip_grad_norm_(model.parameters(), args.max_grad_norm) - - optimizer.step() - scheduler.step() - - batch_size = positions.size(0) - train_loss += loss.item() * batch_size - train_llm_loss += llm_loss.item() * batch_size - train_legal_move_loss += legal_move_loss.item() * batch_size - train_legal_move_ce += legal_move_cross_entropy.item() * batch_size - - progress_bar.set_postfix( - { - "loss": loss.item(), - "llm_loss": llm_loss.item(), - "legal_move_loss": legal_move_loss.item(), - "legal_move_ce": legal_move_cross_entropy.item(), - } - ) - - # Log step-level metrics - current_lrs = scheduler.get_last_lr() - log_dict = { - "train/step_loss": loss.item(), - "train/step_llm_loss": llm_loss.item(), - "train/step_legal_move_loss": legal_move_loss.item(), - "train/step_legal_move_ce": legal_move_cross_entropy.item(), - "train/lr_embeddings": current_lrs[0], - "train/lr_transformers": current_lrs[1], - "train/lr_head": current_lrs[2], - } - accelerator.log(log_dict, step=global_step) - - global_step += 1 - - # Save step checkpoint - if args.save_steps > 0 and global_step % args.save_steps == 0: - step_checkpoint_path = checkpoint_dir / f"checkpoint_step_{global_step:07d}" - accelerator.save_state(str(step_checkpoint_path)) - save_trainer_state(step_checkpoint_path, epoch, global_step, best_val_loss, scheduler_config) - if accelerator.is_main_process: - print(f"\n Saved step checkpoint at step {global_step}") - cleanup_old_step_checkpoints(checkpoint_dir, args.max_checkpoints) - - # Calculate average training metrics - train_loss /= len(train_set) - train_llm_loss /= len(train_set) - train_legal_move_loss /= len(train_set) - train_legal_move_ce /= len(train_set) - - # Validation phase - model.eval() - val_loss = 0.0 - val_llm_loss = 0.0 - val_legal_move_loss = 0.0 - val_legal_move_ce = 0.0 - val_correct = 0 - val_total = 0 - - with torch.no_grad(): - progress_bar = tqdm(val_loader, desc=f"Epoch {epoch}/{args.epochs} - Validation", leave=False) - for batch in progress_bar: - positions = batch["position"] - moves = batch["move"] - is_white = batch["is_white"] - legal_moves_mask = batch["legal_moves_mask"] - castling_rights = batch["castling_rights"] - en_passant_file = batch["en_passant_file"] - halfmove_clock = batch["halfmove_clock"] - - logits = model(positions, is_white, castling_rights, en_passant_file, halfmove_clock) - loss, llm_loss, legal_move_loss, legal_move_cross_entropy = compute_loss( - logits, moves, legal_moves_mask, args.beta, args.legal_move_loss_weight - ) - - batch_size = positions.size(0) - val_loss += loss.item() * batch_size - val_llm_loss += llm_loss.item() * batch_size - val_legal_move_loss += legal_move_loss.item() * batch_size - val_legal_move_ce += legal_move_cross_entropy.item() * batch_size - - # Calculate accuracy - predictions = torch.argmax(logits, dim=-1) - val_correct += (predictions == moves).sum().item() - val_total += batch_size - - progress_bar.set_postfix({"val_loss": loss.item()}) - - val_loss /= len(val_set) - val_llm_loss /= len(val_set) - val_legal_move_loss /= len(val_set) - val_legal_move_ce /= len(val_set) - val_accuracy = val_correct / val_total if val_total > 0 else 0.0 - - # Log epoch-level metrics - accelerator.log( - { - "train/epoch_loss": train_loss, - "train/epoch_llm_loss": train_llm_loss, - "train/epoch_legal_move_loss": train_legal_move_loss, - "train/epoch_legal_move_ce": train_legal_move_ce, - "val/loss": val_loss, - "val/llm_loss": val_llm_loss, - "val/legal_move_loss": val_legal_move_loss, - "val/legal_move_ce": val_legal_move_ce, - "val/accuracy": val_accuracy, - "epoch": epoch, - "train/lr_embeddings_epoch_end": scheduler.get_last_lr()[0], - "train/lr_transformers_epoch_end": scheduler.get_last_lr()[1], - "train/lr_head_epoch_end": scheduler.get_last_lr()[2], - }, - step=global_step, - ) - - print(f"\nEpoch {epoch}/{args.epochs}:") - print(f" Train Loss: {train_loss:.4f} | Val Loss: {val_loss:.4f} | Val Accuracy: {val_accuracy:.4f}") - - # Save best model - if val_loss < best_val_loss: - best_val_loss = val_loss - best_checkpoint_path = checkpoint_dir / "best_model" - accelerator.save_state(str(best_checkpoint_path)) - save_trainer_state(best_checkpoint_path, epoch, global_step, best_val_loss, scheduler_config) - print(f" Saved best model (val_loss: {val_loss:.4f})") - - # Periodic checkpoint saving - if epoch % args.save_every == 0: - checkpoint_path = checkpoint_dir / f"checkpoint_epoch_{epoch:03d}" - accelerator.save_state(str(checkpoint_path)) - save_trainer_state(checkpoint_path, epoch, global_step, best_val_loss, scheduler_config) - print(f" Saved checkpoint at epoch {epoch}") - - # Final test evaluation - print("\nRunning final test evaluation...") - model.eval() - test_loss = 0.0 - test_correct = 0 - test_total = 0 - - with torch.no_grad(): - progress_bar = tqdm(test_loader, desc="Testing", leave=False) - for batch in progress_bar: - positions = batch["position"] - moves = batch["move"] - is_white = batch["is_white"] - legal_moves_mask = batch["legal_moves_mask"] - castling_rights = batch["castling_rights"] - en_passant_file = batch["en_passant_file"] - halfmove_clock = batch["halfmove_clock"] - - logits = model(positions, is_white, castling_rights, en_passant_file, halfmove_clock) - loss, llm_loss, legal_move_loss, legal_move_cross_entropy = compute_loss( - logits, moves, legal_moves_mask, args.beta, args.legal_move_loss_weight - ) - - batch_size = positions.size(0) - test_loss += loss.item() * batch_size - - predictions = torch.argmax(logits, dim=-1) - test_correct += (predictions == moves).sum().item() - test_total += batch_size - - test_loss /= len(test_set) - test_accuracy = test_correct / test_total if test_total > 0 else 0.0 - - accelerator.log( - { - "test/loss": test_loss, - "test/accuracy": test_accuracy, - }, - step=global_step, - ) - - print(f"\nTest Results:") - print(f" Test Loss: {test_loss:.4f} | Test Accuracy: {test_accuracy:.4f}") - - # End tracking - accelerator.end_training() - print(f"\nTraining complete! Logs saved to: {log_path}") - - -if __name__ == "__main__": - main() diff --git a/chesstransformer/utils/__init__.py b/chesstransformer/utils/__init__.py deleted file mode 100644 index 15f4eaa33cae3fe69e6e54482617726e6cb37ba9..0000000000000000000000000000000000000000 --- a/chesstransformer/utils/__init__.py +++ /dev/null @@ -1,3 +0,0 @@ -from .chess_utils import generate_board_image, generate_board_ascii, generate_game_gif - -__all__ = ["generate_board_image", "generate_board_ascii", "generate_game_gif"] diff --git a/chesstransformer/utils/chess_utils.py b/chesstransformer/utils/chess_utils.py deleted file mode 100644 index c086cfd8ae01e6bbfbafdcd1d577a3e39bd0d5c0..0000000000000000000000000000000000000000 --- a/chesstransformer/utils/chess_utils.py +++ /dev/null @@ -1,123 +0,0 @@ -import chess -from PIL import Image -from io import BytesIO -import cairosvg - - -def _create_board_from_moves(moves: list[str]) -> chess.Board: - """ - Create a chess board and apply a sequence of moves. - - Args: - moves: List of moves in UCI format (e.g., ['e2e4', 'd7d5']) - - Returns: - Chess board with moves applied - """ - board = chess.Board() - for move_str in moves: - try: - move = chess.Move.from_uci(move_str) - board.push(move) - except ValueError: - pass # Skip invalid moves - return board - - -def generate_board_image(moves: list[str], size: int = 400) -> Image.Image: - """ - Generate a PIL image of a chess board after applying a sequence of moves. - - Args: - moves: List of moves in UCI format (e.g., ['e2e4', 'd7d5']) - size: Size of the output image in pixels (default: 400) - - Returns: - PIL Image of the chess board - """ - import chess.svg - - board = _create_board_from_moves(moves) - - # Generate SVG using chess library - svg_data = chess.svg.board(board, size=size) - - # Convert SVG to PNG using cairosvg - png_data = cairosvg.svg2png(bytestring=svg_data.encode("utf-8")) - - # Load PNG into PIL Image - img = Image.open(BytesIO(png_data)) - - return img - - -def generate_board_ascii(moves: list[str]) -> str: - """ - Generate an ASCII representation of a chess board after applying a sequence of moves. - - Args: - moves: List of moves in UCI format (e.g., ['e2e4', 'd7d5']) - - Returns: - String representation of the chess board - """ - board = _create_board_from_moves(moves) - return str(board) - - -def generate_game_gif(moves: list[str], size: int = 400, duration: int = 500) -> bytes: - """ - Generate an animated GIF of a chess game from a sequence of moves. - - Args: - moves: List of moves in UCI format (e.g., ['e2e4', 'd7d5']) - size: Size of each frame in pixels (default: 400) - duration: Duration of each frame in milliseconds (default: 500) - - Returns: - Bytes of the animated GIF - """ - frames = [] - - # Initial position - img = generate_board_image([], size) - frames.append(img) - - # Apply moves and capture frames - moves_so_far = [] - for move_str in moves: - try: - move = chess.Move.from_uci(move_str) - moves_so_far.append(move_str) - img = generate_board_image(moves_so_far, size) - frames.append(img) - except ValueError: - pass # Skip invalid moves - - # Save frames as GIF in memory - gif_bytes = BytesIO() - frames[0].save( - gif_bytes, - format="GIF", - save_all=True, - append_images=frames[1:], - duration=duration, - loop=0, - ) - gif_bytes.seek(0) - - return gif_bytes.getvalue() - - -if __name__ == "__main__": - moves = ["e2e4"] - img = generate_board_image(moves) - img.show() - - ascii_board = generate_board_ascii(moves) - print(ascii_board) - - coup_du_berget = ["e2e4", "e7e5", "f1c4", "b8c6", "d1h5", "g8f6", "h5f7"] - gif = generate_game_gif(coup_du_berget) - with open("coup_du_berget.gif", "wb") as f: - f.write(gif) diff --git a/chesstransformer/utils/evaluate_puzzles.py b/chesstransformer/utils/evaluate_puzzles.py deleted file mode 100644 index 77d29bf7e1f33d99fd241d7ac26afb702f8d84b5..0000000000000000000000000000000000000000 --- a/chesstransformer/utils/evaluate_puzzles.py +++ /dev/null @@ -1,426 +0,0 @@ -#!/usr/bin/env python3 -""" -Evaluation script for chess puzzle solving with Position2Move model. - -This script evaluates how well a trained model can solve chess puzzles by: -1. Loading a trained model checkpoint -2. Testing it on puzzles from the Lichess puzzle database -3. Measuring accuracy for first move, full solution, and by rating/theme -4. Generating detailed reports - -Usage: - python src/chesstransformer/utils/evaluate_puzzles.py --model data/models/puzzle_training/run_001/best_model.pth - -Options: - --model: Path to model checkpoint (required) - --puzzle-data: Path to puzzle .csv.zst file (default: data/lichess_db_puzzle.csv.zst) - --num-puzzles: Number of puzzles to evaluate (default: 1000) - --min-rating: Minimum puzzle rating (default: None) - --max-rating: Maximum puzzle rating (default: None) - --themes: Comma-separated puzzle themes to filter by (default: None) - --output: Output JSON file for results (default: results/puzzle_eval_{timestamp}.json) -""" - -from pathlib import Path -from datetime import datetime -import argparse -import json - -import torch -import chess -from tqdm.auto import tqdm - -from chesstransformer.datasets.puzzle_dataset import LichessPuzzleFullSolutionDataset -from chesstransformer.models.transformer.position2move import Position2MoveModel -from chesstransformer.models.tokenizer.position_tokenizer import PostionTokenizer -from chesstransformer.models.tokenizer.move_tokenizer import MoveTokenizer - - -class PuzzleEvaluator: - """Evaluates a Position2Move model on chess puzzles.""" - - def __init__(self, model, device="cpu"): - self.model = model - self.device = device - self.model.to(device) - self.model.eval() - - self.position_tokenizer = PostionTokenizer() - self.move_tokenizer = MoveTokenizer() - - def predict_move(self, board: chess.Board, top_k=5): - """ - Predict the best move for a given board position. - - Args: - board: chess.Board object - top_k: Return top-k predictions - - Returns: - List of (move_uci, probability, is_legal) tuples - """ - # Encode position - position_tokens = self.position_tokenizer.encode(board) - position_tensor = torch.tensor(position_tokens, dtype=torch.long).unsqueeze(0).to(self.device) - is_white = torch.tensor([board.turn == chess.WHITE], dtype=torch.long).to(self.device) - - # Get predictions - with torch.no_grad(): - logits = self.model(position_tensor, is_white) - - # Create legal moves mask - legal_moves = [m.uci() for m in board.legal_moves] - legal_move_indices = [] - for move_uci in legal_moves: - try: - idx = self.move_tokenizer.encode(move_uci) - legal_move_indices.append(idx) - except ValueError: - continue - - # Apply mask to logits (set illegal moves to -inf before softmax) - mask = torch.full_like(logits, float("-inf")) - if legal_move_indices: - mask[0, legal_move_indices] = 0 - masked_logits = logits + mask - - probs = torch.softmax(masked_logits, dim=-1) - - # Get top-k predictions - top_probs, top_indices = torch.topk(probs[0], k=top_k) - - predictions = [] - - for prob, idx in zip(top_probs.cpu().numpy(), top_indices.cpu().numpy()): - try: - move_uci = self.move_tokenizer.decode(int(idx)) - is_legal = move_uci in legal_moves - predictions.append((move_uci, float(prob), is_legal)) - except ValueError: - continue - - return predictions - - def evaluate_puzzle(self, puzzle_data, max_moves=10): - """ - Evaluate a single puzzle. - - Args: - puzzle_data: Dictionary with puzzle information - max_moves: Maximum number of moves to try in the solution - - Returns: - Dictionary with evaluation results - """ - board = chess.Board(puzzle_data["fen"]) - solution_moves = puzzle_data["moves_uci"] - - results = { - "puzzle_id": puzzle_data["puzzle_id"], - "rating": puzzle_data["rating"], - "themes": puzzle_data["themes"], - "solution_length": len(solution_moves), - "moves_tried": [], - "first_move_correct": False, - "fully_solved": False, - "moves_correct": 0, - "predictions": [], - } - - # Try to solve the puzzle move by move - for move_idx in range(0, len(solution_moves), 2): # Only predict our moves (every other move) - if move_idx >= max_moves: - break - - # Apply opponent's move first (if not the first move) - if move_idx > 0: - opponent_move = chess.Move.from_uci(solution_moves[move_idx - 1]) - if opponent_move in board.legal_moves: - board.push(opponent_move) - else: - # Opponent move is illegal - puzzle data might be corrupted - results["error"] = "Illegal opponent move in solution" - break - - # Predict our move - expected_move = solution_moves[move_idx] - predictions = self.predict_move(board, top_k=5) - - if not predictions: - results["error"] = "Model produced no valid predictions" - break - - predicted_move = predictions[0][0] - predicted_prob = predictions[0][1] - is_correct = predicted_move == expected_move - - results["moves_tried"].append( - { - "move_number": move_idx // 2 + 1, - "expected": expected_move, - "predicted": predicted_move, - "probability": predicted_prob, - "correct": is_correct, - "top_5_predictions": [{"move": m, "prob": p, "legal": l} for m, p, l in predictions], - } - ) - - if is_correct: - results["moves_correct"] += 1 - if move_idx == 0: - results["first_move_correct"] = True - - # Apply our correct move - our_move = chess.Move.from_uci(predicted_move) - board.push(our_move) - else: - # Wrong move - puzzle failed - break - - # Check if fully solved - if results["moves_correct"] == (len(solution_moves) + 1) // 2: - results["fully_solved"] = True - - return results - - def evaluate_dataset(self, dataset, num_puzzles=None): - """ - Evaluate the model on a puzzle dataset. - - Args: - dataset: LichessPuzzleFullSolutionDataset - num_puzzles: Number of puzzles to evaluate (None = all) - - Returns: - Dictionary with aggregate results - """ - num_puzzles = min(num_puzzles or len(dataset), len(dataset)) - - print(f"Evaluating {num_puzzles} puzzles...") - - results = { - "num_puzzles": num_puzzles, - "first_move_accuracy": 0, - "full_solution_accuracy": 0, - "average_moves_correct": 0, - "by_rating": {}, - "by_theme": {}, - "puzzle_results": [], - } - - first_move_correct = 0 - fully_solved = 0 - total_moves_correct = 0 - total_moves = 0 - - # Track by rating buckets - rating_buckets = { - "0-1000": {"first": 0, "full": 0, "total": 0}, - "1000-1500": {"first": 0, "full": 0, "total": 0}, - "1500-2000": {"first": 0, "full": 0, "total": 0}, - "2000-2500": {"first": 0, "full": 0, "total": 0}, - "2500+": {"first": 0, "full": 0, "total": 0}, - } - - # Track by theme - theme_stats = {} - - for i in tqdm(range(num_puzzles), desc="Evaluating puzzles"): - puzzle_data = dataset[i] - puzzle_result = self.evaluate_puzzle(puzzle_data) - - # Aggregate statistics - if puzzle_result["first_move_correct"]: - first_move_correct += 1 - if puzzle_result["fully_solved"]: - fully_solved += 1 - - total_moves_correct += puzzle_result["moves_correct"] - total_moves += puzzle_result["solution_length"] // 2 + 1 - - # Rating bucket - rating = puzzle_result["rating"] - if rating < 1000: - bucket = "0-1000" - elif rating < 1500: - bucket = "1000-1500" - elif rating < 2000: - bucket = "1500-2000" - elif rating < 2500: - bucket = "2000-2500" - else: - bucket = "2500+" - - rating_buckets[bucket]["total"] += 1 - if puzzle_result["first_move_correct"]: - rating_buckets[bucket]["first"] += 1 - if puzzle_result["fully_solved"]: - rating_buckets[bucket]["full"] += 1 - - # Theme statistics - for theme in puzzle_result["themes"]: - if theme not in theme_stats: - theme_stats[theme] = {"first": 0, "full": 0, "total": 0} - theme_stats[theme]["total"] += 1 - if puzzle_result["first_move_correct"]: - theme_stats[theme]["first"] += 1 - if puzzle_result["fully_solved"]: - theme_stats[theme]["full"] += 1 - - results["puzzle_results"].append(puzzle_result) - - # Calculate aggregate metrics - results["first_move_accuracy"] = 100.0 * first_move_correct / num_puzzles - results["full_solution_accuracy"] = 100.0 * fully_solved / num_puzzles - results["average_moves_correct"] = total_moves_correct / num_puzzles - results["move_accuracy"] = 100.0 * total_moves_correct / total_moves if total_moves > 0 else 0 - - # Rating bucket statistics - for bucket, stats in rating_buckets.items(): - if stats["total"] > 0: - results["by_rating"][bucket] = { - "count": stats["total"], - "first_move_accuracy": 100.0 * stats["first"] / stats["total"], - "full_solution_accuracy": 100.0 * stats["full"] / stats["total"], - } - - # Theme statistics (top 20 themes by frequency) - sorted_themes = sorted(theme_stats.items(), key=lambda x: x[1]["total"], reverse=True)[:20] - for theme, stats in sorted_themes: - results["by_theme"][theme] = { - "count": stats["total"], - "first_move_accuracy": 100.0 * stats["first"] / stats["total"], - "full_solution_accuracy": 100.0 * stats["full"] / stats["total"], - } - - return results - - -def main(): - parser = argparse.ArgumentParser(description="Evaluate Position2Move model on chess puzzles") - parser.add_argument("--model", type=str, required=True, help="Path to model checkpoint") - parser.add_argument( - "--puzzle-data", type=str, default="data/lichess_db_puzzle.csv.zst", help="Path to puzzle .csv.zst file" - ) - parser.add_argument("--num-puzzles", type=int, default=1000, help="Number of puzzles to evaluate") - parser.add_argument("--min-rating", type=int, default=None, help="Minimum puzzle rating") - parser.add_argument("--max-rating", type=int, default=None, help="Maximum puzzle rating") - parser.add_argument("--themes", type=str, default=None, help="Comma-separated puzzle themes to filter by") - parser.add_argument("--output", type=str, default=None, help="Output JSON file for results") - - args = parser.parse_args() - - # Parse themes - themes = args.themes.split(",") if args.themes else None - - # Setup device - device = torch.device("cuda" if torch.cuda.is_available() else "cpu") - print(f"Using device: {device}") - - # Load model - print(f"\nLoading model from {args.model}...") - model_path = Path(args.model) - - # Support both .pth and .safetensors formats - if model_path.suffix == ".safetensors": - # Load config from same directory - from safetensors import safe_open - import json - - config_path = model_path.parent / "config.json" - with open(config_path, "r") as f: - config = json.load(f) - - model = Position2MoveModel(**config) - - # Load weights from safetensors - with safe_open(str(model_path), framework="pt", device=str(device)) as f: - state_dict = {k: f.get_tensor(k) for k in f.keys()} - - # Handle compiled model prefix (_orig_mod.) - if any(k.startswith("_orig_mod.") for k in state_dict.keys()): - state_dict = {k.replace("_orig_mod.", ""): v for k, v in state_dict.items()} - - model.load_state_dict(state_dict) - - print(f"Model loaded from safetensors") - else: - # Load from .pth checkpoint - checkpoint = torch.load(args.model, map_location=device, weights_only=False) - config = checkpoint["config"] - - model = Position2MoveModel(**config) - model.load_state_dict(checkpoint["model_state_dict"]) - print(f"Model loaded (epoch {checkpoint.get('epoch', 'unknown')})") - - # Load puzzle dataset - print(f"\nLoading puzzle dataset...") - dataset = LichessPuzzleFullSolutionDataset( - puzzle_path=args.puzzle_data, - min_rating=args.min_rating, - max_rating=args.max_rating, - themes=themes, - max_puzzles=args.num_puzzles, - ) - - # Evaluate - print("\n" + "=" * 70) - print("Starting evaluation") - print("=" * 70) - - evaluator = PuzzleEvaluator(model, device=device) - results = evaluator.evaluate_dataset(dataset, num_puzzles=args.num_puzzles) - - # Print summary - print("\n" + "=" * 70) - print("EVALUATION RESULTS") - print("=" * 70) - print(f"Total puzzles: {results['num_puzzles']}") - print(f"First move accuracy: {results['first_move_accuracy']:.2f}%") - print(f"Full solution accuracy: {results['full_solution_accuracy']:.2f}%") - print(f"Move accuracy: {results['move_accuracy']:.2f}%") - print(f"Average moves correct: {results['average_moves_correct']:.2f}") - - print("\n" + "-" * 70) - print("By Rating:") - print("-" * 70) - for rating, stats in sorted(results["by_rating"].items()): - print( - f" {rating:>12}: {stats['count']:4} puzzles | " - f"First: {stats['first_move_accuracy']:5.2f}% | " - f"Full: {stats['full_solution_accuracy']:5.2f}%" - ) - - print("\n" + "-" * 70) - print("Top Themes:") - print("-" * 70) - for theme, stats in list(results["by_theme"].items())[:10]: - print( - f" {theme:>20}: {stats['count']:4} puzzles | " - f"First: {stats['first_move_accuracy']:5.2f}% | " - f"Full: {stats['full_solution_accuracy']:5.2f}%" - ) - - # Save results - if args.output: - output_path = args.output - else: - timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") - output_path = f"results/puzzle_eval_{timestamp}.json" - - output_path = Path(output_path) - output_path.parent.mkdir(parents=True, exist_ok=True) - - # Don't save individual puzzle results to keep file size manageable - results_summary = {k: v for k, v in results.items() if k != "puzzle_results"} - results_summary["num_puzzles_detailed"] = len(results["puzzle_results"]) - - with open(output_path, "w") as f: - json.dump(results_summary, f, indent=2) - - print(f"\nResults saved to {output_path}") - print("=" * 70) - - -if __name__ == "__main__": - main() diff --git a/frontend/.dockerignore b/frontend/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..0cf40507c703ad69c16e23c68d6237302cca9234 --- /dev/null +++ b/frontend/.dockerignore @@ -0,0 +1,36 @@ +# Dependencies +node_modules +.pnp +.pnp.js + +# Build outputs +.next +out +build + +# Testing +coverage + +# Misc +.DS_Store +*.pem + +# Debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Local env files +.env*.local +.env + +# Vercel +.vercel + +# TypeScript +*.tsbuildinfo +next-env.d.ts + +# IDE +.idea +.vscode diff --git a/frontend/.gitignore b/frontend/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..5ef6a520780202a1d6addd833d800ccb1ecac0bb --- /dev/null +++ b/frontend/.gitignore @@ -0,0 +1,41 @@ +# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. + +# dependencies +/node_modules +/.pnp +.pnp.* +.yarn/* +!.yarn/patches +!.yarn/plugins +!.yarn/releases +!.yarn/versions + +# testing +/coverage + +# next.js +/.next/ +/out/ + +# production +/build + +# misc +.DS_Store +*.pem + +# debug +npm-debug.log* +yarn-debug.log* +yarn-error.log* +.pnpm-debug.log* + +# env files (can opt-in for committing if needed) +.env* + +# vercel +.vercel + +# typescript +*.tsbuildinfo +next-env.d.ts diff --git a/frontend/Dockerfile b/frontend/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..3b9f657d15df41262010e717ea2d7583edf58aad --- /dev/null +++ b/frontend/Dockerfile @@ -0,0 +1,50 @@ +# Frontend Dockerfile for ChessTransformer Next.js app +FROM node:20-alpine AS base + +# Install dependencies only when needed +FROM base AS deps +RUN apk add --no-cache libc6-compat +WORKDIR /app + +# Copy package files +COPY package.json package-lock.json* ./ + +# Install dependencies +RUN npm ci + +# Rebuild the source code only when needed +FROM base AS builder +WORKDIR /app +COPY --from=deps /app/node_modules ./node_modules +COPY . . + +# Set the API URL for build time +ARG NEXT_PUBLIC_API_URL=http://localhost:5001 +ENV NEXT_PUBLIC_API_URL=$NEXT_PUBLIC_API_URL + +# Build the application +RUN npm run build + +# Production image, copy all the files and run next +FROM base AS runner +WORKDIR /app + +ENV NODE_ENV=production + +# Create non-root user +RUN addgroup --system --gid 1001 nodejs +RUN adduser --system --uid 1001 nextjs + +# Copy built application +COPY --from=builder /app/public ./public +COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./ +COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static + +USER nextjs + +EXPOSE 3000 + +ENV PORT=3000 +ENV HOSTNAME="0.0.0.0" + +CMD ["node", "server.js"] diff --git a/frontend/README.md b/frontend/README.md new file mode 100644 index 0000000000000000000000000000000000000000..df9922c569e7df198bb3a3068ae1f103ebee5d9e --- /dev/null +++ b/frontend/README.md @@ -0,0 +1,157 @@ +# ChessTransformer Frontend + +A Next.js web application for testing the ChessTransformer bot interactively. Play chess as a human against the AI-powered chess bot. + +## Features + +- 🎮 Interactive chessboard UI +- 🤖 Real-time bot integration +- 📊 Move history display +- ✅ Game status tracking (check, checkmate, draw) +- 🎯 Intuitive and beginner-friendly interface + +## Prerequisites + +- Node.js 18+ and npm +- Python 3.12+ +- UV package manager (for backend dependencies) + +## Setup + +### 1. Install Backend Dependencies + +From the project root directory: + +```bash +cd /path/to/ChessTransformer +uv sync +``` + +This will install all Python dependencies including FastAPI and uvicorn. + +### 2. Install Frontend Dependencies + +```bash +cd frontend +npm install +``` + +## Running the Application + +You need to run both the backend API server and the frontend development server. + +### Start the Backend API Server + +From the project root directory: + +```bash +cd backend +uv run python api.py +``` + +The API server will start on `http://localhost:5000`. + +**Note:** The backend will automatically fall back to using RandomBot if the Position2MoveBot model is not available. + +### Start the Frontend Development Server + +In a separate terminal, from the project root: + +```bash +cd frontend +npm run dev +``` + +The frontend will start on `http://localhost:3000`. + +## Usage + +1. Open your browser and navigate to `http://localhost:3000` +2. You'll see a chessboard with you playing as White +3. Make your move by dragging and dropping pieces +4. The bot (playing as Black) will automatically respond +5. The move history is displayed on the right side +6. Click "New Game" to start over at any time + +## Configuration + +The frontend API URL can be configured via environment variable: + +Create a `.env.local` file in the `frontend` directory: + +``` +NEXT_PUBLIC_API_URL=http://localhost:5000 +``` + +## Building for Production + +### Build the Frontend + +```bash +cd frontend +npm run build +npm start +``` + +This will create an optimized production build. + +### Deploy + +The frontend can be deployed to platforms like Vercel, Netlify, or any Node.js hosting service. + +The backend API should be deployed separately and the `NEXT_PUBLIC_API_URL` environment variable should be updated to point to the production API URL. + +## Technology Stack + +- **Frontend:** + - Next.js 15 (React framework) + - TypeScript + - Tailwind CSS + - chess.js (Chess logic) + - react-chessboard (Chessboard UI) + +- **Backend:** + - FastAPI (Python web framework) + - python-chess (Chess engine) + - ChessTransformer models + +## Troubleshooting + +### Backend Connection Error + +If you see "Failed to connect to the backend" error: +- Ensure the backend API server is running on port 5000 +- Check that CORS is enabled in the API +- Verify the API URL in your environment variables + +### Bot Not Loading + +If the bot type shows "RandomBot" instead of "Position2MoveBot": +- This is expected if the model files are not available +- The RandomBot will work fine for testing the interface +- To use the full Position2MoveBot, ensure model files are in the correct location + +## API Endpoints + +The backend provides the following endpoints: + +- `GET /api/health` - Health check and bot type +- `POST /api/move` - Get bot's next move +- `POST /api/new-game` - Start a new game +- `POST /api/validate-move` - Validate a move + +## Learn More + +To learn more about Next.js, take a look at the following resources: + +- [Next.js Documentation](https://nextjs.org/docs) +- [Learn Next.js](https://nextjs.org/learn) + +## Contributing + +Contributions are welcome! Please feel free to submit issues or pull requests. + +## License + +MIT + diff --git a/frontend/app/components/Avatars.tsx b/frontend/app/components/Avatars.tsx new file mode 100644 index 0000000000000000000000000000000000000000..603c4628d5f6384f9dea2937cb7cf0a9cfe64fb2 --- /dev/null +++ b/frontend/app/components/Avatars.tsx @@ -0,0 +1,91 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import type { Color } from 'chess.js'; +import { defaultPieces } from 'react-chessboard'; + +/** + * How strongly a query square attends to another, using the chess-geometry + * relations the model's attention bias is built on: king-adjacent, knight + * reach, shared file/rank, shared diagonal, everything else. + */ +function attention(q: number, s: number): number { + if (q === s) return 1; + const df = Math.abs((q % 8) - (s % 8)); + const dr = Math.abs((q >> 3) - (s >> 3)); + const d = Math.max(df, dr); + if (d === 1) return 0.7; + if (df * dr === 2) return 0.56; + if (df === 0 || dr === 0) return 0.48 - d * 0.045; + if (df === dr) return 0.42 - d * 0.04; + return 0.05; +} + +const IDLE_QUERY = 28; // e4 from the avatar's point of view + +/** + * The engine's avatar: an 8×8 attention map. While the engine searches, the + * query square wanders the board and the map follows it. + */ +export function BotAvatar({ size = 40, thinking = false }: { size?: number; thinking?: boolean }) { + const [query, setQuery] = useState(IDLE_QUERY); + + useEffect(() => { + if (!thinking || window.matchMedia('(prefers-reduced-motion: reduce)').matches) return; + let seed = 17; + const id = window.setInterval(() => { + seed = (seed * 1103515245 + 12345) & 0x7fffffff; + setQuery((q) => { + // a knight-ish hop, wrapped onto the board, keeps the motion legible + const hops = [17, 15, 10, 6, -6, -10, -15, -17, 9, -9, 7, -7]; + return (q + hops[seed % hops.length] + 64) % 64; + }); + }, 240); + return () => { + window.clearInterval(id); + setQuery(IDLE_QUERY); + }; + }, [thinking]); + + const gap = size >= 64 ? 1 : 0; + return ( +
+ {Array.from({ length: 64 }, (_, s) => { + const a = attention(query, s); + return ( + + ); + })} +
+ ); +} + +export function HumanAvatar({ size = 40, color }: { size?: number; color: Color }) { + const Pawn = defaultPieces[color === 'w' ? 'wP' : 'bP']; + return ( +
+
+ +
+
+ ); +} diff --git a/frontend/app/components/ChessGame.tsx b/frontend/app/components/ChessGame.tsx new file mode 100644 index 0000000000000000000000000000000000000000..6100b6b107ad094e8252557deae9ac5388be199c --- /dev/null +++ b/frontend/app/components/ChessGame.tsx @@ -0,0 +1,754 @@ +'use client'; + +import { useEffect, useMemo, useRef, useState, useSyncExternalStore, type CSSProperties, type ReactNode } from 'react'; +import { Chess, type Color, type PieceSymbol, type Square } from 'chess.js'; +import { Chessboard, defaultArrowOptions, type Arrow, type ChessboardOptions } from 'react-chessboard'; + +import { BotAvatar } from './Avatars'; +import EvalBar from './EvalBar'; +import GameOverModal from './GameOverModal'; +import MoveList from './MoveList'; +import PlayerBar, { type ClockView } from './PlayerBar'; +import PromotionPicker from './PromotionPicker'; +import SettingsMenu, { DEFAULT_SETTINGS, type Settings } from './SettingsMenu'; +import SearchView from './SearchView'; +import SetupPanel, { type ColorChoice, type EngineInfo } from './SetupPanel'; +import { + IconCopy, + IconDownload, + IconDraw, + IconFirst, + IconFlag, + IconFlip, + IconLast, + IconNext, + IconPause, + IconPlay, + IconPlus, + IconPrev, + IconRepeat, + IconUndo, +} from './icons'; +import { + applyPremove, + isPromotionSquare, + kingSquare, + material, + movePiece, + other, + placement, + premoveDests, + reasonText, + RESULT_SCORE, + START_FEN, + TIME_CONTROLS, + timeControlById, +} from '../core/chess'; +import { DRAW_OFFER_GAP, evalAt, GameController } from '../core/game'; +import { useStoredState } from '../core/hooks'; + +// An empty NEXT_PUBLIC_API_URL means same origin (the Space serves the API and the page together). +const API_BASE_URL = process.env.NEXT_PUBLIC_API_URL ?? 'http://localhost:5001'; + +// Board palette: sand and deep teal, with brass for move highlights and coral for +// premoves and annotations. +const BOARD = { light: '#e9e1cc', dark: '#5d8a84' }; +const TINT = { + last: 'rgba(247, 206, 84, 0.5)', + selected: 'rgba(247, 206, 84, 0.75)', + premove: 'rgba(214, 86, 74, 0.6)', + mark: 'rgba(226, 92, 68, 0.85)', +}; +const DOT = 'radial-gradient(circle, rgba(18, 38, 33, 0.22) 21%, transparent 22.5%)'; +const RING = 'radial-gradient(circle, transparent 71%, rgba(18, 38, 33, 0.24) 72.5%)'; +const CHECK = + 'radial-gradient(circle, rgba(236, 62, 46, 0.95) 0%, rgba(236, 62, 46, 0.6) 34%, rgba(236, 62, 46, 0) 72%)'; +const NOTATION_SIZE = 'clamp(9px, 1.55vmin, 13px)'; + +interface PendingPromotion { + from: Square; + to: Square; + premove: boolean; +} + +interface SetupPrefs { + color: ColorChoice; + tc: string; +} + +export default function ChessGame() { + const [ctl] = useState(() => new GameController(API_BASE_URL)); + const snap = useSyncExternalStore(ctl.subscribe, ctl.getSnapshot, ctl.getSnapshot); + const { phase, plies, playerColor, thinking, premoves, result, clock, autoplay } = snap; + + const [prefs, setPrefs] = useStoredState('ct-setup', { color: 'w', tc: 'none' }); + const [settings, setSettings] = useStoredState('ct-settings', DEFAULT_SETTINGS); + const [engine, setEngine] = useState(null); + const [offline, setOffline] = useState(false); + + // Board interaction state. `view` and `marks` remember the move count they were + // set at, so a new move returns the board to the live position and wipes marks. + const [flipped, setFlipped] = useState(false); + const [view, setView] = useState<{ ply: number; len: number } | null>(null); + const [selected, setSelected] = useState(null); + const [marks, setMarks] = useState<{ squares: string[]; len: number; at: number } | null>(null); + const [promotion, setPromotion] = useState(null); + const [confirmResign, setConfirmResign] = useState(false); + const [dismissedGame, setDismissedGame] = useState(0); + const [copied, setCopied] = useState(false); + const [tab, setTab] = useState<'moves' | 'search'>('moves'); + // A search line replayed on the board: hovered, or pinned by a click. Both are + // tied to the position they were set on, so any move or navigation drops them. + const [hoverPath, setHoverPath] = useState<{ path: string[]; key: string } | null>(null); + const [pinnedPath, setPinnedPath] = useState<{ path: string[]; key: string } | null>(null); + const lastDrop = useRef(0); + const rightDown = useRef(null); + + useEffect(() => ctl.setSoundEnabled(settings.sound), [ctl, settings.sound]); + useEffect(() => () => ctl.dispose(), [ctl]); + + useEffect(() => { + let cancelled = false; + let timer = 0; + const poll = (attempt: number) => { + fetch(`${API_BASE_URL}/api/health`) + .then((res) => res.json()) + .then((data) => { + if (cancelled) return; + setEngine({ sims: data.sims, elo: data.approx_elo, model: data.model }); + setOffline(false); + }) + .catch(() => { + if (cancelled) return; + if (attempt >= 2) setOffline(true); + timer = window.setTimeout(() => poll(attempt + 1), 2500); + }); + }; + poll(0); + return () => { + cancelled = true; + window.clearTimeout(timer); + }; + }, []); + + // ------------------------------------------------------------ derived position state + + const botColor = other(playerColor); + const liveFen = plies.length ? plies[plies.length - 1].fen : START_FEN; + const shown = view && view.len === plies.length ? view.ply : plies.length; + const isLive = shown === plies.length; + const shownFen = shown === 0 ? START_FEN : plies[shown - 1].fen; + const orientation: 'white' | 'black' = (playerColor === 'w') !== flipped ? 'white' : 'black'; + const visibleMarks = useMemo( + () => (marks && marks.len === plies.length && marks.at === shown ? marks.squares : []), + [marks, plies.length, shown], + ); + + // The search shown is the one made from this position, else the one that led to it. + const searchIndex = snap.searches[shown] ? shown : snap.searches[shown - 1] ? shown - 1 : null; + const search = searchIndex == null ? null : snap.searches[searchIndex]; + const previewKey = `${plies.length}:${shown}:${tab}`; + const activePath = + (hoverPath?.key === previewKey ? hoverPath.path : null) ?? (pinnedPath?.key === previewKey ? pinnedPath.path : null); + const searchRootFen = searchIndex == null ? null : searchIndex === 0 ? START_FEN : plies[searchIndex - 1].fen; + + const preview = useMemo(() => { + if (!activePath || !searchRootFen) return null; + const g = new Chess(searchRootFen); + const side = g.turn(); + const arrows: Arrow[] = []; + let last: { from: string; to: string } | null = null; + for (const [i, uci] of activePath.entries()) { + try { + const m = g.move({ from: uci.slice(0, 2), to: uci.slice(2, 4), promotion: uci[4] }); + // the searching side's moves in jade, replies in brass; older moves fade + const alpha = Math.max(0.3, 0.95 - (activePath.length - 1 - i) * 0.13).toFixed(2); + const rgb = m.color === side ? '63, 191, 143' : '240, 168, 48'; + arrows.push({ startSquare: m.from, endSquare: m.to, color: `rgba(${rgb}, ${alpha})` }); + last = { from: m.from, to: m.to }; + } catch { + break; + } + } + return { position: placement(g.fen()), arrows, last }; + }, [activePath, searchRootFen]); + + const onPreview = (path: string[] | null, pin = false) => { + if (path && pin) { + const same = pinnedPath?.key === previewKey && pinnedPath.path.join() === path.join(); + setPinnedPath(same ? null : { path, key: previewKey }); + } else { + setHoverPath(path ? { path, key: previewKey } : null); + } + }; + const clearPreview = () => { + setHoverPath(null); + setPinnedPath(null); + }; + + const liveGame = useMemo(() => new Chess(liveFen), [liveFen]); + const livePosition = useMemo(() => placement(liveFen), [liveFen]); + const shownPosition = useMemo(() => placement(shownFen), [shownFen]); + const plannedPosition = useMemo(() => premoves.reduce(applyPremove, livePosition), [livePosition, premoves]); + const boardPosition = useMemo(() => { + if (!isLive) return shownPosition; + return promotion ? movePiece(plannedPosition, promotion.from, promotion.to) : plannedPosition; + }, [isLive, shownPosition, plannedPosition, promotion]); + + const myTurn = phase === 'playing' && !autoplay && liveGame.turn() === playerColor && !thinking; + const activeSelected = + selected && phase === 'playing' && isLive && plannedPosition[selected]?.pieceType[0] === playerColor + ? selected + : null; + + const dests = useMemo(() => { + if (!activeSelected) return []; + return myTurn + ? liveGame.moves({ square: activeSelected, verbose: true }).map((m) => m.to) + : premoveDests(plannedPosition, activeSelected, playerColor); + }, [activeSelected, myTurn, liveGame, plannedPosition, playerColor]); + + const squareStyles = useMemo(() => { + const s: Record = {}; + const tint = (sq: string, color: string) => (s[sq] = { ...s[sq], backgroundColor: color }); + const last = shown > 0 ? plies[shown - 1] : null; + if (last) { + tint(last.from, TINT.last); + tint(last.to, TINT.last); + if (last.check) { + const king = kingSquare(shownPosition, other(last.color)); + if (king) s[king] = { ...s[king], backgroundImage: CHECK }; + } + } + if (isLive) { + premoves.forEach((pm) => { + tint(pm.from, TINT.premove); + tint(pm.to, TINT.premove); + }); + if (activeSelected) { + tint(activeSelected, TINT.selected); + if (settings.legalMoves) { + dests.forEach((d) => (s[d] = { ...s[d], backgroundImage: boardPosition[d] ? RING : DOT })); + } + } + } + visibleMarks.forEach((sq) => tint(sq, TINT.mark)); + return s; + }, [shown, plies, shownPosition, isLive, premoves, activeSelected, settings.legalMoves, dests, boardPosition, visibleMarks]); + + // ------------------------------------------------------------ actions + + const goTo = (ply: number) => { + const clamped = Math.max(0, Math.min(plies.length, ply)); + setView(clamped === plies.length ? null : { ply: clamped, len: plies.length }); + setPromotion(null); + }; + + /** Start a game with the saved setup; `watch` hands both sides to the engine. */ + const begin = (watch = false) => { + const color: Color = prefs.color === 'random' ? (Math.random() < 0.5 ? 'w' : 'b') : prefs.color; + setFlipped(false); + setView(null); + setSelected(null); + setMarks(null); + setPromotion(null); + setConfirmResign(false); + clearPreview(); + if (watch) setTab('search'); + ctl.start(color, timeControlById(prefs.tc), watch); + }; + + const toSetup = () => { + setView(null); + setSelected(null); + setPromotion(null); + ctl.reset(); + }; + + const resign = () => { + if (!plies.some((p) => p.color === playerColor) || confirmResign) { + setConfirmResign(false); + ctl.resign(); + return; + } + setConfirmResign(true); + window.setTimeout(() => setConfirmResign(false), 3000); + }; + + const downloadPgn = () => { + const url = URL.createObjectURL(new Blob([ctl.pgn()], { type: 'application/x-chess-pgn' })); + const a = document.createElement('a'); + a.href = url; + a.download = `chesstransformer-${new Date().toISOString().slice(0, 10)}.pgn`; + a.click(); + URL.revokeObjectURL(url); + }; + + const copyPgn = async () => { + try { + await navigator.clipboard.writeText(ctl.pgn()); + setCopied(true); + window.setTimeout(() => setCopied(false), 1600); + } catch { + // clipboard blocked; the download button still works + } + }; + + /** Queue a premove if the piece could ever make it; promotions ask for a piece first. */ + const planPremove = (from: Square, to: Square): boolean => { + if (!premoveDests(plannedPosition, from, playerColor).includes(to)) return false; + setSelected(null); + if (isPromotionSquare(plannedPosition, from, to) && !settings.autoQueen) { + setPromotion({ from, to, premove: true }); + } else { + ctl.queuePremove({ from, to }); + } + return true; + }; + + const tryMove = (from: Square, to: Square): boolean => { + if (myTurn) { + if (!liveGame.moves({ square: from, verbose: true }).some((m) => m.to === to)) return false; + setSelected(null); + if (ctl.needsPromotion(from, to) && !settings.autoQueen) { + setPromotion({ from, to, premove: false }); + return true; + } + return ctl.playMove(from, to); + } + return planPremove(from, to); + }; + + const pickPromotion = (piece: PieceSymbol) => { + if (!promotion) return; + const { from, to, premove } = promotion; + setPromotion(null); + if (premove && !ctl.isPlayerTurn()) ctl.queuePremove({ from, to, promotion: piece }); + else ctl.playMove(from, to, piece); + }; + + const onDrop = (from: string, to: string | null): boolean => { + lastDrop.current = performance.now(); + if (!to || from === to || !isLive || phase !== 'playing' || promotion || autoplay) return false; + return tryMove(from as Square, to as Square); + }; + + const onSquareClick = (square: Square) => { + // a drag that ends on its own square also fires a click; ignore that echo + if (performance.now() - lastDrop.current < 150) return; + if (preview) return clearPreview(); + if (!isLive) return goTo(plies.length); + if (phase !== 'playing' || promotion || autoplay) return; + if (activeSelected && activeSelected !== square && dests.includes(square)) { + tryMove(activeSelected, square); + setSelected(null); + return; + } + const own = plannedPosition[square]?.pieceType[0] === playerColor; + if (own && activeSelected !== square) return setSelected(square); + setSelected(null); + if (!own) ctl.clearPremoves(); + }; + + const onSquareRightClick = (square: string) => { + if (premoves.length || activeSelected) { + ctl.clearPremoves(); + setSelected(null); + return; + } + const squares = visibleMarks.includes(square) + ? visibleMarks.filter((s) => s !== square) + : [...visibleMarks, square]; + setMarks({ squares, len: plies.length, at: shown }); + }; + + // ------------------------------------------------------------ keyboard + + useEffect(() => { + const onKey = (e: KeyboardEvent) => { + if (e.metaKey || e.ctrlKey || e.altKey) return; + if (e.target instanceof HTMLElement && e.target.closest('input, textarea, select, [role="dialog"]')) { + if (e.key !== 'Escape') return; + } + const step = (to: number) => { + e.preventDefault(); + goTo(to); + }; + switch (e.key) { + case 'ArrowLeft': + return step(shown - 1); + case 'ArrowRight': + return step(shown + 1); + case 'ArrowUp': + case 'Home': + return step(0); + case 'ArrowDown': + case 'End': + return step(plies.length); + case 'f': + return setFlipped((f) => !f); + case 'Escape': + clearPreview(); + setDismissedGame(snap.gameId); + setPromotion(null); + setSelected(null); + ctl.clearPremoves(); + return; + } + }; + window.addEventListener('keydown', onKey); + return () => window.removeEventListener('keydown', onKey); + }); + + // ------------------------------------------------------------ view model + + const { takenBy, balance } = useMemo(() => material(shownPosition), [shownPosition]); + const setupTc = timeControlById(prefs.tc); + const clockFor = (c: Color): ClockView | null => { + if (phase === 'setup') return setupTc ? { ms: setupTc.base * 1000, since: 0, running: false } : null; + if (!clock) return null; + return { ms: clock[c], since: clock.since, running: clock.running === c && phase === 'playing' }; + }; + + const bar = (c: Color) => { + // Under autoplay the engine is playing the player's side too, and the bar says so. + const isBot = c === botColor || autoplay; + return ( + + ); + }; + const bottomColor: Color = orientation === 'white' ? 'w' : 'b'; + + const finalScore = result && !['resignation', 'timeout', 'abort'].includes(result.reason) ? RESULT_SCORE(result) : undefined; + const evalValue = evalAt(snap.evals, shown); + + const playerMoves = plies.filter((p) => p.color === playerColor).length; + const status = (() => { + if (phase === 'over' && result) { + if (result.reason === 'abort') return 'Game aborted'; + const who = + result.winner === null + ? 'Draw' + : autoplay + ? `${result.winner === 'w' ? 'White' : 'Black'} won` + : result.winner === playerColor + ? 'You won' + : 'ChessTransformer won'; + return `${who} ${reasonText(result)}`; + } + if (snap.engineError) return "The engine didn't answer."; + if (autoplay) return 'ChessTransformer is playing itself'; + if (thinking) return 'ChessTransformer is thinking…'; + if (phase === 'playing' && liveGame.turn() === playerColor) return liveGame.inCheck() ? 'Your move. You are in check.' : 'Your move'; + return ''; + })(); + const tcLabel = TIME_CONTROLS.find((t) => t.value === snap.timeControl)?.label ?? 'No clock'; + + const boardOptions: ChessboardOptions = { + id: 'ct-board', + position: preview?.position ?? boardPosition, + boardOrientation: orientation, + squareStyles: preview + ? preview.last + ? { [preview.last.from]: { backgroundColor: TINT.last }, [preview.last.to]: { backgroundColor: TINT.last } } + : {} + : squareStyles, + arrows: preview?.arrows ?? [], + allowDrawingArrows: !preview, + darkSquareStyle: { backgroundColor: BOARD.dark }, + lightSquareStyle: { backgroundColor: BOARD.light }, + darkSquareNotationStyle: { color: BOARD.light, fontWeight: 600 }, + lightSquareNotationStyle: { color: BOARD.dark, fontWeight: 600 }, + alphaNotationStyle: { fontSize: NOTATION_SIZE, position: 'absolute', bottom: 1, right: 3, userSelect: 'none' }, + numericNotationStyle: { fontSize: NOTATION_SIZE, position: 'absolute', top: 2, left: 3, userSelect: 'none' }, + dropSquareStyle: { boxShadow: 'inset 0 0 0 3px rgba(255, 255, 255, 0.7)' }, + draggingPieceStyle: { transform: 'scale(1.12)' }, + draggingPieceGhostStyle: { opacity: 0.3 }, + boardStyle: { borderRadius: 4, boxShadow: '0 6px 24px rgba(0, 0, 0, 0.35)' }, + animationDurationInMs: 170, + allowDragging: phase === 'playing' && isLive && !preview, + canDragPiece: ({ piece }) => piece.pieceType[0] === playerColor && !promotion && !autoplay, + arrowOptions: { + ...defaultArrowOptions, + color: '#f0a830', + secondaryColor: '#3fbf8f', + tertiaryColor: '#e0574b', + opacity: 0.82, + activeOpacity: 0.6, + }, + onPieceDrag: ({ square }) => square && setSelected(square as Square), + onPieceDrop: ({ sourceSquare, targetSquare }) => onDrop(sourceSquare, targetSquare), + onSquareClick: ({ square }) => onSquareClick(square as Square), + // Right-click is read from mousedown/up on the same square rather than the + // contextmenu event, which Linux fires on mousedown, before an arrow drag. + onSquareMouseDown: ({ square }, e) => { + if (e.button === 0 && visibleMarks.length) setMarks(null); + if (e.button === 2) rightDown.current = square; + }, + onSquareMouseUp: ({ square }, e) => { + if (e.button === 2 && rightDown.current === square) onSquareRightClick(square); + rightDown.current = null; + }, + }; + + const showModal = phase === 'over' && result && dismissedGame !== snap.gameId; + + return ( +
+
+
+
+ +
+
{bar(other(bottomColor))}
+ {settings.evalBar ? ( +
+ +
+ ) : null} +
e.preventDefault()}> + + {promotion ? ( + setPromotion(null)} + /> + ) : null} + {showModal ? ( + begin(autoplay)} + onNewGame={toSetup} + onDownload={downloadPgn} + onClose={() => setDismissedGame(snap.gameId)} + /> + ) : null} +
+
{bar(bottomColor)}
+
+ + +
+
+ ); +} + +function PanelButton({ + onClick, + icon, + label, + disabled, + danger, + primary, +}: { + onClick: () => void; + icon: ReactNode; + label: string; + disabled?: boolean; + danger?: boolean; + primary?: boolean; +}) { + return ( + + ); +} + +function NavButton({ + onClick, + disabled, + label, + narrow, + children, +}: { + onClick: () => void; + disabled?: boolean; + label: string; + narrow?: boolean; + children: ReactNode; +}) { + return ( + + ); +} diff --git a/frontend/app/components/EvalBar.tsx b/frontend/app/components/EvalBar.tsx new file mode 100644 index 0000000000000000000000000000000000000000..a56b9b6e48bd44aff6c5bd2b0fcec0a89d82f479 --- /dev/null +++ b/frontend/app/components/EvalBar.tsx @@ -0,0 +1,44 @@ +import { formatEval } from '../core/chess'; + +interface Props { + /** Expected score for White in (-1, 1), or null before the engine has spoken. */ + value: number | null; + /** Final score once the game is decided ('1-0', '0-1', '1/2-1/2'). */ + final?: string; + orientation: 'white' | 'black'; +} + +export default function EvalBar({ value, final, orientation }: Props) { + let white = value == null ? 0.5 : Math.min(0.97, Math.max(0.03, (value + 1) / 2)); + if (final === '1-0') white = 1; + else if (final === '0-1') white = 0; + else if (final === '1/2-1/2') white = 0.5; + + const whiteAhead = white >= 0.5; + const label = final ?? (value == null ? '0.0' : formatEval(value)); + // The label sits at the end of the bar belonging to the side that is ahead. + const labelAtBottom = whiteAhead === (orientation === 'white'); + + return ( +
+
+ + {label} + +
+ ); +} diff --git a/frontend/app/components/GameOverModal.tsx b/frontend/app/components/GameOverModal.tsx new file mode 100644 index 0000000000000000000000000000000000000000..0acf747e332088e51408d60845edd8b0b7c895cc --- /dev/null +++ b/frontend/app/components/GameOverModal.tsx @@ -0,0 +1,88 @@ +'use client'; + +import type { Color } from 'chess.js'; +import { BotAvatar, HumanAvatar } from './Avatars'; +import { IconDownload, IconX } from './icons'; +import { RESULT_SCORE, reasonText, type GameResult } from '../core/chess'; + +interface Props { + result: GameResult; + playerColor: Color; + /** The engine played both sides: name the winner by color. */ + selfPlay: boolean; + onRematch: () => void; + onNewGame: () => void; + onDownload: () => void; + onClose: () => void; +} + +export default function GameOverModal({ result, playerColor, selfPlay, onRematch, onNewGame, onDownload, onClose }: Props) { + const aborted = result.reason === 'abort'; + const title = aborted + ? 'Game aborted' + : result.winner === null + ? 'Draw' + : selfPlay + ? `${result.winner === 'w' ? 'White' : 'Black'} won` + : result.winner === playerColor + ? 'You won' + : 'ChessTransformer won'; + const score = RESULT_SCORE(result).replace('1/2', '½').replace('1/2', '½'); + const [left, right] = playerColor === 'w' ? score.split('-') : score.split('-').reverse(); + + return ( +
+
e.stopPropagation()} + > + +

+ {title} +

+

{reasonText(result)}

+ + {!aborted ? ( +
+ {selfPlay ? : } + + {left} + – + {right} + + +
+ ) : null} + +
+ + +
+ {!aborted ? ( + + ) : null} +
+
+ ); +} diff --git a/frontend/app/components/MoveList.tsx b/frontend/app/components/MoveList.tsx new file mode 100644 index 0000000000000000000000000000000000000000..25831b7c7a6cb358c2a3d4d6bd9b57be931bac65 --- /dev/null +++ b/frontend/app/components/MoveList.tsx @@ -0,0 +1,86 @@ +'use client'; + +import { useEffect, useRef } from 'react'; +import type { Ply } from '../core/chess'; + +interface Props { + plies: Ply[]; + /** Number of plies applied in the shown position (0 = start). */ + current: number; + onSelect: (index: number) => void; + variant: 'table' | 'strip'; + emptyText?: string; +} + +export default function MoveList({ plies, current, onSelect, variant, emptyText }: Props) { + const box = useRef(null); + + // Keep the shown move in view without scrolling the page itself. + useEffect(() => { + const el = box.current; + const active = el?.querySelector('[data-active="true"]'); + if (!el) return; + if (variant === 'strip') { + el.scrollLeft = active ? active.offsetLeft - el.clientWidth / 2 + active.clientWidth / 2 : el.scrollWidth; + } else if (active) { + const top = active.offsetTop - el.offsetTop; + if (top < el.scrollTop || top + active.clientHeight > el.scrollTop + el.clientHeight) { + el.scrollTop = top - el.clientHeight / 2; + } + } else if (current === plies.length) { + el.scrollTop = el.scrollHeight; + } + }, [current, plies.length, variant]); + + const rows = Array.from({ length: Math.ceil(plies.length / 2) }, (_, i) => i); + + const move = (index: number) => { + const ply = plies[index - 1]; + if (!ply) return null; + const active = index === current; + return ( + + ); + }; + + if (variant === 'strip') { + return ( +
+ {plies.length === 0 ? {emptyText} : null} + {plies.map((_, i) => ( + + {i % 2 === 0 ? {i / 2 + 1}. : null} + {move(i + 1)} + + ))} +
+ ); + } + + return ( +
+ {plies.length === 0 ?

{emptyText}

: null} +
    + {rows.map((r) => ( +
  1. + {r + 1}. + {move(2 * r + 1)} + {move(2 * r + 2)} +
  2. + ))} +
+
+ ); +} diff --git a/frontend/app/components/PlayerBar.tsx b/frontend/app/components/PlayerBar.tsx new file mode 100644 index 0000000000000000000000000000000000000000..d587333e444b76690a0f2558c3adee989bc346b2 --- /dev/null +++ b/frontend/app/components/PlayerBar.tsx @@ -0,0 +1,115 @@ +'use client'; + +import { useEffect, useState } from 'react'; +import type { Color, PieceSymbol } from 'chess.js'; +import { defaultPieces } from 'react-chessboard'; +import { BotAvatar, HumanAvatar } from './Avatars'; +import { formatClock, other } from '../core/chess'; + +export interface ClockView { + ms: number; // remaining when `since` was stamped + since: number; + running: boolean; +} + +interface Props { + kind: 'bot' | 'human'; + name: string; + rating?: number; + color: Color; + taken: PieceSymbol[]; + advantage: number; + clock: ClockView | null; + toMove: boolean; + thinking?: boolean; +} + +export default function PlayerBar({ kind, name, rating, color, taken, advantage, clock, toMove, thinking }: Props) { + return ( +
+ {kind === 'bot' ? : } +
+
+ {name} + {rating ? ({rating}) : null} + {thinking ? : null} +
+ +
+ {clock ? : null} +
+ ); +} + +function ThinkingDots() { + return ( + + {[0, 1, 2].map((i) => ( + + ))} + + ); +} + +function Captured({ pieces, pieceColor, advantage }: { pieces: PieceSymbol[]; pieceColor: Color; advantage: number }) { + const groups = pieces.reduce((acc, p) => { + const last = acc[acc.length - 1]; + if (last && last[0] === p) last.push(p); + else acc.push([p]); + return acc; + }, []); + return ( +
+ {groups.map((group) => ( + + {group.map((p, i) => { + const Piece = defaultPieces[`${pieceColor}${p.toUpperCase()}`]; + return ( + + + + ); + })} + + ))} + {advantage > 0 ? +{advantage} : null} +
+ ); +} + +function Clock({ ms, since, running, toMove }: ClockView & { toMove: boolean }) { + const [now, setNow] = useState(since); + + useEffect(() => { + if (!running) return; + const id = window.setInterval(() => setNow(Date.now()), 100); + return () => window.clearInterval(id); + }, [running]); + + const left = running ? ms - Math.max(0, now - since) : ms; + const low = left < 20_000; + const active = running || toMove; + const tone = active + ? low + ? 'bg-coral text-white' + : 'bg-sand text-ink' + : low + ? 'bg-raised text-coral' + : 'bg-raised text-muted'; + return ( +
+ {formatClock(left)} +
+ ); +} diff --git a/frontend/app/components/PromotionPicker.tsx b/frontend/app/components/PromotionPicker.tsx new file mode 100644 index 0000000000000000000000000000000000000000..4bf9c00f1a1e51e374af4be70cf15d5ffc0ddbcf --- /dev/null +++ b/frontend/app/components/PromotionPicker.tsx @@ -0,0 +1,64 @@ +'use client'; + +import type { Color, PieceSymbol } from 'chess.js'; +import { defaultPieces } from 'react-chessboard'; +import { IconX } from './icons'; + +const CHOICES: PieceSymbol[] = ['q', 'n', 'r', 'b']; +const NAMES: Partial> = { q: 'Queen', n: 'Knight', r: 'Rook', b: 'Bishop' }; + +interface Props { + square: string; + color: Color; + orientation: 'white' | 'black'; + onPick: (piece: PieceSymbol) => void; + onCancel: () => void; +} + +/** chess.com-style column of promotion choices, dropping from the promotion square toward the centre. */ +export default function PromotionPicker({ square, color, orientation, onPick, onCancel }: Props) { + const file = 'abcdefgh'.indexOf(square[0]); + const rank = Number(square[1]); + const col = orientation === 'white' ? file : 7 - file; + const row = orientation === 'white' ? 8 - rank : rank - 1; + const fromTop = row === 0; + + return ( +
e.preventDefault()}> +
+
e.stopPropagation()} + > + {CHOICES.map((p) => { + const Piece = defaultPieces[`${color}${p.toUpperCase()}`]; + return ( + + ); + })} + +
+
+ ); +} diff --git a/frontend/app/components/SearchView.tsx b/frontend/app/components/SearchView.tsx new file mode 100644 index 0000000000000000000000000000000000000000..9492d11208f08326ff6186497b52220fbce83e6c --- /dev/null +++ b/frontend/app/components/SearchView.tsx @@ -0,0 +1,227 @@ +'use client'; + +import { useMemo } from 'react'; +import { Chess, type Color } from 'chess.js'; +import { formatEval } from '../core/chess'; +import type { SearchInfo, SearchNode } from '../core/game'; + +/** A searched move with its SAN and the UCI path that leads to it from the searched position. */ +interface Branch { + id: string; + san: string; + color: Color; + visits: number; + q: number; + path: string[]; + children: Branch[]; +} + +function annotate(fen: string, nodes: SearchNode[], path: string[] = []): Branch[] { + const out: Branch[] = []; + for (const n of nodes) { + const g = new Chess(fen); + try { + const m = g.move({ from: n.move.slice(0, 2), to: n.move.slice(2, 4), promotion: n.move[4] }); + const p = [...path, n.move]; + out.push({ + id: p.join(' '), + san: m.san, + color: m.color, + visits: n.visits, + q: n.q, + path: p, + children: annotate(g.fen(), n.children, p), + }); + } catch { + // a move that doesn't parse here would mean a stale tree; skip it + } + } + return out; +} + +/** The branch followed by always taking the most-visited reply. */ +const mainLine = (b: Branch): Branch[] => (b.children[0] ? [b, ...mainLine(b.children[0])] : [b]); + +// ---------------------------------------------------------------- tree layout + +const MAX_DEPTH = 6; +const ROW = 20; +const COL = 56; +const ROOT_X = 8; +const FIRST_X = 26; +const LABEL_W = 40; + +interface Placed { + branch: Branch; + depth: number; + x: number; + y: number; + parent: Placed | null; +} + +/** Tidy tree, left to right: leaves take consecutive rows, parents centre on their children. */ +function layout(roots: Branch[]) { + const placed: Placed[] = []; + let row = 0; + const place = (branch: Branch, depth: number, parent: Placed | null): Placed => { + const me: Placed = { branch, depth, x: FIRST_X + (depth - 1) * COL, y: 0, parent }; + placed.push(me); + const kids = depth < MAX_DEPTH ? branch.children : []; + if (!kids.length) { + me.y = row++ * ROW + ROW / 2; + } else { + const ys = kids.map((k) => place(k, depth + 1, me).y); + me.y = (ys[0] + ys[ys.length - 1]) / 2; + } + return me; + }; + const tops = roots.map((r) => place(r, 1, null)); + const rootY = tops.length ? (tops[0].y + tops[tops.length - 1].y) / 2 : ROW / 2; + return { placed, rootY, height: Math.max(row, 1) * ROW }; +} + +// ---------------------------------------------------------------- view + +interface Props { + search: SearchInfo; + /** The searched position. */ + fen: string; + /** SAN of the move the engine played from it, once known. */ + played?: string; + /** Path being previewed on the board, if any. */ + active: string[] | null; + onPreview: (path: string[] | null, pin?: boolean) => void; +} + +export default function SearchView({ search, fen, played, active, onPreview }: Props) { + const roots = useMemo(() => annotate(fen, search.tree), [fen, search.tree]); + const { placed, rootY, height } = useMemo(() => layout(roots), [roots]); + const total = Math.max(1, search.visits); + const activeId = active?.join(' ') ?? null; + const chosen = roots.find((r) => r.san === played) ?? roots[0]; + const mainIds = useMemo(() => new Set(chosen ? mainLine(chosen).map((b) => b.id) : []), [chosen]); + const onActive = (id: string) => !!activeId && (activeId === id || activeId.startsWith(`${id} `)); + + const hover = (path: string[]) => ({ + onMouseEnter: () => onPreview(path), + onMouseLeave: () => onPreview(null), + onFocus: () => onPreview(path), + onBlur: () => onPreview(null), + onClick: () => onPreview(path, true), + }); + + return ( +
+

+ {played ? ( + <> + Chose {played} after + + ) : ( + 'Weighed' + )}{' '} + {search.visits.toLocaleString()} positions in {(search.elapsedMs / 1000).toFixed(1)} s. Bars show each + move's share of the search; hover or tap one to replay its line on the board. +

+ {search.depth ? ( +

+ Its main line runs {search.depth.mainLine} half-moves deep and + the deepest branch {search.depth.max}; a typical simulation stops after {search.depth.mean.toFixed(0)}. The + diagram below shows only the first {MAX_DEPTH}. +

+ ) : null} + +
    + {roots.map((r) => { + const share = r.visits / total; + const line = mainLine(r).slice(1, 8); + const white = r.color === 'w' ? r.q : -r.q; + const isChosen = r === chosen; + return ( +
  1. + +
  2. + ); + })} +
+ +

Branches explored

+ + + {placed.map((p) => { + const x1 = p.parent ? p.parent.x + LABEL_W : ROOT_X + 4; + const y1 = p.parent ? p.parent.y : rootY; + const mid = (x1 + p.x) / 2; + const share = p.branch.visits / total; + const lit = onActive(p.branch.id); + const main = mainIds.has(p.branch.id); + return ( + + ); + })} + {placed.map((p) => { + const lit = onActive(p.branch.id); + const main = mainIds.has(p.branch.id); + return ( + + + + {p.branch.san} + + + ); + })} + +
+ ); +} diff --git a/frontend/app/components/SettingsMenu.tsx b/frontend/app/components/SettingsMenu.tsx new file mode 100644 index 0000000000000000000000000000000000000000..7a1d23f3bbac2be74bc8f2b1fb68fbf229d7c575 --- /dev/null +++ b/frontend/app/components/SettingsMenu.tsx @@ -0,0 +1,70 @@ +'use client'; + +import { useEffect, useRef, useState } from 'react'; +import { IconGear } from './icons'; + +export interface Settings { + sound: boolean; + legalMoves: boolean; + evalBar: boolean; + autoQueen: boolean; +} + +export const DEFAULT_SETTINGS: Settings = { sound: true, legalMoves: true, evalBar: true, autoQueen: false }; + +const ITEMS: { key: keyof Settings; label: string }[] = [ + { key: 'sound', label: 'Sound' }, + { key: 'legalMoves', label: 'Show legal moves' }, + { key: 'evalBar', label: 'Evaluation bar' }, + { key: 'autoQueen', label: 'Always promote to queen' }, +]; + +export default function SettingsMenu({ settings, onChange }: { settings: Settings; onChange: (s: Settings) => void }) { + const [open, setOpen] = useState(false); + const root = useRef(null); + + useEffect(() => { + if (!open) return; + const close = (e: MouseEvent | KeyboardEvent) => { + if (e instanceof KeyboardEvent ? e.key === 'Escape' : !root.current?.contains(e.target as Node)) setOpen(false); + }; + window.addEventListener('mousedown', close); + window.addEventListener('keydown', close); + return () => { + window.removeEventListener('mousedown', close); + window.removeEventListener('keydown', close); + }; + }, [open]); + + return ( +
+ + {open ? ( +
+ {ITEMS.map(({ key, label }) => ( + + ))} +
+ ) : null} +
+ ); +} diff --git a/frontend/app/components/SetupPanel.tsx b/frontend/app/components/SetupPanel.tsx new file mode 100644 index 0000000000000000000000000000000000000000..df8f7b777c02099586e3613bb6d000941c88a6db --- /dev/null +++ b/frontend/app/components/SetupPanel.tsx @@ -0,0 +1,135 @@ +'use client'; + +import type { JSX } from 'react'; +import { defaultPieces } from 'react-chessboard'; +import { BotAvatar } from './Avatars'; +import { TIME_CONTROLS } from '../core/chess'; + +export type ColorChoice = 'w' | 'random' | 'b'; + +export interface EngineInfo { + sims?: number; + elo?: number; + model?: string; +} + +interface Props { + engine: EngineInfo | null; + offline: boolean; + color: ColorChoice; + onColor: (c: ColorChoice) => void; + timeControl: string; + onTimeControl: (id: string) => void; + onPlay: () => void; + onWatch: () => void; +} + +const WhiteKing = defaultPieces.wK; +const BlackKing = defaultPieces.bK; + +function RandomKing() { + return ( + + + + + + + + + ); +} + +const COLORS: { id: ColorChoice; label: string; Icon: () => JSX.Element }[] = [ + { id: 'w', label: 'White', Icon: WhiteKing }, + { id: 'random', label: 'Random', Icon: RandomKing }, + { id: 'b', label: 'Black', Icon: BlackKing }, +]; + +export default function SetupPanel({ engine, offline, color, onColor, timeControl, onTimeControl, onPlay, onWatch }: Props) { + return ( +
+
+ +
+

ChessTransformer

+

+ {engine?.elo ? `Rated about ${engine.elo}` : offline ? 'Engine offline' : 'Connecting to the engine'} +

+

+ A transformer that learned chess from human games only, then searches{' '} + {engine?.sims ? `${engine.sims} positions` : 'ahead'} before each move. +

+
+
+ +
+

I play as

+
+ {COLORS.map(({ id, label, Icon }) => ( + + ))} +
+
+ +
+

Time control

+
+ {TIME_CONTROLS.map((tc) => ( + + ))} +
+

+ The engine's clock runs while it searches, so faster time controls press it too. +

+
+ +
+ + + {offline ? ( +

+ Can't reach the engine. Start the backend (see the README) and this page will connect on its own. +

+ ) : null} + +
+
+ ); +} diff --git a/frontend/app/components/icons.tsx b/frontend/app/components/icons.tsx new file mode 100644 index 0000000000000000000000000000000000000000..2393c409bbb9de7f91621df7118e6f820c67eb3f --- /dev/null +++ b/frontend/app/components/icons.tsx @@ -0,0 +1,66 @@ +import type { SVGProps } from 'react'; + +const base = (props: SVGProps) => ({ + width: 20, + height: 20, + viewBox: '0 0 24 24', + fill: 'none', + stroke: 'currentColor', + strokeWidth: 2, + strokeLinecap: 'round' as const, + strokeLinejoin: 'round' as const, + 'aria-hidden': true, + ...props, +}); + +export const IconFirst = (p: SVGProps) => ( + +); +export const IconPrev = (p: SVGProps) => ( + +); +export const IconNext = (p: SVGProps) => ( + +); +export const IconLast = (p: SVGProps) => ( + +); +export const IconFlip = (p: SVGProps) => ( + +); +export const IconFlag = (p: SVGProps) => ( + +); +export const IconUndo = (p: SVGProps) => ( + +); +export const IconDraw = (p: SVGProps) => ( + ½ +); +export const IconPlay = (p: SVGProps) => ( + +); +export const IconPause = (p: SVGProps) => ( + +); +export const IconX = (p: SVGProps) => ( + +); +export const IconGear = (p: SVGProps) => ( + + + + +); +export const IconDownload = (p: SVGProps) => ( + +); +export const IconCopy = (p: SVGProps) => ( + +); +export const IconPlus = (p: SVGProps) => ( + +); +export const IconRepeat = (p: SVGProps) => ( + +); diff --git a/frontend/app/core/chess.ts b/frontend/app/core/chess.ts new file mode 100644 index 0000000000000000000000000000000000000000..6cac6556c1904296fbf318f701c03baf4fe01eb4 --- /dev/null +++ b/frontend/app/core/chess.ts @@ -0,0 +1,279 @@ +import type { Chess, Color, PieceSymbol, Square } from 'chess.js'; +import type { PositionDataType } from 'react-chessboard'; + +export const START_FEN = 'rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1'; +const FILES = 'abcdefgh'; + +export type Phase = 'setup' | 'playing' | 'over'; + +/** One half-move as played, with the position it produced. */ +export interface Ply { + san: string; + from: Square; + to: Square; + color: Color; + piece: PieceSymbol; + captured?: PieceSymbol; + promotion?: PieceSymbol; + castle: boolean; + check: boolean; + fen: string; +} + +export interface Premove { + from: Square; + to: Square; + promotion?: PieceSymbol; +} + +export type ResultReason = + | 'checkmate' + | 'resignation' + | 'timeout' + | 'timeout vs insufficient material' + | 'stalemate' + | 'insufficient material' + | 'repetition' + | '50-move rule' + | 'agreement' + | 'abort'; + +export interface GameResult { + winner: Color | null; + reason: ResultReason; +} + +/** Seconds of base time and increment; `null` means an untimed game. */ +export type TimeControl = { base: number; inc: number } | null; + +export const TIME_CONTROLS: { id: string; label: string; value: TimeControl }[] = [ + { id: 'none', label: 'No clock', value: null }, + { id: '3+2', label: '3 | 2', value: { base: 180, inc: 2 } }, + { id: '5+0', label: '5 min', value: { base: 300, inc: 0 } }, + { id: '10+0', label: '10 min', value: { base: 600, inc: 0 } }, + { id: '15+10', label: '15 | 10', value: { base: 900, inc: 10 } }, + { id: '30+0', label: '30 min', value: { base: 1800, inc: 0 } }, +]; + +export const timeControlById = (id: string): TimeControl => + TIME_CONTROLS.find((t) => t.id === id)?.value ?? null; + +export const other = (c: Color): Color => (c === 'w' ? 'b' : 'w'); + +const coords = (sq: string) => ({ f: FILES.indexOf(sq[0]), r: Number(sq[1]) - 1 }); +const square = (f: number, r: number) => `${FILES[f]}${r + 1}` as Square; +const onBoard = (f: number, r: number) => f >= 0 && f < 8 && r >= 0 && r < 8; + +/** Piece placement of a FEN, in react-chessboard's position format. */ +export function placement(fen: string): PositionDataType { + const pos: PositionDataType = {}; + fen + .split(' ')[0] + .split('/') + .forEach((row, i) => { + let f = 0; + for (const ch of row) { + if (ch >= '1' && ch <= '8') { + f += Number(ch); + } else { + const color = ch === ch.toUpperCase() ? 'w' : 'b'; + pos[`${FILES[f]}${8 - i}`] = { pieceType: `${color}${ch.toUpperCase()}` }; + f++; + } + } + }); + return pos; +} + +/** Automatic game endings that chess.js can see from the move history. */ +export function detectEnd(g: Chess): GameResult | null { + if (g.isCheckmate()) return { winner: other(g.turn()), reason: 'checkmate' }; + if (g.isStalemate()) return { winner: null, reason: 'stalemate' }; + if (g.isInsufficientMaterial()) return { winner: null, reason: 'insufficient material' }; + if (g.isThreefoldRepetition()) return { winner: null, reason: 'repetition' }; + if (g.isDrawByFiftyMoves()) return { winner: null, reason: '50-move rule' }; + return null; +} + +/** Whether `color` still has enough material to ever deliver mate (decides timeout vs draw). */ +export function canMate(pos: PositionDataType, color: Color): boolean { + let minors = 0; + for (const { pieceType } of Object.values(pos)) { + if (pieceType[0] !== color) continue; + const t = pieceType[1]; + if (t === 'P' || t === 'R' || t === 'Q') return true; + if (t === 'N' || t === 'B') minors++; + } + return minors >= 2; +} + +export const RESULT_SCORE = (r: GameResult | null): string => + !r || r.reason === 'abort' ? '*' : r.winner === 'w' ? '1-0' : r.winner === 'b' ? '0-1' : '1/2-1/2'; + +const REASON_TEXT: Record = { + checkmate: 'by checkmate', + resignation: 'by resignation', + timeout: 'on time', + 'timeout vs insufficient material': 'timeout vs insufficient material', + stalemate: 'by stalemate', + 'insufficient material': 'by insufficient material', + repetition: 'by repetition', + '50-move rule': 'by the 50-move rule', + agreement: 'by agreement', + abort: 'before it began', +}; + +export const reasonText = (r: GameResult) => REASON_TEXT[r.reason]; + +// ---------------------------------------------------------------- material + +const VALUE: Record = { p: 1, n: 3, b: 3, r: 5, q: 9, k: 0 }; +const START_COUNT: Record = { p: 8, n: 2, b: 2, r: 2, q: 1 }; +const CAPTURE_ORDER: PieceSymbol[] = ['p', 'n', 'b', 'r', 'q']; + +/** Pieces each side has taken (chess.com style: missing from the start set) and the material balance. */ +export function material(pos: PositionDataType) { + const count = { w: { p: 0, n: 0, b: 0, r: 0, q: 0 }, b: { p: 0, n: 0, b: 0, r: 0, q: 0 } } as Record< + Color, + Record + >; + let balance = 0; + for (const { pieceType } of Object.values(pos)) { + const color = pieceType[0] as Color; + const t = pieceType[1].toLowerCase(); + if (t === 'k') continue; + count[color][t]++; + balance += (color === 'w' ? 1 : -1) * VALUE[t]; + } + const taken = (victim: Color) => + CAPTURE_ORDER.flatMap((t) => Array(Math.max(0, START_COUNT[t] - count[victim][t])).fill(t) as PieceSymbol[]); + return { takenBy: { w: taken('b'), b: taken('w') }, balance }; +} + +// ---------------------------------------------------------------- premoves + +const KNIGHT = [[1, 2], [2, 1], [2, -1], [1, -2], [-1, -2], [-2, -1], [-2, 1], [-1, 2]]; +const KING = [[1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]]; +const ROOK_DIRS = [[1, 0], [-1, 0], [0, 1], [0, -1]]; +const BISHOP_DIRS = [[1, 1], [1, -1], [-1, 1], [-1, -1]]; + +/** + * Squares a piece could reach on some future turn, by geometry alone — the + * occupancy will have changed by the time a premove fires, so blockers are ignored. + */ +export function premoveDests(pos: PositionDataType, from: string, color: Color): Square[] { + const piece = pos[from]?.pieceType; + if (!piece || piece[0] !== color) return []; + const { f, r } = coords(from); + const out: Square[] = []; + const step = (df: number, dr: number) => onBoard(f + df, r + dr) && out.push(square(f + df, r + dr)); + const slide = (dirs: number[][]) => + dirs.forEach(([df, dr]) => { + for (let i = 1; onBoard(f + df * i, r + dr * i); i++) out.push(square(f + df * i, r + dr * i)); + }); + switch (piece[1]) { + case 'P': { + const dir = color === 'w' ? 1 : -1; + step(0, dir); + if (r === (color === 'w' ? 1 : 6)) step(0, 2 * dir); + step(-1, dir); + step(1, dir); + break; + } + case 'N': + KNIGHT.forEach(([df, dr]) => step(df, dr)); + break; + case 'B': + slide(BISHOP_DIRS); + break; + case 'R': + slide(ROOK_DIRS); + break; + case 'Q': + slide([...ROOK_DIRS, ...BISHOP_DIRS]); + break; + case 'K': { + KING.forEach(([df, dr]) => step(df, dr)); + const home = color === 'w' ? 0 : 7; + const rook = `${color}R`; + if (f === 4 && r === home) { + if (pos[square(7, home)]?.pieceType === rook) out.push(square(6, home)); + if (pos[square(0, home)]?.pieceType === rook) out.push(square(2, home)); + } + break; + } + } + return out; +} + +export const isPromotionSquare = (pos: PositionDataType, from: string, to: string) => { + const piece = pos[from]?.pieceType; + return piece?.[1] === 'P' && (to[1] === '8' || to[1] === '1'); +}; + +/** Board placement after a premove, so queued premoves show where pieces will be. */ +export function applyPremove(pos: PositionDataType, pm: Premove): PositionDataType { + const piece = pos[pm.from]; + if (!piece) return pos; + const next = { ...pos }; + delete next[pm.from]; + const color = piece.pieceType[0]; + const { f: ff, r } = coords(pm.from); + const { f: tf } = coords(pm.to); + if (piece.pieceType[1] === 'K' && Math.abs(tf - ff) === 2) { + const [rookFrom, rookTo] = tf > ff ? [square(7, r), square(5, r)] : [square(0, r), square(3, r)]; + if (next[rookFrom]) { + next[rookTo] = next[rookFrom]; + delete next[rookFrom]; + } + } + next[pm.to] = isPromotionSquare(pos, pm.from, pm.to) + ? { pieceType: `${color}${(pm.promotion ?? 'q').toUpperCase()}` } + : piece; + return next; +} + +/** Board placement with one piece lifted to another square (the pawn waiting on the promotion picker). */ +export function movePiece(pos: PositionDataType, from: string, to: string): PositionDataType { + const next = { ...pos }; + next[to] = pos[from]; + delete next[from]; + return next; +} + +export function kingSquare(pos: PositionDataType, color: Color): string | undefined { + return Object.keys(pos).find((sq) => pos[sq].pieceType === `${color}K`); +} + +// ---------------------------------------------------------------- evaluation + +/** + * The value head outputs an expected score in (-1, 1). Shown as pawns with the + * Leela convention (cp = 90·tan(1.5637·q)), which reads like a familiar engine eval. + */ +export function evalToPawns(v: number): number { + const q = Math.max(-0.995, Math.min(0.995, v)); + return 0.9 * Math.tan(1.5637541897 * q); +} + +export function formatEval(v: number): string { + const p = evalToPawns(v); + const abs = Math.abs(p); + const txt = abs >= 10 ? abs.toFixed(0) : abs.toFixed(1); + return txt === '0.0' ? '0.0' : `${p > 0 ? '+' : '−'}${txt}`; +} + +// ---------------------------------------------------------------- clocks + +export function formatClock(ms: number): string { + const t = Math.max(0, ms); + if (t < 20_000) { + const tenths = Math.floor(t / 100); + return `0:${String(Math.floor(tenths / 10)).padStart(2, '0')}.${tenths % 10}`; + } + const s = Math.ceil(t / 1000); + const h = Math.floor(s / 3600); + const m = Math.floor((s % 3600) / 60); + const sec = String(s % 60).padStart(2, '0'); + return h ? `${h}:${String(m).padStart(2, '0')}:${sec}` : `${m}:${sec}`; +} diff --git a/frontend/app/core/game.ts b/frontend/app/core/game.ts new file mode 100644 index 0000000000000000000000000000000000000000..3d7794831032747d20282b50b08015d67f263719 --- /dev/null +++ b/frontend/app/core/game.ts @@ -0,0 +1,469 @@ +// The game itself, outside React: rules, clocks, the engine round-trip, the +// premove queue and autoplay (the engine playing the player's side too). Async +// work (engine replies, clock flags) mutates this object and publishes an +// immutable snapshot, so the UI never acts on stale state. + +import { Chess, type Color, type Move, type PieceSymbol, type Square } from 'chess.js'; +import { canMate, detectEnd, other, placement, RESULT_SCORE, type GameResult, type Phase, type Ply, type Premove, type TimeControl } from './chess'; +import { playSound, type SoundName } from './sound'; + +export interface ClockState { + w: number; // ms left, as of `since` + b: number; + running: Color | null; + since: number; +} + +/** One searched move as the engine reports it (UCI, from the searched position). */ +export interface SearchNode { + move: string; + visits: number; + prior: number; + /** Mean value for the side playing `move`, in (-1, 1). */ + q: number; + children: SearchNode[]; +} + +/** The engine's account of one search: its budget and its most-visited branches. */ +export interface SearchInfo { + sims: number; + visits: number; + elapsedMs: number; + /** Plies from the searched position: mean simulation, most-visited line, deepest path. */ + depth?: { mean: number; mainLine: number; max: number }; + tree: SearchNode[]; +} + +export interface GameSnapshot { + gameId: number; + phase: Phase; + plies: Ply[]; + playerColor: Color; + timeControl: TimeControl; + clock: ClockState | null; + thinking: boolean; + /** The engine plays the player's side as well. */ + autoplay: boolean; + engineError: boolean; + premoves: Premove[]; + result: GameResult | null; + /** Engine value for White, keyed by the number of plies in the evaluated position. */ + evals: Record; + /** The engine's search, keyed by the number of plies in the searched position. */ + searches: Record; + notice: string | null; + lastDrawOffer: number; +} + +const INITIAL: GameSnapshot = { + gameId: 0, + phase: 'setup', + plies: [], + playerColor: 'w', + timeControl: null, + clock: null, + thinking: false, + autoplay: false, + engineError: false, + premoves: [], + result: null, + evals: {}, + searches: {}, + notice: null, + lastDrawOffer: -Infinity, +}; + +/** Latest known evaluation at or before ply `index`. */ +export function evalAt(evals: Record, index: number): number | null { + let best = -1; + for (const k of Object.keys(evals)) { + const n = Number(k); + if (n <= index && n > best) best = n; + } + return best < 0 ? null : evals[best]; +} + +/** Plies the player must wait between draw offers. */ +export const DRAW_OFFER_GAP = 6; + +/** Breathing room between autoplay moves in untimed games, so each one can be followed. */ +const AUTOPLAY_PAUSE_MS = 450; + +export class GameController { + private game = new Chess(); + private snap: GameSnapshot = INITIAL; + private listeners = new Set<() => void>(); + private request = { id: 0, ctrl: null as AbortController | null }; + private timers: number[] = []; + private autoplayTimer = 0; + private soundEnabled = true; + + constructor(private api: string) {} + + subscribe = (fn: () => void) => { + this.listeners.add(fn); + return () => { + this.listeners.delete(fn); + }; + }; + + getSnapshot = () => this.snap; + + private set(patch: Partial) { + this.snap = { ...this.snap, ...patch }; + this.listeners.forEach((fn) => fn()); + } + + private sound(name: SoundName) { + if (this.soundEnabled) playSound(name); + } + + private get botColor() { + return other(this.snap.playerColor); + } + + dispose() { + this.cancelRequest(); + this.clearTimers(); + } + + // ------------------------------------------------------------ lifecycle + + start(color: Color, timeControl: TimeControl, autoplay = false) { + this.cancelRequest(); + this.clearTimers(); + this.game = new Chess(); + const gameId = this.snap.gameId + 1; + const ms = timeControl ? timeControl.base * 1000 : 0; + this.set({ + ...INITIAL, + gameId, + phase: 'playing', + playerColor: color, + timeControl, + autoplay, + clock: timeControl ? { w: ms, b: ms, running: null, since: Date.now() } : null, + }); + this.sound('start'); + + // Reset the server's session (search tree, repetition history) before its first move. + const id = ++this.request.id; + fetch(`${this.api}/api/new-game`, { method: 'POST' }) + .catch(() => undefined) + .finally(() => { + if (id !== this.request.id || this.snap.gameId !== gameId) return; + if (color === 'b' || this.snap.autoplay) this.requestEngineMove(); + }); + } + + /** Leave the game for the setup screen. */ + reset() { + this.cancelRequest(); + this.clearTimers(); + this.game = new Chess(); + this.set({ ...INITIAL, gameId: this.snap.gameId + 1 }); + } + + setSoundEnabled(on: boolean) { + this.soundEnabled = on; + } + + /** + * Hand the player's side to the engine, or take it back. Taking over while the + * engine is searching for the player's side cancels that search. + */ + setAutoplay(on: boolean) { + const { phase, autoplay, thinking, playerColor } = this.snap; + if (phase !== 'playing' || autoplay === on) return; + const playersTurn = this.game.turn() === playerColor; + this.set({ autoplay: on, premoves: [] }); + if (on && playersTurn && !thinking) this.requestEngineMove(); + if (!on && playersTurn && thinking) this.cancelRequest(); + // Taken over during the pause before the engine's own move: that move still comes. + if (!on && !playersTurn && !thinking) this.requestEngineMove(); + } + + resign() { + if (this.snap.phase !== 'playing') return; + if (!this.snap.plies.some((p) => p.color === this.snap.playerColor)) { + this.finish({ winner: null, reason: 'abort' }); + } else { + this.finish({ winner: this.botColor, reason: 'resignation' }); + } + } + + offerDraw() { + const { phase, plies, evals, lastDrawOffer } = this.snap; + if (phase !== 'playing' || plies.length - lastDrawOffer < DRAW_OFFER_GAP) return; + // The engine takes a draw when it judges itself worse, or when a long game has gone dead level. + const white = evalAt(evals, plies.length); + const mine = white == null ? null : this.botColor === 'w' ? white : -white; + const accept = mine != null && (mine <= -0.3 || (plies.length >= 60 && Math.abs(mine) <= 0.08)); + if (accept) { + this.finish({ winner: null, reason: 'agreement' }); + } else { + this.set({ notice: 'ChessTransformer declined your draw offer.', lastDrawOffer: plies.length }); + this.sound('notify'); + } + } + + /** Undo back to the player's previous turn: their last move and the engine's reply, if any. */ + takeback() { + const { phase, plies, playerColor, clock, evals } = this.snap; + if (phase !== 'playing' || this.snap.autoplay || !plies.some((p) => p.color === playerColor)) return; + this.cancelRequest(); + const n = this.game.turn() === playerColor ? 2 : 1; + for (let i = 0; i < n; i++) this.game.undo(); + const kept = plies.slice(0, plies.length - n); + + let nextClock = clock; + if (clock) { + const t = Date.now(); + nextClock = { ...clock, since: t, running: kept.length >= 2 ? playerColor : null }; + if (clock.running) nextClock[clock.running] = Math.max(0, clock[clock.running] - (t - clock.since)); + } + const keep = (byPly: Record) => + Object.fromEntries(Object.entries(byPly).filter(([k]) => Number(k) <= kept.length)); + this.set({ + plies: kept, + clock: nextClock, + evals: keep(evals), + searches: keep(this.snap.searches), + thinking: false, + engineError: false, + premoves: [], + notice: null, + }); + this.sound('move'); + this.scheduleClock(); + } + + retry() { + const { phase, thinking, autoplay } = this.snap; + if (phase === 'playing' && !thinking && (autoplay || this.game.turn() === this.botColor)) this.requestEngineMove(); + } + + pgn(): string { + const { playerColor, result, timeControl } = this.snap; + const d = new Date(); + const pad = (n: number) => String(n).padStart(2, '0'); + const g = this.game; + g.setHeader('Event', 'Casual game'); + g.setHeader('Site', 'ChessTransformer demo'); + g.setHeader('Date', `${d.getFullYear()}.${pad(d.getMonth() + 1)}.${pad(d.getDate())}`); + g.setHeader('White', playerColor === 'w' ? 'You' : 'ChessTransformer'); + g.setHeader('Black', playerColor === 'b' ? 'You' : 'ChessTransformer'); + g.setHeader('TimeControl', timeControl ? `${timeControl.base}+${timeControl.inc}` : '-'); + g.setHeader('Result', RESULT_SCORE(result)); + if (result) g.setHeader('Termination', result.reason); + return g.pgn(); + } + + // ------------------------------------------------------------ moves + + isPlayerTurn() { + const { phase, playerColor, thinking, autoplay } = this.snap; + return phase === 'playing' && !autoplay && this.game.turn() === playerColor && !thinking; + } + + needsPromotion(from: Square, to: Square) { + return this.game.moves({ square: from, verbose: true }).some((m) => m.to === to && m.isPromotion()); + } + + playMove(from: Square, to: Square, promotion?: PieceSymbol): boolean { + if (!this.isPlayerTurn()) return false; + const legal = this.game.moves({ square: from, verbose: true }).find((m) => m.to === to); + if (!legal) return false; + const move = this.game.move({ from, to, promotion: legal.isPromotion() ? (promotion ?? 'q') : undefined }); + if (!this.commit(move, true)) this.requestEngineMove(); + return true; + } + + queuePremove(pm: Premove) { + if (this.snap.phase !== 'playing' || this.snap.autoplay || this.isPlayerTurn()) return; + this.set({ premoves: [...this.snap.premoves, pm] }); + this.sound('premove'); + } + + clearPremoves() { + if (this.snap.premoves.length) this.set({ premoves: [] }); + } + + private commit(move: Move, byPlayer: boolean): boolean { + const g = this.game; + const ply: Ply = { + san: move.san, + from: move.from, + to: move.to, + color: move.color, + piece: move.piece, + captured: move.captured, + promotion: move.promotion, + castle: move.isKingsideCastle() || move.isQueensideCastle(), + check: g.inCheck(), + fen: g.fen(), + }; + const plies = [...this.snap.plies, ply]; + + // Clocks start once both sides have moved; increment is earned on moves made against the clock. + let clock = this.snap.clock; + const tc = this.snap.timeControl; + if (clock && tc) { + const t = Date.now(); + const next: ClockState = { ...clock, since: t, running: plies.length >= 2 ? other(move.color) : null }; + if (clock.running === move.color) { + next[move.color] = Math.max(0, clock[move.color] - (t - clock.since)) + tc.inc * 1000; + } + clock = next; + } + this.set({ plies, clock, notice: null, engineError: false }); + this.sound( + ply.check ? 'check' : ply.promotion ? 'promote' : ply.castle ? 'castle' : ply.captured ? 'capture' : byPlayer ? 'move' : 'opponent', + ); + + const end = detectEnd(g); + if (end) { + this.finish(end); + return true; + } + this.scheduleClock(); + return false; + } + + private async requestEngineMove() { + const fen = this.game.fen(); + const index = this.snap.plies.length; + const gameId = this.snap.gameId; + this.request.ctrl?.abort(); + const ctrl = new AbortController(); + const id = ++this.request.id; + this.request.ctrl = ctrl; + this.set({ thinking: true, engineError: false }); + + try { + const res = await fetch(`${this.api}/api/move`, { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ fen }), + signal: ctrl.signal, + }); + if (!res.ok) throw new Error(`engine answered ${res.status}`); + const data: { + move: string; + value?: number; + search?: { + sims: number; + visits: number; + elapsed_ms: number; + depth?: { mean: number; max: number; main_line: number }; + tree: SearchNode[]; + }; + } = await res.json(); + if (id !== this.request.id || this.snap.gameId !== gameId || this.snap.phase !== 'playing') return; + this.request.ctrl = null; + + const uci = data.move; + const move = this.game.move({ from: uci.slice(0, 2), to: uci.slice(2, 4), promotion: uci[4] }); + const evals = + typeof data.value === 'number' + ? { ...this.snap.evals, [index]: move.color === 'w' ? data.value : -data.value } + : this.snap.evals; + // Only the Rust backend reports its search tree; the Python one sends none. + const searches = data.search + ? { + ...this.snap.searches, + [index]: { + sims: data.search.sims, + visits: data.search.visits, + elapsedMs: data.search.elapsed_ms, + depth: data.search.depth && { + mean: data.search.depth.mean, + mainLine: data.search.depth.main_line, + max: data.search.depth.max, + }, + tree: data.search.tree, + }, + } + : this.snap.searches; + this.set({ thinking: false, evals, searches }); + if (this.commit(move, move.color === this.snap.playerColor)) return; + if (this.snap.autoplay) this.scheduleAutoplay(); + else this.firePremove(); + } catch { + if (id !== this.request.id) return; + this.request.ctrl = null; + this.set({ thinking: false, engineError: true }); + } + } + + /** Play the first queued premove if it is legal now; an illegal one cancels the whole queue. */ + private firePremove() { + const [pm, ...rest] = this.snap.premoves; + if (!pm) return; + const legal = this.game.moves({ square: pm.from, verbose: true }).some((m) => m.to === pm.to); + this.set({ premoves: legal ? rest : [] }); + if (legal) this.playMove(pm.from, pm.to, pm.promotion); + } + + private scheduleAutoplay() { + window.clearTimeout(this.autoplayTimer); + const gameId = this.snap.gameId; + this.autoplayTimer = window.setTimeout( + () => { + const { autoplay, phase, thinking } = this.snap; + if (autoplay && phase === 'playing' && !thinking && this.snap.gameId === gameId) this.requestEngineMove(); + }, + this.snap.timeControl ? 0 : AUTOPLAY_PAUSE_MS, + ); + } + + private cancelRequest() { + window.clearTimeout(this.autoplayTimer); + this.request.id++; + this.request.ctrl?.abort(); + this.request.ctrl = null; + if (this.snap.thinking) this.set({ thinking: false }); + } + + // ------------------------------------------------------------ clocks & endings + + private clearTimers() { + this.timers.forEach((t) => window.clearTimeout(t)); + this.timers = []; + } + + private scheduleClock() { + this.clearTimers(); + const { clock, phase, playerColor, timeControl } = this.snap; + if (!clock?.running || phase !== 'playing') return; + const side = clock.running; + const left = clock[side] - (Date.now() - clock.since); + this.timers.push(window.setTimeout(() => this.flag(side), Math.max(0, left) + 5)); + if (side === playerColor && timeControl && timeControl.base >= 60 && left > 10_000) { + this.timers.push(window.setTimeout(() => this.sound('lowtime'), left - 10_000)); + } + } + + private flag(side: Color) { + const { clock, phase } = this.snap; + if (!clock || clock.running !== side || phase !== 'playing') return; + if (clock[side] - (Date.now() - clock.since) > 0) return this.scheduleClock(); + const winner = other(side); + const pos = placement(this.game.fen()); + this.finish( + canMate(pos, winner) ? { winner, reason: 'timeout' } : { winner: null, reason: 'timeout vs insufficient material' }, + ); + } + + private finish(result: GameResult) { + this.cancelRequest(); + this.clearTimers(); + let clock = this.snap.clock; + if (clock?.running) { + const t = Date.now(); + clock = { ...clock, [clock.running]: Math.max(0, clock[clock.running] - (t - clock.since)), running: null, since: t }; + } + this.set({ phase: 'over', result, clock, thinking: false, premoves: [] }); + this.timers.push(window.setTimeout(() => this.sound('end'), result.reason === 'abort' ? 0 : 250)); + } +} diff --git a/frontend/app/core/hooks.ts b/frontend/app/core/hooks.ts new file mode 100644 index 0000000000000000000000000000000000000000..602411434ebcd4e44d4bac927caec4370027b3af --- /dev/null +++ b/frontend/app/core/hooks.ts @@ -0,0 +1,29 @@ +import { useEffect, useRef, useState } from 'react'; + +/** State mirrored to localStorage; storage failures (private mode, blocked) fall back to memory. */ +export function useStoredState(key: string, initial: T) { + const [state, setState] = useState(initial); + const loaded = useRef(false); + + useEffect(() => { + try { + const raw = window.localStorage.getItem(key); + if (raw) setState({ ...initial, ...JSON.parse(raw) }); + } catch { + // keep defaults + } + loaded.current = true; + // eslint-disable-next-line react-hooks/exhaustive-deps -- initial is a constant default + }, [key]); + + useEffect(() => { + if (!loaded.current) return; + try { + window.localStorage.setItem(key, JSON.stringify(state)); + } catch { + // not persisted; fine + } + }, [key, state]); + + return [state, setState] as const; +} diff --git a/frontend/app/core/sound.ts b/frontend/app/core/sound.ts new file mode 100644 index 0000000000000000000000000000000000000000..84bff36bb26f66d51819ac1444c6caf53da30ead --- /dev/null +++ b/frontend/app/core/sound.ts @@ -0,0 +1,138 @@ +// Board sounds, synthesised with the Web Audio API so the demo ships no audio +// assets: a filtered-noise "knock" for wood on wood, plus short tones for +// check, game start/end and notices. + +export type SoundName = + | 'move' + | 'opponent' + | 'capture' + | 'castle' + | 'check' + | 'promote' + | 'premove' + | 'illegal' + | 'start' + | 'end' + | 'notify' + | 'lowtime'; + +let ctx: AudioContext | null = null; +let master: GainNode | null = null; +let noise: AudioBuffer | null = null; + +function audio(): AudioContext | null { + if (typeof window === 'undefined') return null; + if (!ctx) { + const AC = + window.AudioContext ?? + (window as unknown as { webkitAudioContext?: typeof AudioContext }).webkitAudioContext; + if (!AC) return null; + ctx = new AC(); + master = ctx.createGain(); + master.gain.value = 0.7; + master.connect(ctx.destination); + } + if (ctx.state === 'suspended') void ctx.resume(); + return ctx; +} + +function noiseBuffer(c: AudioContext): AudioBuffer { + if (!noise) { + noise = c.createBuffer(1, Math.floor(c.sampleRate * 0.25), c.sampleRate); + const data = noise.getChannelData(0); + for (let i = 0; i < data.length; i++) data[i] = Math.random() * 2 - 1; + } + return noise; +} + +function envelope(c: AudioContext, t: number, peak: number, decay: number): GainNode { + const g = c.createGain(); + g.gain.setValueAtTime(0.0001, t); + g.gain.exponentialRampToValueAtTime(peak, t + 0.004); + g.gain.exponentialRampToValueAtTime(0.0001, t + decay); + g.connect(master!); + return g; +} + +/** A piece set down on the board: a bandpassed click with a short low body. */ +function knock(c: AudioContext, t: number, { freq = 1500, body = 190, gain = 0.55, decay = 0.07 } = {}) { + const src = c.createBufferSource(); + src.buffer = noiseBuffer(c); + const bp = c.createBiquadFilter(); + bp.type = 'bandpass'; + bp.frequency.value = freq; + bp.Q.value = 1.6; + src.connect(bp).connect(envelope(c, t, gain, decay)); + src.start(t); + src.stop(t + decay + 0.02); + + const osc = c.createOscillator(); + osc.frequency.setValueAtTime(body, t); + osc.frequency.exponentialRampToValueAtTime(body * 0.55, t + 0.09); + osc.connect(envelope(c, t, gain * 0.7, 0.1)); + osc.start(t); + osc.stop(t + 0.12); +} + +function tone(c: AudioContext, t: number, freq: number, dur: number, gain = 0.16, type: OscillatorType = 'sine') { + const osc = c.createOscillator(); + osc.type = type; + osc.frequency.value = freq; + osc.connect(envelope(c, t, gain, dur)); + osc.start(t); + osc.stop(t + dur + 0.02); +} + +export function playSound(name: SoundName) { + const c = audio(); + if (!c) return; + const t = c.currentTime + 0.01; + switch (name) { + case 'move': + knock(c, t); + break; + case 'opponent': + knock(c, t, { freq: 1150, body: 160 }); + break; + case 'capture': + knock(c, t, { freq: 2300, body: 230, gain: 0.7, decay: 0.05 }); + knock(c, t + 0.03, { freq: 1300, body: 150, gain: 0.5 }); + break; + case 'castle': + knock(c, t); + knock(c, t + 0.1, { freq: 1250, body: 170, gain: 0.45 }); + break; + case 'check': + knock(c, t); + tone(c, t + 0.02, 1046, 0.18, 0.09, 'triangle'); + tone(c, t + 0.02, 1568, 0.14, 0.05, 'triangle'); + break; + case 'promote': + knock(c, t); + tone(c, t + 0.03, 784, 0.12, 0.08); + tone(c, t + 0.1, 1175, 0.18, 0.08); + break; + case 'premove': + knock(c, t, { freq: 2600, body: 260, gain: 0.25, decay: 0.04 }); + break; + case 'illegal': + tone(c, t, 150, 0.14, 0.12, 'square'); + break; + case 'start': + tone(c, t, 523, 0.22, 0.13); + tone(c, t + 0.11, 784, 0.32, 0.13); + break; + case 'end': + tone(c, t, 784, 0.2, 0.13); + tone(c, t + 0.12, 659, 0.2, 0.13); + tone(c, t + 0.24, 523, 0.45, 0.14); + break; + case 'notify': + tone(c, t, 880, 0.2, 0.1); + break; + case 'lowtime': + tone(c, t, 1318, 0.08, 0.1, 'triangle'); + tone(c, t + 0.14, 1318, 0.08, 0.1, 'triangle'); + break; + } +} diff --git a/frontend/app/favicon.ico b/frontend/app/favicon.ico new file mode 100644 index 0000000000000000000000000000000000000000..718d6fea4835ec2d246af9800eddb7ffb276240c Binary files /dev/null and b/frontend/app/favicon.ico differ diff --git a/frontend/app/globals.css b/frontend/app/globals.css new file mode 100644 index 0000000000000000000000000000000000000000..0d2e504d93239c579888fdef60f038f168e026d7 --- /dev/null +++ b/frontend/app/globals.css @@ -0,0 +1,286 @@ +@import "tailwindcss"; + +@theme { + --color-page: #1d2528; + --color-panel: #253035; + --color-raised: #2f3c42; + --color-line: #3c4c53; + --color-fg: #e8eeec; + --color-muted: #9aaba6; + --color-faint: #6b7d80; + --color-jade: #3fbf8f; + --color-sand: #ece5d3; + --color-ink: #1a2224; + --color-coral: #e0614c; + + --font-sans: var(--font-plex), ui-sans-serif, system-ui, sans-serif; + --font-display: var(--font-bricolage), var(--font-plex), ui-sans-serif, sans-serif; +} + +html { + color-scheme: dark; +} + +body { + background: var(--color-page); + color: var(--color-fg); + font-family: var(--font-sans); +} + +:focus-visible { + outline: 2px solid var(--color-jade); + outline-offset: 2px; +} + +/* Pieces are focusable drag handles; a ring on the last-touched piece is noise. */ +#ct-board-board [role="button"]:focus-visible { + outline: none; +} + +/* ------------------------------------------------------------------ layout */ + +/* The board is sized from the viewport: as tall as the window allows on + desktop (minus the two player bars), full width on phones. */ +.app { + min-height: 100dvh; + display: flex; + justify-content: center; + align-items: center; + padding: 1rem; +} + +.play-area { + --bar: 3rem; + --gap: 0.5rem; + --eval-w: 1.5rem; + --panel-w: 25rem; + --board: max( + 18rem, + min( + calc(100dvh - 2rem - 2 * var(--bar) - 2 * var(--gap)), + calc(100vw - 2rem - var(--panel-w) - 1.5rem - var(--eval-w) - 0.5rem), + 58rem + ) + ); + display: flex; + gap: 1.5rem; +} + +.play-area:has([data-eval="off"]) { + --eval-w: 0px; +} + +.board-grid { + display: grid; + grid-template-columns: var(--eval-w) var(--board); + grid-template-rows: var(--bar) var(--board) var(--bar); + grid-template-areas: + ". top" + "eval board" + ". bottom"; + column-gap: 0.5rem; + row-gap: var(--gap); +} + +.board-grid[data-eval="off"] { + column-gap: 0; +} + +.strip-slot { + grid-area: strip; +} +.top-slot { + grid-area: top; +} +.eval-slot { + grid-area: eval; +} +.board-slot { + grid-area: board; +} +.bottom-slot { + grid-area: bottom; +} + +.panel { + width: var(--panel-w); + height: calc(var(--board) + 2 * var(--bar) + 2 * var(--gap)); + display: flex; + flex-direction: column; + border-radius: 0.75rem; + background: var(--color-panel); + overflow: hidden; +} + +@media (max-width: 1023px) { + .app { + align-items: flex-start; + padding: 0.5rem 0.5rem 1.5rem; + } + + .play-area { + --eval-w: 0.75rem; + --board: min(calc(100vw - 1rem - var(--eval-w) - 0.375rem), 40rem); + flex-direction: column; + align-items: center; + gap: 0.75rem; + width: 100%; + } + + .board-grid { + grid-template-rows: auto var(--bar) var(--board) var(--bar); + grid-template-areas: + "strip strip" + ". top" + "eval board" + ". bottom"; + column-gap: 0.375rem; + } + + .panel { + width: calc(var(--board) + var(--eval-w) + 0.375rem); + height: auto; + } +} + +/* ----------------------------------------------------------------- controls */ + +.btn-primary { + border-radius: 0.65rem; + background: var(--color-jade); + color: #0d2a1f; + font-weight: 700; + box-shadow: inset 0 -3px 0 rgb(0 0 0 / 0.2); + transition: background-color 0.15s, transform 0.05s; +} +.btn-primary:hover:not(:disabled) { + background: #52cfa0; +} +.btn-primary:active:not(:disabled) { + transform: translateY(1px); + box-shadow: inset 0 -1px 0 rgb(0 0 0 / 0.2); +} +.btn-primary:disabled { + opacity: 0.45; + cursor: not-allowed; +} + +.btn-secondary { + border-radius: 0.65rem; + background: var(--color-raised); + color: var(--color-fg); + font-weight: 600; + transition: background-color 0.15s; +} +.btn-secondary:hover { + background: var(--color-line); +} + +.choice { + border: 2px solid transparent; + background: var(--color-raised); + color: var(--color-muted); + transition: background-color 0.15s, border-color 0.15s, color 0.15s; +} +.choice:hover { + background: var(--color-line); + color: var(--color-fg); +} +.choice-on, +.choice-on:hover { + border-color: var(--color-jade); + background: color-mix(in srgb, var(--color-jade) 14%, var(--color-raised)); + color: var(--color-fg); +} + +.switch { + appearance: none; + position: relative; + flex-shrink: 0; + width: 2.25rem; + height: 1.25rem; + border-radius: 999px; + background: var(--color-line); + cursor: pointer; + transition: background-color 0.15s; +} +.switch::before { + content: ""; + position: absolute; + top: 2px; + left: 2px; + width: calc(1.25rem - 4px); + height: calc(1.25rem - 4px); + border-radius: 999px; + background: var(--color-fg); + transition: transform 0.15s; +} +.switch:checked { + background: var(--color-jade); +} +.switch:checked::before { + transform: translateX(1rem); +} + +/* --------------------------------------------------------------- details */ + +.captured-dark svg { + filter: drop-shadow(0 0 1px rgb(255 255 255 / 0.4)); +} + +.thinking-dot { + animation: thinking 1s ease-in-out infinite; +} +@keyframes thinking { + 0%, + 80%, + 100% { + opacity: 0.25; + transform: translateY(0); + } + 40% { + opacity: 1; + transform: translateY(-2px); + } +} + +/* The result card waits for the final move's animation to land. */ +.modal-in { + animation: modal-in 0.25s ease-out 0.4s both; +} +.modal-in > [role="dialog"] { + animation: modal-card 0.3s cubic-bezier(0.2, 0.9, 0.3, 1.2) 0.4s both; +} +@keyframes modal-in { + from { + opacity: 0; + visibility: hidden; + } + to { + opacity: 1; + visibility: visible; + } +} +@keyframes modal-card { + from { + transform: translateY(8px) scale(0.96); + } + to { + transform: none; + } +} + +.no-scrollbar { + scrollbar-width: none; +} +.no-scrollbar::-webkit-scrollbar { + display: none; +} + +@media (prefers-reduced-motion: reduce) { + .thinking-dot, + .modal-in, + .modal-in > [role="dialog"] { + animation: none; + } +} diff --git a/frontend/app/layout.tsx b/frontend/app/layout.tsx new file mode 100644 index 0000000000000000000000000000000000000000..9bbffbbb73f0dd9fec758880184c7a3349c4ecf3 --- /dev/null +++ b/frontend/app/layout.tsx @@ -0,0 +1,35 @@ +import type { Metadata, Viewport } from "next"; +import { Bricolage_Grotesque, IBM_Plex_Sans } from "next/font/google"; +import "./globals.css"; + +const display = Bricolage_Grotesque({ + variable: "--font-bricolage", + subsets: ["latin"], +}); + +const sans = IBM_Plex_Sans({ + variable: "--font-plex", + subsets: ["latin"], + weight: ["400", "500", "600", "700"], +}); + +export const metadata: Metadata = { + title: "Play ChessTransformer", + description: "Play chess against ChessTransformer, a transformer engine trained on human games", +}; + +export const viewport: Viewport = { + themeColor: "#1d2528", +}; + +export default function RootLayout({ + children, +}: Readonly<{ + children: React.ReactNode; +}>) { + return ( + + {children} + + ); +} diff --git a/frontend/app/page.tsx b/frontend/app/page.tsx new file mode 100644 index 0000000000000000000000000000000000000000..64aef2d6e9063e0878210bf120b0b68ccc64b429 --- /dev/null +++ b/frontend/app/page.tsx @@ -0,0 +1,5 @@ +import ChessGame from "./components/ChessGame"; + +export default function Home() { + return ; +} diff --git a/frontend/eslint.config.mjs b/frontend/eslint.config.mjs new file mode 100644 index 0000000000000000000000000000000000000000..05e726d1b4201bc8c7716d2b058279676582e8c0 --- /dev/null +++ b/frontend/eslint.config.mjs @@ -0,0 +1,18 @@ +import { defineConfig, globalIgnores } from "eslint/config"; +import nextVitals from "eslint-config-next/core-web-vitals"; +import nextTs from "eslint-config-next/typescript"; + +const eslintConfig = defineConfig([ + ...nextVitals, + ...nextTs, + // Override default ignores of eslint-config-next. + globalIgnores([ + // Default ignores of eslint-config-next: + ".next/**", + "out/**", + "build/**", + "next-env.d.ts", + ]), +]); + +export default eslintConfig; diff --git a/frontend/next.config.ts b/frontend/next.config.ts new file mode 100644 index 0000000000000000000000000000000000000000..6f66ce2a361763166ca935a7a5c64a57fb9ed74d --- /dev/null +++ b/frontend/next.config.ts @@ -0,0 +1,9 @@ +import type { NextConfig } from "next"; + +const nextConfig: NextConfig = { + // "standalone" for the docker-compose frontend container; "export" builds a + // static site that ct-bot serves itself (the Hugging Face Space). + output: process.env.NEXT_OUTPUT === "export" ? "export" : "standalone", +}; + +export default nextConfig; diff --git a/frontend/package-lock.json b/frontend/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..4390529be84d44b22875f1427794fb4789cc9a5c --- /dev/null +++ b/frontend/package-lock.json @@ -0,0 +1,6617 @@ +{ + "name": "frontend", + "version": "0.1.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "frontend", + "version": "0.1.0", + "dependencies": { + "chess.js": "^1.4.0", + "next": "16.1.1", + "react": "19.2.3", + "react-chessboard": "^5.8.6", + "react-dom": "19.2.3" + }, + "devDependencies": { + "@tailwindcss/postcss": "^4", + "@types/node": "^20", + "@types/react": "^19", + "@types/react-dom": "^19", + "eslint": "^9", + "eslint-config-next": "16.1.1", + "tailwindcss": "^4", + "typescript": "^5" + } + }, + "node_modules/@alloc/quick-lru": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/@alloc/quick-lru/-/quick-lru-5.2.0.tgz", + "integrity": "sha512-UrcABB+4bUrFABwbluTIBErXwvbsU/V7TZWfmbgJfbkwiBuziS9gxdODUyuiecfdGQ85jglMW6juS3+z5TsKLw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.27.1.tgz", + "integrity": "sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.27.1", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.28.5.tgz", + "integrity": "sha512-6uFXyCayocRbqhZOB+6XcuZbkMNimwfVGFji8CTZnCzOHVGvDqzvitu1re2AU5LROliz7eQPhB8CpAMvnx9EjA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.28.5.tgz", + "integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.27.1", + "@babel/generator": "^7.28.5", + "@babel/helper-compilation-targets": "^7.27.2", + "@babel/helper-module-transforms": "^7.28.3", + "@babel/helpers": "^7.28.4", + "@babel/parser": "^7.28.5", + "@babel/template": "^7.27.2", + "@babel/traverse": "^7.28.5", + "@babel/types": "^7.28.5", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.28.5.tgz", + "integrity": "sha512-3EwLFhZ38J4VyIP6WNtt2kUdW9dokXA9Cr4IVIFHuCpZ3H8/YFOl5JjZHisrn1fATPBmKKqXzDFvh9fUwHz6CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.28.5", + "@babel/types": "^7.28.5", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.27.2", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.27.2.tgz", + "integrity": "sha512-2+1thGUUWWjLTYTHZWK1n8Yga0ijBz1XAhUXcKy81rd5g6yh7hGqMp45v7cadSbEHc9G3OTv45SyneRN3ps4DQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.27.2", + "@babel/helper-validator-option": "^7.27.1", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz", + "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.27.1.tgz", + "integrity": "sha512-0gSFWUPNXNopqtIPQvlD5WgXYI5GY2kP2cCvoT8kczjbfcfuIljTbcWrulD1CIPIX2gt1wghbDy08yE1p+/r3w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.27.1", + "@babel/types": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.28.3", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.3.tgz", + "integrity": "sha512-gytXUbs8k2sXS9PnQptz5o0QnpLL51SwASIORY6XaBKF88nsOT0Zw9szLqlSGQDP/4TljBAD5y98p2U1fqkdsw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.27.1", + "@babel/helper-validator-identifier": "^7.27.1", + "@babel/traverse": "^7.28.3" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.27.1.tgz", + "integrity": "sha512-YvjJow9FxbhFFKDSuFnVCe2WxXk1zWc22fFePVNEaWJEu8IrZVlda6N0uHwzZrUM1il7NC9Mlp4MaJYbYd9JSg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.28.4", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.28.4.tgz", + "integrity": "sha512-HFN59MmQXGHVyYadKLVumYsA9dBFun/ldYxipEjzA4196jpLZd8UjEEBLkbEkvfYreDqJhZxYAWFPtrfhNpj4w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.27.2", + "@babel/types": "^7.28.4" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.28.5.tgz", + "integrity": "sha512-KKBU1VGYR7ORr3At5HAtUQ+TV3SzRCXmA/8OdDZiLDBIZxVyzXuztPjfLd3BV1PRAQGCMWWSHYhL0F8d5uHBDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.28.5" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/template": { + "version": "7.27.2", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.27.2.tgz", + "integrity": "sha512-LPDZ85aEJyYSd18/DkjNh4/y1ntkE5KwUHWTiqgRxruuZL2F1yuHligVHLvcHY2vMHXttKFpJn6LwfI7cw7ODw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.27.1", + "@babel/parser": "^7.27.2", + "@babel/types": "^7.27.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.28.5.tgz", + "integrity": "sha512-TCCj4t55U90khlYkVV/0TfkJkAkUg3jZFA3Neb7unZT8CPok7iiRfaX0F+WnqWqt7OxhOn0uBKXCw4lbL8W0aQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.27.1", + "@babel/generator": "^7.28.5", + "@babel/helper-globals": "^7.28.0", + "@babel/parser": "^7.28.5", + "@babel/template": "^7.27.2", + "@babel/types": "^7.28.5", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.28.5.tgz", + "integrity": "sha512-qQ5m48eI/MFLQ5PxQj4PFaprjyCTLI37ElWMmNs0K8Lk3dVeOdNpB3ks8jc7yM5CDmVC73eMVk/trk3fgmrUpA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@dnd-kit/accessibility": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz", + "integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/core": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz", + "integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==", + "license": "MIT", + "dependencies": { + "@dnd-kit/accessibility": "^3.1.1", + "@dnd-kit/utilities": "^3.2.2", + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/modifiers": { + "version": "9.0.0", + "resolved": "https://registry.npmjs.org/@dnd-kit/modifiers/-/modifiers-9.0.0.tgz", + "integrity": "sha512-ybiLc66qRGuZoC20wdSSG6pDXFikui/dCNGthxv4Ndy8ylErY0N3KVxY2bgo7AWwIbxDmXDg3ylAFmnrjcbVvw==", + "license": "MIT", + "dependencies": { + "@dnd-kit/utilities": "^3.2.2", + "tslib": "^2.0.0" + }, + "peerDependencies": { + "@dnd-kit/core": "^6.3.0", + "react": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/utilities": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz", + "integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0" + } + }, + "node_modules/@emnapi/core": { + "version": "1.7.1", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.7.1.tgz", + "integrity": "sha512-o1uhUASyo921r2XtHYOHy7gdkGLge8ghBEQHMWmyJFoXlpU58kIrhhN3w26lpQb6dspetweapMn2CSNwQ8I4wg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.1.0", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.7.1", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.7.1.tgz", + "integrity": "sha512-PVtJr5CmLwYAU9PZDMITZoR5iAOShYREoR45EyyLrbntV50mdePTgUn4AmOw90Ifcj+x2kRjdzr1HP3RrNiHGA==", + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.1.0.tgz", + "integrity": "sha512-WI0DdZ8xFSbgMjR1sFsKABJ/C5OnRrjT06JXbZKexJGrDuPTzZdDYfFlsgcCXCyf+suG5QU2e/y1Wo2V/OapLQ==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.9.0", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.0.tgz", + "integrity": "sha512-ayVFHdtZ+hsq1t2Dy24wCmGXGe4q9Gu3smhLYALJrr473ZH27MsnSL+LKUlimp4BWJqMDMLmPpx/Q9R3OAlL4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.21.1", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.21.1.tgz", + "integrity": "sha512-aw1gNayWpdI/jSYVgzN5pL0cfzU02GT3NBpeT/DXbx1/1x7ZKxFPd9bwrzygx/qiwIQiJ1sw/zD8qY/kRvlGHA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^2.1.7", + "debug": "^4.3.1", + "minimatch": "^3.1.2" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.4.2.tgz", + "integrity": "sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/core": { + "version": "0.17.0", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-0.17.0.tgz", + "integrity": "sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/eslintrc": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/@eslint/eslintrc/-/eslintrc-3.3.3.tgz", + "integrity": "sha512-Kr+LPIUVKz2qkx1HAMH8q1q6azbqBAsXJUxBl/ODDuVPX45Z9DfwB8tPjTi6nNZ8BuM3nbJxC5zCAg5elnBUTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ajv": "^6.12.4", + "debug": "^4.3.2", + "espree": "^10.0.1", + "globals": "^14.0.0", + "ignore": "^5.2.0", + "import-fresh": "^3.2.1", + "js-yaml": "^4.1.1", + "minimatch": "^3.1.2", + "strip-json-comments": "^3.1.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint/js": { + "version": "9.39.2", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-9.39.2.tgz", + "integrity": "sha512-q1mjIoW1VX4IvSocvM/vbTiveKC4k9eLrajNEuSsmjymSDEbpGddtpfOoN7YGAqBK3NG+uqo8ia4PDTt8buCYA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + } + }, + "node_modules/@eslint/object-schema": { + "version": "2.1.7", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-2.1.7.tgz", + "integrity": "sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz", + "integrity": "sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^0.17.0", + "levn": "^0.4.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.1", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.1.tgz", + "integrity": "sha512-5DyQ4+1JEUzejeK1JGICcideyfUbGixgS9jNgex5nqkW+cY7WZhxBigmieN5Qnw9ZosSNVC9KQKyb+GUaGyKUA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.7", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.7.tgz", + "integrity": "sha512-/zUx+yOsIrG4Y43Eh2peDeKCxlRt/gET6aHfaKpuq267qXdYDFViVHfMaLyygZOnl0kGWxFIgsBy8QFuTLUXEQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.1", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@img/colour": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/@img/colour/-/colour-1.0.0.tgz", + "integrity": "sha512-A5P/LfWGFSl6nsckYtjw9da+19jB8hkJ6ACTGcDfEJ0aE+l2n2El7dsVM7UVHZQ9s2lmYMWlrS21YLy2IR1LUw==", + "license": "MIT", + "optional": true, + "engines": { + "node": ">=18" + } + }, + "node_modules/@img/sharp-darwin-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-arm64/-/sharp-darwin-arm64-0.34.5.tgz", + "integrity": "sha512-imtQ3WMJXbMY4fxb/Ndp6HBTNVtWCUI0WdobyheGf5+ad6xX8VIDO8u2xE4qc/fr08CKG/7dDseFtn6M6g/r3w==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-darwin-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-darwin-x64/-/sharp-darwin-x64-0.34.5.tgz", + "integrity": "sha512-YNEFAF/4KQ/PeW0N+r+aVVsoIY0/qxxikF2SWdp+NRkmMB7y9LBZAVqQ4yhGCm/H3H270OSykqmQMKLBhBJDEw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-darwin-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-libvips-darwin-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-arm64/-/sharp-libvips-darwin-arm64-1.2.4.tgz", + "integrity": "sha512-zqjjo7RatFfFoP0MkQ51jfuFZBnVE2pRiaydKJ1G/rHZvnsrHAOcQALIi9sA5co5xenQdTugCvtb1cuf78Vf4g==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-darwin-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-darwin-x64/-/sharp-libvips-darwin-x64-1.2.4.tgz", + "integrity": "sha512-1IOd5xfVhlGwX+zXv2N93k0yMONvUlANylbJw1eTah8K/Jtpi15KC+WSiaX/nBmbm2HxRM1gZ0nSdjSsrZbGKg==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "darwin" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm/-/sharp-libvips-linux-arm-1.2.4.tgz", + "integrity": "sha512-bFI7xcKFELdiNCVov8e44Ia4u2byA+l3XtsAj+Q8tfCwO6BQ8iDojYdvoPMqsKDkuoOo+X6HZA0s0q11ANMQ8A==", + "cpu": [ + "arm" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-arm64/-/sharp-libvips-linux-arm64-1.2.4.tgz", + "integrity": "sha512-excjX8DfsIcJ10x1Kzr4RcWe1edC9PquDRRPx3YVCvQv+U5p7Yin2s32ftzikXojb1PIFc/9Mt28/y+iRklkrw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-ppc64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-ppc64/-/sharp-libvips-linux-ppc64-1.2.4.tgz", + "integrity": "sha512-FMuvGijLDYG6lW+b/UvyilUWu5Ayu+3r2d1S8notiGCIyYU/76eig1UfMmkZ7vwgOrzKzlQbFSuQfgm7GYUPpA==", + "cpu": [ + "ppc64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-riscv64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-riscv64/-/sharp-libvips-linux-riscv64-1.2.4.tgz", + "integrity": "sha512-oVDbcR4zUC0ce82teubSm+x6ETixtKZBh/qbREIOcI3cULzDyb18Sr/Wcyx7NRQeQzOiHTNbZFF1UwPS2scyGA==", + "cpu": [ + "riscv64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-s390x": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-s390x/-/sharp-libvips-linux-s390x-1.2.4.tgz", + "integrity": "sha512-qmp9VrzgPgMoGZyPvrQHqk02uyjA0/QrTO26Tqk6l4ZV0MPWIW6LTkqOIov+J1yEu7MbFQaDpwdwJKhbJvuRxQ==", + "cpu": [ + "s390x" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linux-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linux-x64/-/sharp-libvips-linux-x64-1.2.4.tgz", + "integrity": "sha512-tJxiiLsmHc9Ax1bz3oaOYBURTXGIRDODBqhveVHonrHJ9/+k89qbLl0bcJns+e4t4rvaNBxaEZsFtSfAdquPrw==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-arm64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-arm64/-/sharp-libvips-linuxmusl-arm64-1.2.4.tgz", + "integrity": "sha512-FVQHuwx1IIuNow9QAbYUzJ+En8KcVm9Lk5+uGUQJHaZmMECZmOlix9HnH7n1TRkXMS0pGxIJokIVB9SuqZGGXw==", + "cpu": [ + "arm64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-libvips-linuxmusl-x64": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/@img/sharp-libvips-linuxmusl-x64/-/sharp-libvips-linuxmusl-x64-1.2.4.tgz", + "integrity": "sha512-+LpyBk7L44ZIXwz/VYfglaX/okxezESc6UxDSoyo2Ks6Jxc4Y7sGjpgU9s4PMgqgjj1gZCylTieNamqA1MF7Dg==", + "cpu": [ + "x64" + ], + "license": "LGPL-3.0-or-later", + "optional": true, + "os": [ + "linux" + ], + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-linux-arm": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm/-/sharp-linux-arm-0.34.5.tgz", + "integrity": "sha512-9dLqsvwtg1uuXBGZKsxem9595+ujv0sJ6Vi8wcTANSFpwV/GONat5eCkzQo/1O6zRIkh0m/8+5BjrRr7jDUSZw==", + "cpu": [ + "arm" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-arm64/-/sharp-linux-arm64-0.34.5.tgz", + "integrity": "sha512-bKQzaJRY/bkPOXyKx5EVup7qkaojECG6NLYswgktOZjaXecSAeCWiZwwiFf3/Y+O1HrauiE3FVsGxFg8c24rZg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-ppc64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-ppc64/-/sharp-linux-ppc64-0.34.5.tgz", + "integrity": "sha512-7zznwNaqW6YtsfrGGDA6BRkISKAAE1Jo0QdpNYXNMHu2+0dTrPflTLNkpc8l7MUP5M16ZJcUvysVWWrMefZquA==", + "cpu": [ + "ppc64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-ppc64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-riscv64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-riscv64/-/sharp-linux-riscv64-0.34.5.tgz", + "integrity": "sha512-51gJuLPTKa7piYPaVs8GmByo7/U7/7TZOq+cnXJIHZKavIRHAP77e3N2HEl3dgiqdD/w0yUfiJnII77PuDDFdw==", + "cpu": [ + "riscv64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-riscv64": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-s390x": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-s390x/-/sharp-linux-s390x-0.34.5.tgz", + "integrity": "sha512-nQtCk0PdKfho3eC5MrbQoigJ2gd1CgddUMkabUj+rBevs8tZ2cULOx46E7oyX+04WGfABgIwmMC0VqieTiR4jg==", + "cpu": [ + "s390x" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-s390x": "1.2.4" + } + }, + "node_modules/@img/sharp-linux-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linux-x64/-/sharp-linux-x64-0.34.5.tgz", + "integrity": "sha512-MEzd8HPKxVxVenwAa+JRPwEC7QFjoPWuS5NZnBt6B3pu7EG2Ge0id1oLHZpPJdn3OQK+BQDiw9zStiHBTJQQQQ==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linux-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-arm64/-/sharp-linuxmusl-arm64-0.34.5.tgz", + "integrity": "sha512-fprJR6GtRsMt6Kyfq44IsChVZeGN97gTD331weR1ex1c1rypDEABN6Tm2xa1wE6lYb5DdEnk03NZPqA7Id21yg==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4" + } + }, + "node_modules/@img/sharp-linuxmusl-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-linuxmusl-x64/-/sharp-linuxmusl-x64-0.34.5.tgz", + "integrity": "sha512-Jg8wNT1MUzIvhBFxViqrEhWDGzqymo3sV7z7ZsaWbZNDLXRJZoRGrjulp60YYtV4wfY8VIKcWidjojlLcWrd8Q==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-libvips-linuxmusl-x64": "1.2.4" + } + }, + "node_modules/@img/sharp-wasm32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-wasm32/-/sharp-wasm32-0.34.5.tgz", + "integrity": "sha512-OdWTEiVkY2PHwqkbBI8frFxQQFekHaSSkUIJkwzclWZe64O1X4UlUjqqqLaPbUpMOQk6FBu/HtlGXNblIs0huw==", + "cpu": [ + "wasm32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later AND MIT", + "optional": true, + "dependencies": { + "@emnapi/runtime": "^1.7.0" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-arm64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-arm64/-/sharp-win32-arm64-0.34.5.tgz", + "integrity": "sha512-WQ3AgWCWYSb2yt+IG8mnC6Jdk9Whs7O0gxphblsLvdhSpSTtmu69ZG1Gkb6NuvxsNACwiPV6cNSZNzt0KPsw7g==", + "cpu": [ + "arm64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-ia32": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-ia32/-/sharp-win32-ia32-0.34.5.tgz", + "integrity": "sha512-FV9m/7NmeCmSHDD5j4+4pNI8Cp3aW+JvLoXcTUo0IqyjSfAZJ8dIUmijx1qaJsIiU+Hosw6xM5KijAWRJCSgNg==", + "cpu": [ + "ia32" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@img/sharp-win32-x64": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/@img/sharp-win32-x64/-/sharp-win32-x64-0.34.5.tgz", + "integrity": "sha512-+29YMsqY2/9eFEiW93eqWnuLcWcufowXewwSNIT6UwZdUUCrM3oFjMWH/Z6/TMmb4hlFenmfAVbpWeup2jryCw==", + "cpu": [ + "x64" + ], + "license": "Apache-2.0 AND LGPL-3.0-or-later", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "0.2.12", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-0.2.12.tgz", + "integrity": "sha512-ZVWUcfwY4E/yPitQJl481FjFo3K22D6qF0DuFH6Y/nbnE11GY5uguDxZMGXPQ8WQ0128MXQD7TnfHyK4oWoIJQ==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.4.3", + "@emnapi/runtime": "^1.4.3", + "@tybys/wasm-util": "^0.10.0" + } + }, + "node_modules/@next/env": { + "version": "16.1.1", + "resolved": "https://registry.npmjs.org/@next/env/-/env-16.1.1.tgz", + "integrity": "sha512-3oxyM97Sr2PqiVyMyrZUtrtM3jqqFxOQJVuKclDsgj/L728iZt/GyslkN4NwarledZATCenbk4Offjk1hQmaAA==", + "license": "MIT" + }, + "node_modules/@next/eslint-plugin-next": { + "version": "16.1.1", + "resolved": "https://registry.npmjs.org/@next/eslint-plugin-next/-/eslint-plugin-next-16.1.1.tgz", + "integrity": "sha512-Ovb/6TuLKbE1UiPcg0p39Ke3puyTCIKN9hGbNItmpQsp+WX3qrjO3WaMVSi6JHr9X1NrmthqIguVHodMJbh/dw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-glob": "3.3.1" + } + }, + "node_modules/@next/swc-darwin-arm64": { + "version": "16.1.1", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-16.1.1.tgz", + "integrity": "sha512-JS3m42ifsVSJjSTzh27nW+Igfha3NdBOFScr9C80hHGrWx55pTrVL23RJbqir7k7/15SKlrLHhh/MQzqBBYrQA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-darwin-x64": { + "version": "16.1.1", + "resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-16.1.1.tgz", + "integrity": "sha512-hbyKtrDGUkgkyQi1m1IyD3q4I/3m9ngr+V93z4oKHrPcmxwNL5iMWORvLSGAf2YujL+6HxgVvZuCYZfLfb4bGw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-arm64-gnu": { + "version": "16.1.1", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-16.1.1.tgz", + "integrity": "sha512-/fvHet+EYckFvRLQ0jPHJCUI5/B56+2DpI1xDSvi80r/3Ez+Eaa2Yq4tJcRTaB1kqj/HrYKn8Yplm9bNoMJpwQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-arm64-musl": { + "version": "16.1.1", + "resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-16.1.1.tgz", + "integrity": "sha512-MFHrgL4TXNQbBPzkKKur4Fb5ICEJa87HM7fczFs2+HWblM7mMLdco3dvyTI+QmLBU9xgns/EeeINSZD6Ar+oLg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-x64-gnu": { + "version": "16.1.1", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-16.1.1.tgz", + "integrity": "sha512-20bYDfgOQAPUkkKBnyP9PTuHiJGM7HzNBbuqmD0jiFVZ0aOldz+VnJhbxzjcSabYsnNjMPsE0cyzEudpYxsrUQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-linux-x64-musl": { + "version": "16.1.1", + "resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-16.1.1.tgz", + "integrity": "sha512-9pRbK3M4asAHQRkwaXwu601oPZHghuSC8IXNENgbBSyImHv/zY4K5udBusgdHkvJ/Tcr96jJwQYOll0qU8+fPA==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-win32-arm64-msvc": { + "version": "16.1.1", + "resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-16.1.1.tgz", + "integrity": "sha512-bdfQkggaLgnmYrFkSQfsHfOhk/mCYmjnrbRCGgkMcoOBZ4n+TRRSLmT/CU5SATzlBJ9TpioUyBW/vWFXTqQRiA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@next/swc-win32-x64-msvc": { + "version": "16.1.1", + "resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-16.1.1.tgz", + "integrity": "sha512-Ncwbw2WJ57Al5OX0k4chM68DKhEPlrXBaSXDCi2kPi5f4d8b3ejr3RRJGfKBLrn2YJL5ezNS7w2TZLHSti8CMw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@nodelib/fs.scandir": { + "version": "2.1.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.scandir/-/fs.scandir-2.1.5.tgz", + "integrity": "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "2.0.5", + "run-parallel": "^1.1.9" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.stat": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/@nodelib/fs.stat/-/fs.stat-2.0.5.tgz", + "integrity": "sha512-RkhPPp2zrqDAQA/2jNhnztcPAlv64XdhIp7a7454A5ovI7Bukxgt7MX7udwAu3zg1DcpPU0rz3VV1SeaqvY4+A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nodelib/fs.walk": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/@nodelib/fs.walk/-/fs.walk-1.2.8.tgz", + "integrity": "sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.scandir": "2.1.5", + "fastq": "^1.6.0" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/@nolyfill/is-core-module": { + "version": "1.0.39", + "resolved": "https://registry.npmjs.org/@nolyfill/is-core-module/-/is-core-module-1.0.39.tgz", + "integrity": "sha512-nn5ozdjYQpUCZlWGuxcJY/KpxkWQs4DcbMCmKojjyrYDEAGy4Ce19NN4v5MduafTwJlbKc99UA8YhSVqq9yPZA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.4.0" + } + }, + "node_modules/@rtsao/scc": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@rtsao/scc/-/scc-1.1.0.tgz", + "integrity": "sha512-zt6OdqaDoOnJ1ZYsCYGt9YmWzDXl4vQdKTyJev62gFhRGKdx7mcT54V9KIjg+d2wi9EXsPvAPKe7i7WjfVWB8g==", + "dev": true, + "license": "MIT" + }, + "node_modules/@swc/helpers": { + "version": "0.5.15", + "resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.15.tgz", + "integrity": "sha512-JQ5TuMi45Owi4/BIMAJBoSQoOJu12oOk/gADqlcUL9JEdHB8vyjUSsxqeNXnmXHjYKMi2WcYtezGEEhqUI/E2g==", + "license": "Apache-2.0", + "dependencies": { + "tslib": "^2.8.0" + } + }, + "node_modules/@tailwindcss/node": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.1.18.tgz", + "integrity": "sha512-DoR7U1P7iYhw16qJ49fgXUlry1t4CpXeErJHnQ44JgTSKMaZUdf17cfn5mHchfJ4KRBZRFA/Coo+MUF5+gOaCQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.4", + "enhanced-resolve": "^5.18.3", + "jiti": "^2.6.1", + "lightningcss": "1.30.2", + "magic-string": "^0.30.21", + "source-map-js": "^1.2.1", + "tailwindcss": "4.1.18" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.1.18.tgz", + "integrity": "sha512-EgCR5tTS5bUSKQgzeMClT6iCY3ToqE1y+ZB0AKldj809QXk1Y+3jB0upOYZrn9aGIzPtUsP7sX4QQ4XtjBB95A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 10" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.1.18", + "@tailwindcss/oxide-darwin-arm64": "4.1.18", + "@tailwindcss/oxide-darwin-x64": "4.1.18", + "@tailwindcss/oxide-freebsd-x64": "4.1.18", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.1.18", + "@tailwindcss/oxide-linux-arm64-gnu": "4.1.18", + "@tailwindcss/oxide-linux-arm64-musl": "4.1.18", + "@tailwindcss/oxide-linux-x64-gnu": "4.1.18", + "@tailwindcss/oxide-linux-x64-musl": "4.1.18", + "@tailwindcss/oxide-wasm32-wasi": "4.1.18", + "@tailwindcss/oxide-win32-arm64-msvc": "4.1.18", + "@tailwindcss/oxide-win32-x64-msvc": "4.1.18" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.1.18.tgz", + "integrity": "sha512-dJHz7+Ugr9U/diKJA0W6N/6/cjI+ZTAoxPf9Iz9BFRF2GzEX8IvXxFIi/dZBloVJX/MZGvRuFA9rqwdiIEZQ0Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.1.18.tgz", + "integrity": "sha512-Gc2q4Qhs660bhjyBSKgq6BYvwDz4G+BuyJ5H1xfhmDR3D8HnHCmT/BSkvSL0vQLy/nkMLY20PQ2OoYMO15Jd0A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.1.18.tgz", + "integrity": "sha512-FL5oxr2xQsFrc3X9o1fjHKBYBMD1QZNyc1Xzw/h5Qu4XnEBi3dZn96HcHm41c/euGV+GRiXFfh2hUCyKi/e+yw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.1.18.tgz", + "integrity": "sha512-Fj+RHgu5bDodmV1dM9yAxlfJwkkWvLiRjbhuO2LEtwtlYlBgiAT4x/j5wQr1tC3SANAgD+0YcmWVrj8R9trVMA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.1.18.tgz", + "integrity": "sha512-Fp+Wzk/Ws4dZn+LV2Nqx3IilnhH51YZoRaYHQsVq3RQvEl+71VGKFpkfHrLM/Li+kt5c0DJe/bHXK1eHgDmdiA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.1.18.tgz", + "integrity": "sha512-S0n3jboLysNbh55Vrt7pk9wgpyTTPD0fdQeh7wQfMqLPM/Hrxi+dVsLsPrycQjGKEQk85Kgbx+6+QnYNiHalnw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.1.18.tgz", + "integrity": "sha512-1px92582HkPQlaaCkdRcio71p8bc8i/ap5807tPRDK/uw953cauQBT8c5tVGkOwrHMfc2Yh6UuxaH4vtTjGvHg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.1.18.tgz", + "integrity": "sha512-v3gyT0ivkfBLoZGF9LyHmts0Isc8jHZyVcbzio6Wpzifg/+5ZJpDiRiUhDLkcr7f/r38SWNe7ucxmGW3j3Kb/g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.1.18.tgz", + "integrity": "sha512-bhJ2y2OQNlcRwwgOAGMY0xTFStt4/wyU6pvI6LSuZpRgKQwxTec0/3Scu91O8ir7qCR3AuepQKLU/kX99FouqQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.1.18.tgz", + "integrity": "sha512-LffYTvPjODiP6PT16oNeUQJzNVyJl1cjIebq/rWWBF+3eDst5JGEFSc5cWxyRCJ0Mxl+KyIkqRxk1XPEs9x8TA==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1", + "@emnapi/wasi-threads": "^1.1.0", + "@napi-rs/wasm-runtime": "^1.1.0", + "@tybys/wasm-util": "^0.10.1", + "tslib": "^2.4.0" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.1.18.tgz", + "integrity": "sha512-HjSA7mr9HmC8fu6bdsZvZ+dhjyGCLdotjVOgLA2vEqxEBZaQo9YTX4kwgEvPCpRh8o4uWc4J/wEoFzhEmjvPbA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.1.18.tgz", + "integrity": "sha512-bJWbyYpUlqamC8dpR7pfjA0I7vdF6t5VpUGMWRkXVE3AXgIZjYUYAK7II1GNaxR8J1SSrSrppRar8G++JekE3Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10" + } + }, + "node_modules/@tailwindcss/postcss": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/@tailwindcss/postcss/-/postcss-4.1.18.tgz", + "integrity": "sha512-Ce0GFnzAOuPyfV5SxjXGn0CubwGcuDB0zcdaPuCSzAa/2vII24JTkH+I6jcbXLb1ctjZMZZI6OjDaLPJQL1S0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@alloc/quick-lru": "^5.2.0", + "@tailwindcss/node": "4.1.18", + "@tailwindcss/oxide": "4.1.18", + "postcss": "^8.4.41", + "tailwindcss": "4.1.18" + } + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.1", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.1.tgz", + "integrity": "sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/estree": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.8.tgz", + "integrity": "sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json5": { + "version": "0.0.29", + "resolved": "https://registry.npmjs.org/@types/json5/-/json5-0.0.29.tgz", + "integrity": "sha512-dRLjCWHYg4oaA77cxO64oO+7JwCwnIzkZPdrrC71jQmQtlhM556pwKo5bUzqvZndkVbeFLIIi+9TC40JNF5hNQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "20.19.27", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.19.27.tgz", + "integrity": "sha512-N2clP5pJhB2YnZJ3PIHFk5RkygRX5WO/5f0WC08tp0wd+sv0rsJk3MqWn3CbNmT2J505a5336jaQj4ph1AdMug==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~6.21.0" + } + }, + "node_modules/@types/react": { + "version": "19.2.7", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.7.tgz", + "integrity": "sha512-MWtvHrGZLFttgeEj28VXHxpmwYbor/ATPYbBfSFZEIRK0ecCFLl2Qo55z52Hss+UV9CRN7trSeq1zbgx7YDWWg==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.2.3", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz", + "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.2.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.50.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.50.1.tgz", + "integrity": "sha512-PKhLGDq3JAg0Jk/aK890knnqduuI/Qj+udH7wCf0217IGi4gt+acgCyPVe79qoT+qKUvHMDQkwJeKW9fwl8Cyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.10.0", + "@typescript-eslint/scope-manager": "8.50.1", + "@typescript-eslint/type-utils": "8.50.1", + "@typescript-eslint/utils": "8.50.1", + "@typescript-eslint/visitor-keys": "8.50.1", + "ignore": "^7.0.0", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.1.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.50.1", + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", + "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.50.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.50.1.tgz", + "integrity": "sha512-hM5faZwg7aVNa819m/5r7D0h0c9yC4DUlWAOvHAtISdFTc8xB86VmX5Xqabrama3wIPJ/q9RbGS1worb6JfnMg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.50.1", + "@typescript-eslint/types": "8.50.1", + "@typescript-eslint/typescript-estree": "8.50.1", + "@typescript-eslint/visitor-keys": "8.50.1", + "debug": "^4.3.4" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.50.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.50.1.tgz", + "integrity": "sha512-E1ur1MCVf+YiP89+o4Les/oBAVzmSbeRB0MQLfSlYtbWU17HPxZ6Bhs5iYmKZRALvEuBoXIZMOIRRc/P++Ortg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.50.1", + "@typescript-eslint/types": "^8.50.1", + "debug": "^4.3.4" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.50.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.50.1.tgz", + "integrity": "sha512-mfRx06Myt3T4vuoHaKi8ZWNTPdzKPNBhiblze5N50//TSHOAQQevl/aolqA/BcqqbJ88GUnLqjjcBc8EWdBcVw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.50.1", + "@typescript-eslint/visitor-keys": "8.50.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.50.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.50.1.tgz", + "integrity": "sha512-ooHmotT/lCWLXi55G4mvaUF60aJa012QzvLK0Y+Mp4WdSt17QhMhWOaBWeGTFVkb2gDgBe19Cxy1elPXylslDw==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.50.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.50.1.tgz", + "integrity": "sha512-7J3bf022QZE42tYMO6SL+6lTPKFk/WphhRPe9Tw/el+cEwzLz1Jjz2PX3GtGQVxooLDKeMVmMt7fWpYRdG5Etg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.50.1", + "@typescript-eslint/typescript-estree": "8.50.1", + "@typescript-eslint/utils": "8.50.1", + "debug": "^4.3.4", + "ts-api-utils": "^2.1.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.50.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.50.1.tgz", + "integrity": "sha512-v5lFIS2feTkNyMhd7AucE/9j/4V9v5iIbpVRncjk/K0sQ6Sb+Np9fgYS/63n6nwqahHQvbmujeBL7mp07Q9mlA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.50.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.50.1.tgz", + "integrity": "sha512-woHPdW+0gj53aM+cxchymJCrh0cyS7BTIdcDxWUNsclr9VDkOSbqC13juHzxOmQ22dDkMZEpZB+3X1WpUvzgVQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.50.1", + "@typescript-eslint/tsconfig-utils": "8.50.1", + "@typescript-eslint/types": "8.50.1", + "@typescript-eslint/visitor-keys": "8.50.1", + "debug": "^4.3.4", + "minimatch": "^9.0.4", + "semver": "^7.6.0", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.1.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.2.tgz", + "integrity": "sha512-Jt0vHyM+jmUBqojB7E1NIYadt0vI0Qxjxd2TErW94wDz+E2LAm5vKMXXwg6ZZBTHPuUlDgQHKXvjGBdfcF1ZDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": { + "version": "9.0.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-9.0.5.tgz", + "integrity": "sha512-G6T0ZX48xgozx7587koeX9Ys2NYy6Gmv//P89sEte9V9whIapMNF4idKxnW2QtCcLiTWlb/wfCabAtAFWhhBow==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=16 || 14 >=14.17" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.50.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.50.1.tgz", + "integrity": "sha512-lCLp8H1T9T7gPbEuJSnHwnSuO9mDf8mfK/Nion5mZmiEaQD9sWf9W4dfeFqRyqRjF06/kBuTmAqcs9sewM2NbQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.7.0", + "@typescript-eslint/scope-manager": "8.50.1", + "@typescript-eslint/types": "8.50.1", + "@typescript-eslint/typescript-estree": "8.50.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.50.1", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.50.1.tgz", + "integrity": "sha512-IrDKrw7pCRUR94zeuCSUWQ+w8JEf5ZX5jl/e6AHGSLi1/zIr0lgutfn/7JpfCey+urpgQEdrZVYzCaVVKiTwhQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.50.1", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@unrs/resolver-binding-android-arm-eabi": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm-eabi/-/resolver-binding-android-arm-eabi-1.11.1.tgz", + "integrity": "sha512-ppLRUgHVaGRWUx0R0Ut06Mjo9gBaBkg3v/8AxusGLhsIotbBLuRk51rAzqLC8gq6NyyAojEXglNjzf6R948DNw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@unrs/resolver-binding-android-arm64": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-android-arm64/-/resolver-binding-android-arm64-1.11.1.tgz", + "integrity": "sha512-lCxkVtb4wp1v+EoN+HjIG9cIIzPkX5OtM03pQYkG+U5O/wL53LC4QbIeazgiKqluGeVEeBlZahHalCaBvU1a2g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ] + }, + "node_modules/@unrs/resolver-binding-darwin-arm64": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-arm64/-/resolver-binding-darwin-arm64-1.11.1.tgz", + "integrity": "sha512-gPVA1UjRu1Y/IsB/dQEsp2V1pm44Of6+LWvbLc9SDk1c2KhhDRDBUkQCYVWe6f26uJb3fOK8saWMgtX8IrMk3g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@unrs/resolver-binding-darwin-x64": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-darwin-x64/-/resolver-binding-darwin-x64-1.11.1.tgz", + "integrity": "sha512-cFzP7rWKd3lZaCsDze07QX1SC24lO8mPty9vdP+YVa3MGdVgPmFc59317b2ioXtgCMKGiCLxJ4HQs62oz6GfRQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ] + }, + "node_modules/@unrs/resolver-binding-freebsd-x64": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-freebsd-x64/-/resolver-binding-freebsd-x64-1.11.1.tgz", + "integrity": "sha512-fqtGgak3zX4DCB6PFpsH5+Kmt/8CIi4Bry4rb1ho6Av2QHTREM+47y282Uqiu3ZRF5IQioJQ5qWRV6jduA+iGw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm-gnueabihf": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-gnueabihf/-/resolver-binding-linux-arm-gnueabihf-1.11.1.tgz", + "integrity": "sha512-u92mvlcYtp9MRKmP+ZvMmtPN34+/3lMHlyMj7wXJDeXxuM0Vgzz0+PPJNsro1m3IZPYChIkn944wW8TYgGKFHw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm-musleabihf": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm-musleabihf/-/resolver-binding-linux-arm-musleabihf-1.11.1.tgz", + "integrity": "sha512-cINaoY2z7LVCrfHkIcmvj7osTOtm6VVT16b5oQdS4beibX2SYBwgYLmqhBjA1t51CarSaBuX5YNsWLjsqfW5Cw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm64-gnu": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-gnu/-/resolver-binding-linux-arm64-gnu-1.11.1.tgz", + "integrity": "sha512-34gw7PjDGB9JgePJEmhEqBhWvCiiWCuXsL9hYphDF7crW7UgI05gyBAi6MF58uGcMOiOqSJ2ybEeCvHcq0BCmQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-arm64-musl": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-arm64-musl/-/resolver-binding-linux-arm64-musl-1.11.1.tgz", + "integrity": "sha512-RyMIx6Uf53hhOtJDIamSbTskA99sPHS96wxVE/bJtePJJtpdKGXO1wY90oRdXuYOGOTuqjT8ACccMc4K6QmT3w==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-ppc64-gnu": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-ppc64-gnu/-/resolver-binding-linux-ppc64-gnu-1.11.1.tgz", + "integrity": "sha512-D8Vae74A4/a+mZH0FbOkFJL9DSK2R6TFPC9M+jCWYia/q2einCubX10pecpDiTmkJVUH+y8K3BZClycD8nCShA==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-riscv64-gnu": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-gnu/-/resolver-binding-linux-riscv64-gnu-1.11.1.tgz", + "integrity": "sha512-frxL4OrzOWVVsOc96+V3aqTIQl1O2TjgExV4EKgRY09AJ9leZpEg8Ak9phadbuX0BA4k8U5qtvMSQQGGmaJqcQ==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-riscv64-musl": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-riscv64-musl/-/resolver-binding-linux-riscv64-musl-1.11.1.tgz", + "integrity": "sha512-mJ5vuDaIZ+l/acv01sHoXfpnyrNKOk/3aDoEdLO/Xtn9HuZlDD6jKxHlkN8ZhWyLJsRBxfv9GYM2utQ1SChKew==", + "cpu": [ + "riscv64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-s390x-gnu": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-s390x-gnu/-/resolver-binding-linux-s390x-gnu-1.11.1.tgz", + "integrity": "sha512-kELo8ebBVtb9sA7rMe1Cph4QHreByhaZ2QEADd9NzIQsYNQpt9UkM9iqr2lhGr5afh885d/cB5QeTXSbZHTYPg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-x64-gnu": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-gnu/-/resolver-binding-linux-x64-gnu-1.11.1.tgz", + "integrity": "sha512-C3ZAHugKgovV5YvAMsxhq0gtXuwESUKc5MhEtjBpLoHPLYM+iuwSj3lflFwK3DPm68660rZ7G8BMcwSro7hD5w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-linux-x64-musl": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-linux-x64-musl/-/resolver-binding-linux-x64-musl-1.11.1.tgz", + "integrity": "sha512-rV0YSoyhK2nZ4vEswT/QwqzqQXw5I6CjoaYMOX0TqBlWhojUf8P94mvI7nuJTeaCkkds3QE4+zS8Ko+GdXuZtA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ] + }, + "node_modules/@unrs/resolver-binding-wasm32-wasi": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-wasm32-wasi/-/resolver-binding-wasm32-wasi-1.11.1.tgz", + "integrity": "sha512-5u4RkfxJm+Ng7IWgkzi3qrFOvLvQYnPBmjmZQ8+szTK/b31fQCnleNl1GgEt7nIsZRIf5PLhPwT0WM+q45x/UQ==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@napi-rs/wasm-runtime": "^0.2.11" + }, + "engines": { + "node": ">=14.0.0" + } + }, + "node_modules/@unrs/resolver-binding-win32-arm64-msvc": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-arm64-msvc/-/resolver-binding-win32-arm64-msvc-1.11.1.tgz", + "integrity": "sha512-nRcz5Il4ln0kMhfL8S3hLkxI85BXs3o8EYoattsJNdsX4YUU89iOkVn7g0VHSRxFuVMdM4Q1jEpIId1Ihim/Uw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@unrs/resolver-binding-win32-ia32-msvc": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-ia32-msvc/-/resolver-binding-win32-ia32-msvc-1.11.1.tgz", + "integrity": "sha512-DCEI6t5i1NmAZp6pFonpD5m7i6aFrpofcp4LA2i8IIq60Jyo28hamKBxNrZcyOwVOZkgsRp9O2sXWBWP8MnvIQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/@unrs/resolver-binding-win32-x64-msvc": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/@unrs/resolver-binding-win32-x64-msvc/-/resolver-binding-win32-x64-msvc-1.11.1.tgz", + "integrity": "sha512-lrW200hZdbfRtztbygyaq/6jP6AKE8qQN2KvPcJ+x7wiD038YtnYtZ82IMNJ69GJibV7bwL3y9FgK+5w/pYt6g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ] + }, + "node_modules/acorn": { + "version": "8.15.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz", + "integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.12.6", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz", + "integrity": "sha512-j3fVLgvTo527anyYyJOGTYJbG+vnnQYvE0m5mmkc1TK+nxAppkCLMIL0aZ4dblVCNoGShhm+kzE4ZUykBoMg4g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==", + "dev": true, + "license": "Python-2.0" + }, + "node_modules/aria-query": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/aria-query/-/aria-query-5.3.2.tgz", + "integrity": "sha512-COROpnaoap1E2F000S62r6A60uHZnmlvomhfyT2DlTcrY1OrBKn2UhH7qn5wTC9zMvD0AY7csdPSNwKP+7WiQw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/array-buffer-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/array-buffer-byte-length/-/array-buffer-byte-length-1.0.2.tgz", + "integrity": "sha512-LHE+8BuR7RYGDKvnrmcuSq3tDcKv9OFEXQt/HpbZhY7V6h0zlUXutnAD82GiFx9rdieCMjkvtcsPqBwgUl1Iiw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "is-array-buffer": "^3.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array-includes": { + "version": "3.1.9", + "resolved": "https://registry.npmjs.org/array-includes/-/array-includes-3.1.9.tgz", + "integrity": "sha512-FmeCCAenzH0KH381SPT5FZmiA/TmpndpcaShhfgEN9eCVjnFBqq3l1xrI42y8+PPLI6hypzou4GXw00WHmPBLQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.24.0", + "es-object-atoms": "^1.1.1", + "get-intrinsic": "^1.3.0", + "is-string": "^1.1.1", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.findlast": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/array.prototype.findlast/-/array.prototype.findlast-1.2.5.tgz", + "integrity": "sha512-CVvd6FHg1Z3POpBLxO6E6zr+rSKEQ9L6rZHAaY7lLfhKsWYUBBOuMs0e9o24oopj6H+geRCX0YJ+TJLBK2eHyQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.findlastindex": { + "version": "1.2.6", + "resolved": "https://registry.npmjs.org/array.prototype.findlastindex/-/array.prototype.findlastindex-1.2.6.tgz", + "integrity": "sha512-F/TKATkzseUExPlfvmwQKGITM3DGTK+vkAsCZoDc5daVygbJBnjEUCbgkAvVFsgfXfX4YIqZ/27G3k3tdXrTxQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.9", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "es-shim-unscopables": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.flat": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/array.prototype.flat/-/array.prototype.flat-1.3.3.tgz", + "integrity": "sha512-rwG/ja1neyLqCuGZ5YYrznA62D4mZXg0i1cIskIUKSiqF3Cje9/wXAls9B9s1Wa2fomMsIv8czB8jZcPmxCXFg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.flatmap": { + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/array.prototype.flatmap/-/array.prototype.flatmap-1.3.3.tgz", + "integrity": "sha512-Y7Wt51eKJSyi80hFrJCePGGNo5ktJCslFuboqJsbf57CCPcm5zztluPlc4/aD8sWsKvlwatezpV4U1efk8kpjg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/array.prototype.tosorted": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/array.prototype.tosorted/-/array.prototype.tosorted-1.1.4.tgz", + "integrity": "sha512-p6Fx8B7b7ZhL/gmUsAy0D15WhvDccw3mnGNbZpi3pmeJdxtWsj2jEaI4Y6oo3XiHfzuSgPwKc04MYt6KgvC/wA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.3", + "es-errors": "^1.3.0", + "es-shim-unscopables": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/arraybuffer.prototype.slice": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/arraybuffer.prototype.slice/-/arraybuffer.prototype.slice-1.0.4.tgz", + "integrity": "sha512-BNoCY6SXXPQ7gF2opIP4GBE+Xw7U+pHMYKuzjgCN3GwiaIR09UUeKfheyIry77QtrCBlC0KK0q5/TER/tYh3PQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.1", + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "is-array-buffer": "^3.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ast-types-flow": { + "version": "0.0.8", + "resolved": "https://registry.npmjs.org/ast-types-flow/-/ast-types-flow-0.0.8.tgz", + "integrity": "sha512-OH/2E5Fg20h2aPrbe+QL8JZQFko0YZaF+j4mnQ7BGhfavO7OpSLa8a0y9sBwomHdSbkhTS8TQNayBfnW5DwbvQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/async-function": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-function/-/async-function-1.0.0.tgz", + "integrity": "sha512-hsU18Ae8CDTR6Kgu9DYf0EbCr/a5iGL0rytQDobUcdpYOKokk8LEjVphnXkDkgpi0wYVsqrXuP0bZxJaTqdgoA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/available-typed-arrays": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz", + "integrity": "sha512-wvUjBtSGN7+7SjNpq/9M2Tg350UZD3q62IFZLbRAR1bSMlCo1ZaeW+BJ+D090e4hIIZLBcTDWe4Mh4jvUDajzQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "possible-typed-array-names": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/axe-core": { + "version": "4.11.0", + "resolved": "https://registry.npmjs.org/axe-core/-/axe-core-4.11.0.tgz", + "integrity": "sha512-ilYanEU8vxxBexpJd8cWM4ElSQq4QctCLKih0TSfjIfCQTeyH/6zVrmIJfLPrKTKJRbiG+cfnZbQIjAlJmF1jQ==", + "dev": true, + "license": "MPL-2.0", + "engines": { + "node": ">=4" + } + }, + "node_modules/axobject-query": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz", + "integrity": "sha512-qIj0G9wZbMGNLjLmg1PT6v2mE9AH2zlnADJD/2tC6E00hgmhUOfEB6greHPAfLRSufHqROIUTkw6E+M3lH0PTQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/baseline-browser-mapping": { + "version": "2.9.11", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.11.tgz", + "integrity": "sha512-Sg0xJUNDU1sJNGdfGWhVHX0kkZ+HWcvmVymJbj6NSgZZmW/8S9Y2HQ5euytnIgakgxN6papOAWiwDo1ctFDcoQ==", + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.js" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.12", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.12.tgz", + "integrity": "sha512-9T9UjW3r0UW5c1Q7GTwllptXwhvYmEzFhzMfZ9H7FQWt+uZePjZPjBP/W1ZEyZ1twGWom5/56TF4lPcqjnDHcg==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.3", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.3.tgz", + "integrity": "sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==", + "dev": true, + "license": "MIT", + "dependencies": { + "fill-range": "^7.1.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browserslist": { + "version": "4.28.1", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz", + "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.9.0", + "caniuse-lite": "^1.0.30001759", + "electron-to-chromium": "^1.5.263", + "node-releases": "^2.0.27", + "update-browserslist-db": "^1.2.0" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/call-bind": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/call-bind/-/call-bind-1.0.8.tgz", + "integrity": "sha512-oKlSFMcMwpUg2ednkhQ454wfWiU/ul3CkJe/PEHcTKuiX6RpbehUiFMXu13HalGZxfUwCQzZG747YXBn1im9ww==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.0", + "es-define-property": "^1.0.0", + "get-intrinsic": "^1.2.4", + "set-function-length": "^1.2.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/call-bind-apply-helpers": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz", + "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/call-bound": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/call-bound/-/call-bound-1.0.4.tgz", + "integrity": "sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "get-intrinsic": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/callsites": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz", + "integrity": "sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001761", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001761.tgz", + "integrity": "sha512-JF9ptu1vP2coz98+5051jZ4PwQgd2ni8A+gYSN7EA7dPKIMf0pDlSUxhdmVOaV3/fYK5uWBkgSXJaRLr4+3A6g==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chess.js": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/chess.js/-/chess.js-1.4.0.tgz", + "integrity": "sha512-BBJgrrtKQOzFLonR0l+k64A98NLemPwNsCskwb+29bRwobUa4iTm51E1kwGPbWXAcfdDa18nad6vpPPKPWarqw==", + "license": "BSD-2-Clause" + }, + "node_modules/client-only": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz", + "integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==", + "license": "MIT" + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==", + "dev": true, + "license": "MIT" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", + "dev": true, + "license": "MIT" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/damerau-levenshtein": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/damerau-levenshtein/-/damerau-levenshtein-1.0.8.tgz", + "integrity": "sha512-sdQSFB7+llfUcQHUQO3+B8ERRj0Oa4w9POWMI/puGtuf7gFywGmkaLCElnudfTiKZV+NvHqL0ifzdrI8Ro7ESA==", + "dev": true, + "license": "BSD-2-Clause" + }, + "node_modules/data-view-buffer": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz", + "integrity": "sha512-EmKO5V3OLXh1rtK2wgXRansaK1/mtVdTUEiEI0W8RkvgT05kfxaH29PliLnpLP73yYO6142Q72QNa8Wx/A5CqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/data-view-byte-length": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/data-view-byte-length/-/data-view-byte-length-1.0.2.tgz", + "integrity": "sha512-tuhGbE6CfTM9+5ANGf+oQb72Ky/0+s3xKUpHvShfiz2RxMFgFPjsXuRLBVMtvMs15awe45SRb83D6wH4ew6wlQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/inspect-js" + } + }, + "node_modules/data-view-byte-offset": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/data-view-byte-offset/-/data-view-byte-offset-1.0.1.tgz", + "integrity": "sha512-BS8PfmtDGnrgYdOonGZQdLZslWIeCGFP9tpan0hi1Co2Zr2NKADsvGYA8XxuG/4UWgJ6Cjtv+YJnB6MM69QGlQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-data-view": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/define-data-property": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/define-data-property/-/define-data-property-1.1.4.tgz", + "integrity": "sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0", + "es-errors": "^1.3.0", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/define-properties": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/define-properties/-/define-properties-1.2.1.tgz", + "integrity": "sha512-8QmQKqEASLd5nx0U1B1okLElbUuuttJ/AnYmRXbbbGDWh6uS208EjD4Xqq/I9wK7u0v6O08XhTWnt5XtEbR6Dg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.0.1", + "has-property-descriptors": "^1.0.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "devOptional": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/doctrine": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/doctrine/-/doctrine-2.1.0.tgz", + "integrity": "sha512-35mSku4ZXK0vfCuHEDAwt55dg2jNajHZ1odvF+8SSr82EsZY4QmXfuWso8oEd8zRhVObSN18aM0CjSdoBX7zIw==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "esutils": "^2.0.2" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/dunder-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz", + "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.1", + "es-errors": "^1.3.0", + "gopd": "^1.2.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.267", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.267.tgz", + "integrity": "sha512-0Drusm6MVRXSOJpGbaSVgcQsuB4hEkMpHXaVstcPmhu5LIedxs1xNK/nIxmQIU/RPC0+1/o0AVZfBTkTNJOdUw==", + "dev": true, + "license": "ISC" + }, + "node_modules/emoji-regex": { + "version": "9.2.2", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-9.2.2.tgz", + "integrity": "sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg==", + "dev": true, + "license": "MIT" + }, + "node_modules/enhanced-resolve": { + "version": "5.18.4", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.18.4.tgz", + "integrity": "sha512-LgQMM4WXU3QI+SYgEc2liRgznaD5ojbmY3sb8LxyguVkIg5FxdpTkvk72te2R38/TGKxH634oLxXRGY6d7AP+Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.2.0" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/es-abstract": { + "version": "1.24.1", + "resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.1.tgz", + "integrity": "sha512-zHXBLhP+QehSSbsS9Pt23Gg964240DPd6QCf8WpkqEXxQ7fhdZzYsocOr5u7apWonsS5EjZDmTF+/slGMyasvw==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-buffer-byte-length": "^1.0.2", + "arraybuffer.prototype.slice": "^1.0.4", + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "data-view-buffer": "^1.0.2", + "data-view-byte-length": "^1.0.2", + "data-view-byte-offset": "^1.0.1", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "es-set-tostringtag": "^2.1.0", + "es-to-primitive": "^1.3.0", + "function.prototype.name": "^1.1.8", + "get-intrinsic": "^1.3.0", + "get-proto": "^1.0.1", + "get-symbol-description": "^1.1.0", + "globalthis": "^1.0.4", + "gopd": "^1.2.0", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "internal-slot": "^1.1.0", + "is-array-buffer": "^3.0.5", + "is-callable": "^1.2.7", + "is-data-view": "^1.0.2", + "is-negative-zero": "^2.0.3", + "is-regex": "^1.2.1", + "is-set": "^2.0.3", + "is-shared-array-buffer": "^1.0.4", + "is-string": "^1.1.1", + "is-typed-array": "^1.1.15", + "is-weakref": "^1.1.1", + "math-intrinsics": "^1.1.0", + "object-inspect": "^1.13.4", + "object-keys": "^1.1.1", + "object.assign": "^4.1.7", + "own-keys": "^1.0.1", + "regexp.prototype.flags": "^1.5.4", + "safe-array-concat": "^1.1.3", + "safe-push-apply": "^1.0.0", + "safe-regex-test": "^1.1.0", + "set-proto": "^1.0.0", + "stop-iteration-iterator": "^1.1.0", + "string.prototype.trim": "^1.2.10", + "string.prototype.trimend": "^1.0.9", + "string.prototype.trimstart": "^1.0.8", + "typed-array-buffer": "^1.0.3", + "typed-array-byte-length": "^1.0.3", + "typed-array-byte-offset": "^1.0.4", + "typed-array-length": "^1.0.7", + "unbox-primitive": "^1.1.0", + "which-typed-array": "^1.1.19" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/es-define-property": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz", + "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-errors": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz", + "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-iterator-helpers": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/es-iterator-helpers/-/es-iterator-helpers-1.2.2.tgz", + "integrity": "sha512-BrUQ0cPTB/IwXj23HtwHjS9n7O4h9FX94b4xc5zlTHxeLgTAdzYUDyy6KdExAl9lbN5rtfe44xpjpmj9grxs5w==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.24.1", + "es-errors": "^1.3.0", + "es-set-tostringtag": "^2.1.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.3.0", + "globalthis": "^1.0.4", + "gopd": "^1.2.0", + "has-property-descriptors": "^1.0.2", + "has-proto": "^1.2.0", + "has-symbols": "^1.1.0", + "internal-slot": "^1.1.0", + "iterator.prototype": "^1.1.5", + "safe-array-concat": "^1.1.3" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-object-atoms": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz", + "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-set-tostringtag": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz", + "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-shim-unscopables": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/es-shim-unscopables/-/es-shim-unscopables-1.1.0.tgz", + "integrity": "sha512-d9T8ucsEhh8Bi1woXCf+TIKDIROLG5WCkxg8geBCbvk22kzwC5G2OnXVMO6FUsvQlgUUXQ2itephWDLqDzbeCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/es-to-primitive": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/es-to-primitive/-/es-to-primitive-1.3.0.tgz", + "integrity": "sha512-w+5mJ3GuFL+NjVtJlvydShqE1eN3h3PbI7/5LAsYJP/2qtuMXjfL2LpHSRqo4b4eSF5K/DH1JXKUAHSB2UW50g==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-callable": "^1.2.7", + "is-date-object": "^1.0.5", + "is-symbol": "^1.0.4" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "9.39.2", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-9.39.2.tgz", + "integrity": "sha512-LEyamqS7W5HB3ujJyvi0HQK/dtVINZvd5mAAp9eT5S/ujByGjiZLCzPcHVzuXbpJDJF/cxwHlfceVUDZ2lnSTw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.1", + "@eslint/config-array": "^0.21.1", + "@eslint/config-helpers": "^0.4.2", + "@eslint/core": "^0.17.0", + "@eslint/eslintrc": "^3.3.1", + "@eslint/js": "9.39.2", + "@eslint/plugin-kit": "^0.4.1", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.12.4", + "chalk": "^4.0.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^8.4.0", + "eslint-visitor-keys": "^4.2.1", + "espree": "^10.4.0", + "esquery": "^1.5.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "lodash.merge": "^4.6.2", + "minimatch": "^3.1.2", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-config-next": { + "version": "16.1.1", + "resolved": "https://registry.npmjs.org/eslint-config-next/-/eslint-config-next-16.1.1.tgz", + "integrity": "sha512-55nTpVWm3qeuxoQKLOjQVciKZJUphKrNM0fCcQHAIOGl6VFXgaqeMfv0aKJhs7QtcnlAPhNVqsqRfRjeKBPIUA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@next/eslint-plugin-next": "16.1.1", + "eslint-import-resolver-node": "^0.3.6", + "eslint-import-resolver-typescript": "^3.5.2", + "eslint-plugin-import": "^2.32.0", + "eslint-plugin-jsx-a11y": "^6.10.0", + "eslint-plugin-react": "^7.37.0", + "eslint-plugin-react-hooks": "^7.0.0", + "globals": "16.4.0", + "typescript-eslint": "^8.46.0" + }, + "peerDependencies": { + "eslint": ">=9.0.0", + "typescript": ">=3.3.1" + }, + "peerDependenciesMeta": { + "typescript": { + "optional": true + } + } + }, + "node_modules/eslint-config-next/node_modules/globals": { + "version": "16.4.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-16.4.0.tgz", + "integrity": "sha512-ob/2LcVVaVGCYN+r14cnwnoDPUufjiYgSqRhiFD0Q1iI4Odora5RE8Iv1D24hAz5oMophRGkGz+yuvQmmUMnMw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint-import-resolver-node": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-node/-/eslint-import-resolver-node-0.3.9.tgz", + "integrity": "sha512-WFj2isz22JahUv+B788TlO3N6zL3nNJGU8CcZbPZvVEkBPaJdCV4vy5wyghty5ROFbCRnm132v8BScu5/1BQ8g==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^3.2.7", + "is-core-module": "^2.13.0", + "resolve": "^1.22.4" + } + }, + "node_modules/eslint-import-resolver-node/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-import-resolver-typescript": { + "version": "3.10.1", + "resolved": "https://registry.npmjs.org/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-3.10.1.tgz", + "integrity": "sha512-A1rHYb06zjMGAxdLSkN2fXPBwuSaQ0iO5M/hdyS0Ajj1VBaRp0sPD3dn1FhME3c/JluGFbwSxyCfqdSbtQLAHQ==", + "dev": true, + "license": "ISC", + "dependencies": { + "@nolyfill/is-core-module": "1.0.39", + "debug": "^4.4.0", + "get-tsconfig": "^4.10.0", + "is-bun-module": "^2.0.0", + "stable-hash": "^0.0.5", + "tinyglobby": "^0.2.13", + "unrs-resolver": "^1.6.2" + }, + "engines": { + "node": "^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint-import-resolver-typescript" + }, + "peerDependencies": { + "eslint": "*", + "eslint-plugin-import": "*", + "eslint-plugin-import-x": "*" + }, + "peerDependenciesMeta": { + "eslint-plugin-import": { + "optional": true + }, + "eslint-plugin-import-x": { + "optional": true + } + } + }, + "node_modules/eslint-module-utils": { + "version": "2.12.1", + "resolved": "https://registry.npmjs.org/eslint-module-utils/-/eslint-module-utils-2.12.1.tgz", + "integrity": "sha512-L8jSWTze7K2mTg0vos/RuLRS5soomksDPoJLXIslC7c8Wmut3bx7CPpJijDcBZtxQ5lrbUdM+s0OlNbz0DCDNw==", + "dev": true, + "license": "MIT", + "dependencies": { + "debug": "^3.2.7" + }, + "engines": { + "node": ">=4" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, + "node_modules/eslint-module-utils/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-plugin-import": { + "version": "2.32.0", + "resolved": "https://registry.npmjs.org/eslint-plugin-import/-/eslint-plugin-import-2.32.0.tgz", + "integrity": "sha512-whOE1HFo/qJDyX4SnXzP4N6zOWn79WhnCUY/iDR0mPfQZO8wcYE4JClzI2oZrhBnnMUCBCHZhO6VQyoBU95mZA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rtsao/scc": "^1.1.0", + "array-includes": "^3.1.9", + "array.prototype.findlastindex": "^1.2.6", + "array.prototype.flat": "^1.3.3", + "array.prototype.flatmap": "^1.3.3", + "debug": "^3.2.7", + "doctrine": "^2.1.0", + "eslint-import-resolver-node": "^0.3.9", + "eslint-module-utils": "^2.12.1", + "hasown": "^2.0.2", + "is-core-module": "^2.16.1", + "is-glob": "^4.0.3", + "minimatch": "^3.1.2", + "object.fromentries": "^2.0.8", + "object.groupby": "^1.0.3", + "object.values": "^1.2.1", + "semver": "^6.3.1", + "string.prototype.trimend": "^1.0.9", + "tsconfig-paths": "^3.15.0" + }, + "engines": { + "node": ">=4" + }, + "peerDependencies": { + "eslint": "^2 || ^3 || ^4 || ^5 || ^6 || ^7.2.0 || ^8 || ^9" + } + }, + "node_modules/eslint-plugin-import/node_modules/debug": { + "version": "3.2.7", + "resolved": "https://registry.npmjs.org/debug/-/debug-3.2.7.tgz", + "integrity": "sha512-CFjzYYAi4ThfiQvizrFQevTTXHtnCqWfe7x1AhgEscTz6ZbLbfoLRLPugTQyBth6f8ZERVUSyWHFD/7Wu4t1XQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.1" + } + }, + "node_modules/eslint-plugin-jsx-a11y": { + "version": "6.10.2", + "resolved": "https://registry.npmjs.org/eslint-plugin-jsx-a11y/-/eslint-plugin-jsx-a11y-6.10.2.tgz", + "integrity": "sha512-scB3nz4WmG75pV8+3eRUQOHZlNSUhFNq37xnpgRkCCELU3XMvXAxLk1eqWWyE22Ki4Q01Fnsw9BA3cJHDPgn2Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "aria-query": "^5.3.2", + "array-includes": "^3.1.8", + "array.prototype.flatmap": "^1.3.2", + "ast-types-flow": "^0.0.8", + "axe-core": "^4.10.0", + "axobject-query": "^4.1.0", + "damerau-levenshtein": "^1.0.8", + "emoji-regex": "^9.2.2", + "hasown": "^2.0.2", + "jsx-ast-utils": "^3.3.5", + "language-tags": "^1.0.9", + "minimatch": "^3.1.2", + "object.fromentries": "^2.0.8", + "safe-regex-test": "^1.0.3", + "string.prototype.includes": "^2.0.1" + }, + "engines": { + "node": ">=4.0" + }, + "peerDependencies": { + "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9" + } + }, + "node_modules/eslint-plugin-react": { + "version": "7.37.5", + "resolved": "https://registry.npmjs.org/eslint-plugin-react/-/eslint-plugin-react-7.37.5.tgz", + "integrity": "sha512-Qteup0SqU15kdocexFNAJMvCJEfa2xUKNV4CC1xsVMrIIqEy3SQ/rqyxCWNzfrd3/ldy6HMlD2e0JDVpDg2qIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-includes": "^3.1.8", + "array.prototype.findlast": "^1.2.5", + "array.prototype.flatmap": "^1.3.3", + "array.prototype.tosorted": "^1.1.4", + "doctrine": "^2.1.0", + "es-iterator-helpers": "^1.2.1", + "estraverse": "^5.3.0", + "hasown": "^2.0.2", + "jsx-ast-utils": "^2.4.1 || ^3.0.0", + "minimatch": "^3.1.2", + "object.entries": "^1.1.9", + "object.fromentries": "^2.0.8", + "object.values": "^1.2.1", + "prop-types": "^15.8.1", + "resolve": "^2.0.0-next.5", + "semver": "^6.3.1", + "string.prototype.matchall": "^4.0.12", + "string.prototype.repeat": "^1.0.0" + }, + "engines": { + "node": ">=4" + }, + "peerDependencies": { + "eslint": "^3 || ^4 || ^5 || ^6 || ^7 || ^8 || ^9.7" + } + }, + "node_modules/eslint-plugin-react-hooks": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.0.1.tgz", + "integrity": "sha512-O0d0m04evaNzEPoSW+59Mezf8Qt0InfgGIBJnpC0h3NH/WjUAR7BIKUfysC6todmtiZ/A0oUVS8Gce0WhBrHsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.24.4", + "@babel/parser": "^7.24.4", + "hermes-parser": "^0.25.1", + "zod": "^3.25.0 || ^4.0.0", + "zod-validation-error": "^3.5.0 || ^4.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0" + } + }, + "node_modules/eslint-plugin-react/node_modules/resolve": { + "version": "2.0.0-next.5", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-2.0.0-next.5.tgz", + "integrity": "sha512-U7WjGVG9sH8tvjW5SmGbQuui75FiyjAX72HX15DwBBwF9dNiQZRQAg9nnPhYy+TUnE0+VcrttuvNI8oSxZcocA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-core-module": "^2.13.0", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/eslint-scope": { + "version": "8.4.0", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-8.4.0.tgz", + "integrity": "sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz", + "integrity": "sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-10.4.0.tgz", + "integrity": "sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.15.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^4.2.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.6.0.tgz", + "integrity": "sha512-ca9pw9fomFcKPvFLXhBKUK90ZvGibiGOvRJNbjljY7s7uq/5YO4BOzcYtJqExdx99rF6aAcnRxHmcUHcz6sQsg==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-glob": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.1.tgz", + "integrity": "sha512-kNFPyjhh5cKjrUltxs+wFx+ZkbRaxxmZ+X0ZU31SOsxCEtP9VPgtq2teZw1DebupL5GmDaNQ6yKMMVcM41iqDg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@nodelib/fs.stat": "^2.0.2", + "@nodelib/fs.walk": "^1.2.3", + "glob-parent": "^5.1.2", + "merge2": "^1.3.0", + "micromatch": "^4.0.4" + }, + "engines": { + "node": ">=8.6.0" + } + }, + "node_modules/fast-glob/node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fastq": { + "version": "1.20.1", + "resolved": "https://registry.npmjs.org/fastq/-/fastq-1.20.1.tgz", + "integrity": "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw==", + "dev": true, + "license": "ISC", + "dependencies": { + "reusify": "^1.0.4" + } + }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/fill-range": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.1.1.tgz", + "integrity": "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg==", + "dev": true, + "license": "MIT", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.3.3.tgz", + "integrity": "sha512-GX+ysw4PBCz0PzosHDepZGANEuFCMLrnRTiEy9McGjmkCQYwRq4A/X786G/fjM/+OjsWSU1ZrY5qyARZmO/uwg==", + "dev": true, + "license": "ISC" + }, + "node_modules/for-each": { + "version": "0.3.5", + "resolved": "https://registry.npmjs.org/for-each/-/for-each-0.3.5.tgz", + "integrity": "sha512-dKx12eRCVIzqCxFGplyFKJMPvLEWgmNtUrpTiJIR5u97zEhRG8ySrtboPHZXx7daLxQVrl643cTzbab2tkQjxg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/function-bind": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz", + "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/function.prototype.name": { + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/function.prototype.name/-/function.prototype.name-1.1.8.tgz", + "integrity": "sha512-e5iwyodOHhbMr/yNrc7fDYG4qlbIvI5gajyzPnb5TCwyhjApznQh1BMFou9b30SevY43gCJKXycoCBjMbsuW0Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "functions-have-names": "^1.2.3", + "hasown": "^2.0.2", + "is-callable": "^1.2.7" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/functions-have-names": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/functions-have-names/-/functions-have-names-1.2.3.tgz", + "integrity": "sha512-xckBUXyTIqT97tq2x2AMb+g163b5JFysYk0x4qxNFwbfQkmNZoiRHb6sPzI9/QV33WeuvVYBUIiD4NzNIyqaRQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/generator-function": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/generator-function/-/generator-function-2.0.1.tgz", + "integrity": "sha512-SFdFmIJi+ybC0vjlHN0ZGVGHc3lgE0DxPAT0djjVg+kjOnSqclqmj0KQ7ykTOLP6YxoqOvuAODGdcHJn+43q3g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/get-intrinsic": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", + "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind-apply-helpers": "^1.0.2", + "es-define-property": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.1.1", + "function-bind": "^1.1.2", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "hasown": "^2.0.2", + "math-intrinsics": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-proto": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz", + "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/get-symbol-description": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/get-symbol-description/-/get-symbol-description-1.1.0.tgz", + "integrity": "sha512-w9UMqWwJxHNOvoNzSJ2oPF5wvYcvP7jUvYzhp67yEhTi17ZDBBC1z9pTdGuzjD+EFIqLSYRweZjqfiPzQ06Ebg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/get-tsconfig": { + "version": "4.13.0", + "resolved": "https://registry.npmjs.org/get-tsconfig/-/get-tsconfig-4.13.0.tgz", + "integrity": "sha512-1VKTZJCwBrvbd+Wn3AOgQP/2Av+TfTCOlE4AcRJE72W1ksZXbAx8PPBR9RzgTeSPzlPMHrbANMH3LbltH73wxQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "resolve-pkg-maps": "^1.0.0" + }, + "funding": { + "url": "https://github.com/privatenumber/get-tsconfig?sponsor=1" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "14.0.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-14.0.0.tgz", + "integrity": "sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/globalthis": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/globalthis/-/globalthis-1.0.4.tgz", + "integrity": "sha512-DpLKbNU4WylpxJykQujfCcwYWiV/Jhm50Goo0wrVILAv5jOr9d+H+UR3PhSCD2rCCEIg0uc+G+muBTwD54JhDQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-properties": "^1.2.1", + "gopd": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/gopd": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz", + "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.11", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz", + "integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==", + "dev": true, + "license": "ISC" + }, + "node_modules/has-bigints": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-bigints/-/has-bigints-1.1.0.tgz", + "integrity": "sha512-R3pbpkcIqv2Pm3dUwgjclDRVmWpTJW2DcMzcIhEXEx1oh/CEMObMm3KLmRJOdvhM7o4uQBnwr8pzRK2sJWIqfg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/has-property-descriptors": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-property-descriptors/-/has-property-descriptors-1.0.2.tgz", + "integrity": "sha512-55JNKuIW+vq4Ke1BjOTjM2YctQIvCT7GFzHwmfZPGo5wnrgkid0YQtnAleFSqumZm4az3n2BS+erby5ipJdgrg==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-define-property": "^1.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-proto": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/has-proto/-/has-proto-1.2.0.tgz", + "integrity": "sha512-KIL7eQPfHQRC8+XluaIw7BHUwwqL19bQn4hzNgdr+1wXoU0KKj6rufu47lhY7KbJR2C6T6+PfyN0Ea7wkSS+qQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-symbols": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz", + "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/has-tostringtag": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz", + "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-symbols": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/hasown": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz", + "integrity": "sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "function-bind": "^1.1.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/hermes-estree": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz", + "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==", + "dev": true, + "license": "MIT" + }, + "node_modules/hermes-parser": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz", + "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hermes-estree": "0.25.1" + } + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/import-fresh": { + "version": "3.3.1", + "resolved": "https://registry.npmjs.org/import-fresh/-/import-fresh-3.3.1.tgz", + "integrity": "sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "parent-module": "^1.0.0", + "resolve-from": "^4.0.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/internal-slot": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/internal-slot/-/internal-slot-1.1.0.tgz", + "integrity": "sha512-4gd7VpWNQNB4UKKCFFVcp1AVv+FMOgs9NKzjHKusc8jTMhd5eL1NqQqOpE0KzMds804/yHlglp3uxgluOqAPLw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "hasown": "^2.0.2", + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/is-array-buffer": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz", + "integrity": "sha512-DDfANUiiG2wC1qawP66qlTugJeL5HyzMpfr8lLK+jMQirGzNod0B12cFB/9q838Ru27sBwfw78/rdoU7RERz6A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-async-function": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-async-function/-/is-async-function-2.1.1.tgz", + "integrity": "sha512-9dgM/cZBnNvjzaMYHVoxxfPj2QXt22Ev7SuuPrs+xav0ukGB0S6d4ydZdEiM48kLx5kDV+QBPrpVnFyefL8kkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "async-function": "^1.0.0", + "call-bound": "^1.0.3", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-bigint": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-bigint/-/is-bigint-1.1.0.tgz", + "integrity": "sha512-n4ZT37wG78iz03xPRKJrHTdZbe3IicyucEtdRsV5yglwc3GyUfbAfpSeD0FJ41NbUNSt5wbhqfp1fS+BgnvDFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-bigints": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-boolean-object": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/is-boolean-object/-/is-boolean-object-1.2.2.tgz", + "integrity": "sha512-wa56o2/ElJMYqjCjGkXri7it5FbebW5usLw/nPmCMs5DeZ7eziSYZhSmPRn0txqeW4LnAmQQU7FgqLpsEFKM4A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-bun-module": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-bun-module/-/is-bun-module-2.0.0.tgz", + "integrity": "sha512-gNCGbnnnnFAUGKeZ9PdbyeGYJqewpmc2aKHUEMO5nQPWU9lOmv7jcmQIv+qHD8fXW6W7qfuCwX4rY9LNRjXrkQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "semver": "^7.7.1" + } + }, + "node_modules/is-bun-module/node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/is-callable": { + "version": "1.2.7", + "resolved": "https://registry.npmjs.org/is-callable/-/is-callable-1.2.7.tgz", + "integrity": "sha512-1BC0BVFhS/p0qtw6enp8e+8OD0UrK0oFLztSjNzhcKA3WDuJxxAPXzPuPtKkjEY9UUoEWlX/8fgKeu2S8i9JTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-core-module": { + "version": "2.16.1", + "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.16.1.tgz", + "integrity": "sha512-UfoeMA6fIJ8wTYFEUjelnaGI67v6+N7qXJEvQuIGa99l4xsCruSYOVSQ0uPANn4dAzm8lkYPaKLrrijLq7x23w==", + "dev": true, + "license": "MIT", + "dependencies": { + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-data-view": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/is-data-view/-/is-data-view-1.0.2.tgz", + "integrity": "sha512-RKtWF8pGmS87i2D6gqQu/l7EYRlVdfzemCJN/P3UOs//x1QE7mfhvzHIApBTRf7axvT6DMGwSwBXYCT0nfB9xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "get-intrinsic": "^1.2.6", + "is-typed-array": "^1.1.13" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-date-object": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/is-date-object/-/is-date-object-1.1.0.tgz", + "integrity": "sha512-PwwhEakHVKTdRNVOw+/Gyh0+MzlCl4R6qKvkhuvLtPMggI1WAHt9sOwZxQLSGpUaDnrdyDsomoRgNnCfKNSXXg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-finalizationregistry": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-finalizationregistry/-/is-finalizationregistry-1.1.1.tgz", + "integrity": "sha512-1pC6N8qWJbWoPtEjgcL2xyhQOP491EQjeUo3qTKcmV8YSDDJrOepfG8pcC7h/QgnQHYSv0mJ3Z/ZWxmatVrysg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-generator-function": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/is-generator-function/-/is-generator-function-1.1.2.tgz", + "integrity": "sha512-upqt1SkGkODW9tsGNG5mtXTXtECizwtS2kA161M+gJPc1xdb/Ax629af6YrTwcOeQHbewrPNlE5Dx7kzvXTizA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.4", + "generator-function": "^2.0.0", + "get-proto": "^1.0.1", + "has-tostringtag": "^1.0.2", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-map": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz", + "integrity": "sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-negative-zero": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-negative-zero/-/is-negative-zero-2.0.3.tgz", + "integrity": "sha512-5KoIu2Ngpyek75jXodFvnafB6DJgr3u8uuK0LEZJjrU19DrMD3EVERaR8sjz8CCGgpZvxPl9SuE1GMVPFHx1mw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-number-object": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-number-object/-/is-number-object-1.1.1.tgz", + "integrity": "sha512-lZhclumE1G6VYD8VHe35wFaIif+CTy5SJIi5+3y4psDgWu4wPDoBhF8NxUOinEc7pHgiTsT6MaBb92rKhhD+Xw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-regex": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz", + "integrity": "sha512-MjYsKHO5O7mCsmRGxWcLWheFqN9DJ/2TmngvjKXihe6efViPqc274+Fx/4fYj/r03+ESvBdTXK0V6tA3rgez1g==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2", + "hasown": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-set": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/is-set/-/is-set-2.0.3.tgz", + "integrity": "sha512-iPAjerrse27/ygGLxw+EBR9agv9Y6uLeYVJMu+QNCoouJ1/1ri0mGrcWpfCqFZuzzx3WjtwxG098X+n4OuRkPg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-shared-array-buffer": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/is-shared-array-buffer/-/is-shared-array-buffer-1.0.4.tgz", + "integrity": "sha512-ISWac8drv4ZGfwKl5slpHG9OwPNty4jOWPRIhBpxOoD+hqITiwuipOQ2bNthAzwA3B4fIjO4Nln74N0S9byq8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-string": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-string/-/is-string-1.1.1.tgz", + "integrity": "sha512-BtEeSsoaQjlSPBemMQIrY1MY0uM6vnS1g5fmufYOtnxLGUZM2178PKbhsk7Ffv58IX+ZtcvoGwccYsh0PglkAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-symbol": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-symbol/-/is-symbol-1.1.1.tgz", + "integrity": "sha512-9gGx6GTtCQM73BgmHQXfDmLtfjjTUDSyoxTCbp5WtoixAhfgsDirWIcVQ/IHpvI5Vgd5i/J5F7B9cN/WlVbC/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "has-symbols": "^1.1.0", + "safe-regex-test": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-typed-array": { + "version": "1.1.15", + "resolved": "https://registry.npmjs.org/is-typed-array/-/is-typed-array-1.1.15.tgz", + "integrity": "sha512-p3EcsicXjit7SaskXHs1hA91QxgTw46Fv6EFKKGS5DRFLD8yKnohjF3hxoju94b/OcMZoQukzpPpBE9uLVKzgQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakmap": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/is-weakmap/-/is-weakmap-2.0.2.tgz", + "integrity": "sha512-K5pXYOm9wqY1RgjpL3YTkF39tni1XajUIkawTLUo9EZEVUFga5gSQJF8nNS7ZwJQ02y+1YCNYcMh+HIf1ZqE+w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakref": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/is-weakref/-/is-weakref-1.1.1.tgz", + "integrity": "sha512-6i9mGWSlqzNMEqpCp93KwRS1uUOodk2OJ6b+sq7ZPDSy2WuI5NFIxp/254TytR8ftefexkWn5xNiHUNpPOfSew==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/is-weakset": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/is-weakset/-/is-weakset-2.0.4.tgz", + "integrity": "sha512-mfcwb6IzQyOKTs84CQMrOwW4gQcaTOAWJ0zzJCl2WSPDrWk/OzDaImWFH3djXhb24g4eudZfLRozAvPGw4d9hQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "get-intrinsic": "^1.2.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/isarray": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/isarray/-/isarray-2.0.5.tgz", + "integrity": "sha512-xHjhDr3cNBK0BzdUJSPXZntQUx/mwMS5Rw4A7lPJ90XGAO6ISP/ePDNuo0vhqOZU+UD5JoodwCAAoZQd3FeAKw==", + "dev": true, + "license": "MIT" + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/iterator.prototype": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/iterator.prototype/-/iterator.prototype-1.1.5.tgz", + "integrity": "sha512-H0dkQoCa3b2VEeKQBOxFph+JAbcrQdE7KC0UkqwpLmv2EC4P41QXP+rqo9wYodACiG5/WM5s9oDApTU8utwj9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.6", + "get-proto": "^1.0.0", + "has-symbols": "^1.1.0", + "set-function-name": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/jiti": { + "version": "2.6.1", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.6.1.tgz", + "integrity": "sha512-ekilCSN1jwRvIbgeg/57YFh8qQDNbwDb9xT/qu2DAHbFFZUicIl4ygVaAvzveMhMVr3LnpSKTNnwt8PoOfmKhQ==", + "dev": true, + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/js-yaml": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.1.tgz", + "integrity": "sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==", + "dev": true, + "license": "MIT", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/jsx-ast-utils": { + "version": "3.3.5", + "resolved": "https://registry.npmjs.org/jsx-ast-utils/-/jsx-ast-utils-3.3.5.tgz", + "integrity": "sha512-ZZow9HBI5O6EPgSJLUb8n2NKgmVWTwCvHGwFuJlMjvLFqlGG6pjirPhtdsseaLZjSibD8eegzmYpUZwoIlj2cQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "array-includes": "^3.1.6", + "array.prototype.flat": "^1.3.1", + "object.assign": "^4.1.4", + "object.values": "^1.1.6" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/language-subtag-registry": { + "version": "0.3.23", + "resolved": "https://registry.npmjs.org/language-subtag-registry/-/language-subtag-registry-0.3.23.tgz", + "integrity": "sha512-0K65Lea881pHotoGEa5gDlMxt3pctLi2RplBb7Ezh4rRdLEOtgi7n4EwK9lamnUCkKBqaeKRVebTq6BAxSkpXQ==", + "dev": true, + "license": "CC0-1.0" + }, + "node_modules/language-tags": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/language-tags/-/language-tags-1.0.9.tgz", + "integrity": "sha512-MbjN408fEndfiQXbFQ1vnd+1NoLDsnQW41410oQBXiyXDMYH5z505juWa4KUE1LqxRC7DgOgZDbKLxHIwm27hA==", + "dev": true, + "license": "MIT", + "dependencies": { + "language-subtag-registry": "^0.3.20" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/lightningcss": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.30.2.tgz", + "integrity": "sha512-utfs7Pr5uJyyvDETitgsaqSyjCb2qNRAtuqUeWIAKztsOYdcACf2KtARYXg2pSvhkt+9NfoaNY7fxjl6nuMjIQ==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.30.2", + "lightningcss-darwin-arm64": "1.30.2", + "lightningcss-darwin-x64": "1.30.2", + "lightningcss-freebsd-x64": "1.30.2", + "lightningcss-linux-arm-gnueabihf": "1.30.2", + "lightningcss-linux-arm64-gnu": "1.30.2", + "lightningcss-linux-arm64-musl": "1.30.2", + "lightningcss-linux-x64-gnu": "1.30.2", + "lightningcss-linux-x64-musl": "1.30.2", + "lightningcss-win32-arm64-msvc": "1.30.2", + "lightningcss-win32-x64-msvc": "1.30.2" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.30.2.tgz", + "integrity": "sha512-BH9sEdOCahSgmkVhBLeU7Hc9DWeZ1Eb6wNS6Da8igvUwAe0sqROHddIlvU06q3WyXVEOYDZ6ykBZQnjTbmo4+A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.30.2.tgz", + "integrity": "sha512-ylTcDJBN3Hp21TdhRT5zBOIi73P6/W0qwvlFEk22fkdXchtNTOU4Qc37SkzV+EKYxLouZ6M4LG9NfZ1qkhhBWA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.30.2.tgz", + "integrity": "sha512-oBZgKchomuDYxr7ilwLcyms6BCyLn0z8J0+ZZmfpjwg9fRVZIR5/GMXd7r9RH94iDhld3UmSjBM6nXWM2TfZTQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.30.2.tgz", + "integrity": "sha512-c2bH6xTrf4BDpK8MoGG4Bd6zAMZDAXS569UxCAGcA7IKbHNMlhGQ89eRmvpIUGfKWNVdbhSbkQaWhEoMGmGslA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.30.2.tgz", + "integrity": "sha512-eVdpxh4wYcm0PofJIZVuYuLiqBIakQ9uFZmipf6LF/HRj5Bgm0eb3qL/mr1smyXIS1twwOxNWndd8z0E374hiA==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.30.2.tgz", + "integrity": "sha512-UK65WJAbwIJbiBFXpxrbTNArtfuznvxAJw4Q2ZGlU8kPeDIWEX1dg3rn2veBVUylA2Ezg89ktszWbaQnxD/e3A==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.30.2.tgz", + "integrity": "sha512-5Vh9dGeblpTxWHpOx8iauV02popZDsCYMPIgiuw97OJ5uaDsL86cnqSFs5LZkG3ghHoX5isLgWzMs+eD1YzrnA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.30.2.tgz", + "integrity": "sha512-Cfd46gdmj1vQ+lR6VRTTadNHu6ALuw2pKR9lYq4FnhvgBc4zWY1EtZcAc6EffShbb1MFrIPfLDXD6Xprbnni4w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.30.2.tgz", + "integrity": "sha512-XJaLUUFXb6/QG2lGIW6aIk6jKdtjtcffUT0NKvIqhSBY3hh9Ch+1LCeH80dR9q9LBjG3ewbDjnumefsLsP6aiA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.30.2.tgz", + "integrity": "sha512-FZn+vaj7zLv//D/192WFFVA0RgHawIcHqLX9xuWiQt7P0PtdFEVaxgF9rjM/IRYHQXNnk61/H/gb2Ei+kUQ4xQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.30.2", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.30.2.tgz", + "integrity": "sha512-5g1yc73p+iAkid5phb4oVFMB45417DkRevRbt/El/gKXJk4jid+vPFF/AXbxn05Aky8PapwzZrdJShv5C0avjw==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lodash.merge": { + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/lodash.merge/-/lodash.merge-4.6.2.tgz", + "integrity": "sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/loose-envify": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz", + "integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "js-tokens": "^3.0.0 || ^4.0.0" + }, + "bin": { + "loose-envify": "cli.js" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/magic-string": { + "version": "0.30.21", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz", + "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.5" + } + }, + "node_modules/math-intrinsics": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", + "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/merge2": { + "version": "1.4.1", + "resolved": "https://registry.npmjs.org/merge2/-/merge2-1.4.1.tgz", + "integrity": "sha512-8q7VEgMJW4J8tcfVPy8g09NcQwZdbwFEqhe/WZkoIzjn/3TGDwtOCYtXGxA3O8tPzpczCCDgv+P2P5y00ZJOOg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 8" + } + }, + "node_modules/micromatch": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/micromatch/-/micromatch-4.0.8.tgz", + "integrity": "sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA==", + "dev": true, + "license": "MIT", + "dependencies": { + "braces": "^3.0.3", + "picomatch": "^2.3.1" + }, + "engines": { + "node": ">=8.6" + } + }, + "node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dev": true, + "license": "ISC", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/minimist": { + "version": "1.2.8", + "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", + "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.11", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", + "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/napi-postinstall": { + "version": "0.3.4", + "resolved": "https://registry.npmjs.org/napi-postinstall/-/napi-postinstall-0.3.4.tgz", + "integrity": "sha512-PHI5f1O0EP5xJ9gQmFGMS6IZcrVvTjpXjz7Na41gTE7eE2hK11lg04CECCYEEjdc17EV4DO+fkGEtt7TpTaTiQ==", + "dev": true, + "license": "MIT", + "bin": { + "napi-postinstall": "lib/cli.js" + }, + "engines": { + "node": "^12.20.0 || ^14.18.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/napi-postinstall" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/next": { + "version": "16.1.1", + "resolved": "https://registry.npmjs.org/next/-/next-16.1.1.tgz", + "integrity": "sha512-QI+T7xrxt1pF6SQ/JYFz95ro/mg/1Znk5vBebsWwbpejj1T0A23hO7GYEaVac9QUOT2BIMiuzm0L99ooq7k0/w==", + "license": "MIT", + "dependencies": { + "@next/env": "16.1.1", + "@swc/helpers": "0.5.15", + "baseline-browser-mapping": "^2.8.3", + "caniuse-lite": "^1.0.30001579", + "postcss": "8.4.31", + "styled-jsx": "5.1.6" + }, + "bin": { + "next": "dist/bin/next" + }, + "engines": { + "node": ">=20.9.0" + }, + "optionalDependencies": { + "@next/swc-darwin-arm64": "16.1.1", + "@next/swc-darwin-x64": "16.1.1", + "@next/swc-linux-arm64-gnu": "16.1.1", + "@next/swc-linux-arm64-musl": "16.1.1", + "@next/swc-linux-x64-gnu": "16.1.1", + "@next/swc-linux-x64-musl": "16.1.1", + "@next/swc-win32-arm64-msvc": "16.1.1", + "@next/swc-win32-x64-msvc": "16.1.1", + "sharp": "^0.34.4" + }, + "peerDependencies": { + "@opentelemetry/api": "^1.1.0", + "@playwright/test": "^1.51.1", + "babel-plugin-react-compiler": "*", + "react": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", + "react-dom": "^18.2.0 || 19.0.0-rc-de68d2f4-20241204 || ^19.0.0", + "sass": "^1.3.0" + }, + "peerDependenciesMeta": { + "@opentelemetry/api": { + "optional": true + }, + "@playwright/test": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + }, + "sass": { + "optional": true + } + } + }, + "node_modules/next/node_modules/postcss": { + "version": "8.4.31", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz", + "integrity": "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.6", + "picocolors": "^1.0.0", + "source-map-js": "^1.0.2" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/node-releases": { + "version": "2.0.27", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.27.tgz", + "integrity": "sha512-nmh3lCkYZ3grZvqcCH+fjmQ7X+H0OeZgP40OierEaAptX4XofMh5kwNbWh7lBduUzCcV/8kZ+NDLCwm2iorIlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/object-assign": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", + "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/object-inspect": { + "version": "1.13.4", + "resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz", + "integrity": "sha512-W67iLl4J2EXEGTbfeHCffrjDfitvLANg0UlX3wFUUSTx92KXRFegMHUVgSqE+wvhAbi4WqjGg9czysTV2Epbew==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object-keys": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/object-keys/-/object-keys-1.1.1.tgz", + "integrity": "sha512-NuAESUOUMrlIXOfHKzD6bpPu3tYt3xvjNdRIQ+FeT0lNb4K8WR70CaDxhuNguS2XG+GjkyMwOzsN5ZktImfhLA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.assign": { + "version": "4.1.7", + "resolved": "https://registry.npmjs.org/object.assign/-/object.assign-4.1.7.tgz", + "integrity": "sha512-nK28WOo+QIjBkDduTINE4JkF/UJJKyf2EJxvJKfblDpyg0Q+pkOHNTL0Qwy6NP6FhE/EnzV73BxxqcJaXY9anw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0", + "has-symbols": "^1.1.0", + "object-keys": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.entries": { + "version": "1.1.9", + "resolved": "https://registry.npmjs.org/object.entries/-/object.entries-1.1.9.tgz", + "integrity": "sha512-8u/hfXFRBD1O0hPUjioLhoWFHRmt6tKA4/vZPyckBr18l1KE9uHrFaFaUi8MDRTpi4uak2goyPTSNJLXX2k2Hw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.fromentries": { + "version": "2.0.8", + "resolved": "https://registry.npmjs.org/object.fromentries/-/object.fromentries-2.0.8.tgz", + "integrity": "sha512-k6E21FzySsSK5a21KRADBd/NGneRegFO5pLHfdQLpRDETUNJueLXs3WCzyQ3tFRDYgbq3KHGXfTbi2bs8WQ6rQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/object.groupby": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/object.groupby/-/object.groupby-1.0.3.tgz", + "integrity": "sha512-+Lhy3TQTuzXI5hevh8sBGqbmurHbbIjAi0Z4S63nthVLmLxfbj4T54a4CfZrXIrt9iP4mVAPYMo/v99taj3wjQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/object.values": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/object.values/-/object.values-1.2.1.tgz", + "integrity": "sha512-gXah6aZrcUxjWg2zR2MwouP2eHlCBzdV4pygudehaKXSGW4v2AsRQUK+lwwXhii6KFZcunEnmSUoYp5CXibxtA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/own-keys": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/own-keys/-/own-keys-1.0.1.tgz", + "integrity": "sha512-qFOyK5PjiWZd+QQIh+1jhdb9LpxTF0qs7Pm8o5QHYZ0M3vKqSqzsZaEB6oWlxZ+q2sJBMI/Ktgd2N5ZwQoRHfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "get-intrinsic": "^1.2.6", + "object-keys": "^1.1.1", + "safe-push-apply": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/parent-module": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/parent-module/-/parent-module-1.0.1.tgz", + "integrity": "sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g==", + "dev": true, + "license": "MIT", + "dependencies": { + "callsites": "^3.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-parse": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz", + "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==", + "dev": true, + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/possible-typed-array-names": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/possible-typed-array-names/-/possible-typed-array-names-1.1.0.tgz", + "integrity": "sha512-/+5VFTchJDoVj3bhoqi6UeymcD00DAwb1nJwamzPvHEszJ4FpF6SNNbUbOS8yI56qHzdV8eK0qEfOSiodkTdxg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/postcss": { + "version": "8.5.6", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", + "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.11", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/prop-types": { + "version": "15.8.1", + "resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz", + "integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==", + "dev": true, + "license": "MIT", + "dependencies": { + "loose-envify": "^1.4.0", + "object-assign": "^4.1.1", + "react-is": "^16.13.1" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/queue-microtask": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/queue-microtask/-/queue-microtask-1.2.3.tgz", + "integrity": "sha512-NuaNSa6flKT5JaSYQzJok04JzTL1CA6aGhv5rfLW3PgqA+M2ChpZQnAC8h8i4ZFkBS8X5RqkDBHA7r4hej3K9A==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT" + }, + "node_modules/react": { + "version": "19.2.3", + "resolved": "https://registry.npmjs.org/react/-/react-19.2.3.tgz", + "integrity": "sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-chessboard": { + "version": "5.8.6", + "resolved": "https://registry.npmjs.org/react-chessboard/-/react-chessboard-5.8.6.tgz", + "integrity": "sha512-K4I6eWQJODIQlgdDu8uOl9EuwpBbaHPceT42cyAWw2VO9ODAm2GxqVfRZjTpOV74B3YCe7iNFA+z7IIIS4D7/A==", + "license": "MIT", + "dependencies": { + "@dnd-kit/core": "^6.3.1", + "@dnd-kit/modifiers": "^9.0.0" + }, + "engines": { + "node": ">=20.11.0", + "pnpm": ">=9.4.0" + }, + "peerDependencies": { + "react": "^19.0.0", + "react-dom": "^19.0.0" + } + }, + "node_modules/react-dom": { + "version": "19.2.3", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.3.tgz", + "integrity": "sha512-yELu4WmLPw5Mr/lmeEpox5rw3RETacE++JgHqQzd2dg+YbJuat3jH4ingc+WPZhxaoFzdv9y33G+F7Nl5O0GBg==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.27.0" + }, + "peerDependencies": { + "react": "^19.2.3" + } + }, + "node_modules/react-is": { + "version": "16.13.1", + "resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz", + "integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/reflect.getprototypeof": { + "version": "1.0.10", + "resolved": "https://registry.npmjs.org/reflect.getprototypeof/-/reflect.getprototypeof-1.0.10.tgz", + "integrity": "sha512-00o4I+DVrefhv+nX0ulyi3biSHCPDe+yLv5o/p6d/UVlirijB8E16FtfwSAi4g3tcqrQ4lRAqQSoFEZJehYEcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.9", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.7", + "get-proto": "^1.0.1", + "which-builtin-type": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/regexp.prototype.flags": { + "version": "1.5.4", + "resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz", + "integrity": "sha512-dYqgNSZbDwkaJ2ceRd9ojCGjBq+mOm9LmtXnAnEGyHhN/5R7iDW2TRw3h+o/jCFxus3P2LfWIIiwowAjANm7IA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "define-properties": "^1.2.1", + "es-errors": "^1.3.0", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "set-function-name": "^2.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve": { + "version": "1.22.11", + "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.11.tgz", + "integrity": "sha512-RfqAvLnMl313r7c9oclB1HhUEAezcpLjz95wFH4LVuhk9JF/r22qmVP9AMmOU4vMX7Q8pN8jwNg/CSpdFnMjTQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-core-module": "^2.16.1", + "path-parse": "^1.0.7", + "supports-preserve-symlinks-flag": "^1.0.0" + }, + "bin": { + "resolve": "bin/resolve" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/resolve-from": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/resolve-from/-/resolve-from-4.0.0.tgz", + "integrity": "sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/resolve-pkg-maps": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/resolve-pkg-maps/-/resolve-pkg-maps-1.0.0.tgz", + "integrity": "sha512-seS2Tj26TBVOC2NIc2rOe2y2ZO7efxITtLZcGSOnHHNOQ7CkiUBfw0Iw2ck6xkIhPwLhKNLS8BO+hEpngQlqzw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" + } + }, + "node_modules/reusify": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/reusify/-/reusify-1.1.0.tgz", + "integrity": "sha512-g6QUff04oZpHs0eG5p83rFLhHeV00ug/Yf9nZM6fLeUrPguBTkTQOdpAWWspMh55TZfVQDPaN3NQJfbVRAxdIw==", + "dev": true, + "license": "MIT", + "engines": { + "iojs": ">=1.0.0", + "node": ">=0.10.0" + } + }, + "node_modules/run-parallel": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz", + "integrity": "sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ], + "license": "MIT", + "dependencies": { + "queue-microtask": "^1.2.2" + } + }, + "node_modules/safe-array-concat": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/safe-array-concat/-/safe-array-concat-1.1.3.tgz", + "integrity": "sha512-AURm5f0jYEOydBj7VQlVvDrjeFgthDdEF5H1dP+6mNpoXOMo1quQqJ4wvJDyRZ9+pO3kGWoOdmV08cSv2aJV6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.2", + "get-intrinsic": "^1.2.6", + "has-symbols": "^1.1.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">=0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-push-apply": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/safe-push-apply/-/safe-push-apply-1.0.0.tgz", + "integrity": "sha512-iKE9w/Z7xCzUMIZqdBsp6pEQvwuEebH4vdpjcDWnyzaI6yl6O9FHvVpmGelvEHNsoY6wGblkxR6Zty/h00WiSA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "isarray": "^2.0.5" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/safe-regex-test": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/safe-regex-test/-/safe-regex-test-1.1.0.tgz", + "integrity": "sha512-x/+Cz4YrimQxQccJf5mKEbIa1NzeCRNI5Ecl/ekmlYaampdNLPalVyIcCZNNH3MvmqBugV5TMYZXv0ljslUlaw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "is-regex": "^1.2.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/scheduler": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", + "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/set-function-length": { + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/set-function-length/-/set-function-length-1.2.2.tgz", + "integrity": "sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "function-bind": "^1.1.2", + "get-intrinsic": "^1.2.4", + "gopd": "^1.0.1", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-function-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/set-function-name/-/set-function-name-2.0.2.tgz", + "integrity": "sha512-7PGFlmtwsEADb0WYyvCMa1t+yke6daIG4Wirafur5kcf+MhUnPms1UeR0CKQdTZD81yESwMHbtn+TR+dMviakQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-data-property": "^1.1.4", + "es-errors": "^1.3.0", + "functions-have-names": "^1.2.3", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/set-proto": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/set-proto/-/set-proto-1.0.0.tgz", + "integrity": "sha512-RJRdvCo6IAnPdsvP/7m6bsQqNnn1FCBX5ZNtFL98MmFF/4xAIJTIg1YbHW5DC2W5SKZanrC6i4HsJqlajw/dZw==", + "dev": true, + "license": "MIT", + "dependencies": { + "dunder-proto": "^1.0.1", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/sharp": { + "version": "0.34.5", + "resolved": "https://registry.npmjs.org/sharp/-/sharp-0.34.5.tgz", + "integrity": "sha512-Ou9I5Ft9WNcCbXrU9cMgPBcCK8LiwLqcbywW3t4oDV37n1pzpuNLsYiAV8eODnjbtQlSDwZ2cUEeQz4E54Hltg==", + "hasInstallScript": true, + "license": "Apache-2.0", + "optional": true, + "dependencies": { + "@img/colour": "^1.0.0", + "detect-libc": "^2.1.2", + "semver": "^7.7.3" + }, + "engines": { + "node": "^18.17.0 || ^20.3.0 || >=21.0.0" + }, + "funding": { + "url": "https://opencollective.com/libvips" + }, + "optionalDependencies": { + "@img/sharp-darwin-arm64": "0.34.5", + "@img/sharp-darwin-x64": "0.34.5", + "@img/sharp-libvips-darwin-arm64": "1.2.4", + "@img/sharp-libvips-darwin-x64": "1.2.4", + "@img/sharp-libvips-linux-arm": "1.2.4", + "@img/sharp-libvips-linux-arm64": "1.2.4", + "@img/sharp-libvips-linux-ppc64": "1.2.4", + "@img/sharp-libvips-linux-riscv64": "1.2.4", + "@img/sharp-libvips-linux-s390x": "1.2.4", + "@img/sharp-libvips-linux-x64": "1.2.4", + "@img/sharp-libvips-linuxmusl-arm64": "1.2.4", + "@img/sharp-libvips-linuxmusl-x64": "1.2.4", + "@img/sharp-linux-arm": "0.34.5", + "@img/sharp-linux-arm64": "0.34.5", + "@img/sharp-linux-ppc64": "0.34.5", + "@img/sharp-linux-riscv64": "0.34.5", + "@img/sharp-linux-s390x": "0.34.5", + "@img/sharp-linux-x64": "0.34.5", + "@img/sharp-linuxmusl-arm64": "0.34.5", + "@img/sharp-linuxmusl-x64": "0.34.5", + "@img/sharp-wasm32": "0.34.5", + "@img/sharp-win32-arm64": "0.34.5", + "@img/sharp-win32-ia32": "0.34.5", + "@img/sharp-win32-x64": "0.34.5" + } + }, + "node_modules/sharp/node_modules/semver": { + "version": "7.7.3", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.7.3.tgz", + "integrity": "sha512-SdsKMrI9TdgjdweUSR9MweHA4EJ8YxHn8DFaDisvhVlUOe4BF1tLD7GAj0lIqWVl+dPb/rExr0Btby5loQm20Q==", + "license": "ISC", + "optional": true, + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/side-channel": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/side-channel/-/side-channel-1.1.0.tgz", + "integrity": "sha512-ZX99e6tRweoUXqR+VBrslhda51Nh5MTQwou5tnUDgbtyM0dBgmhEDtWGP/xbKn6hqfPRHujUNwz5fy/wbbhnpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3", + "side-channel-list": "^1.0.0", + "side-channel-map": "^1.0.1", + "side-channel-weakmap": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-list": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/side-channel-list/-/side-channel-list-1.0.0.tgz", + "integrity": "sha512-FCLHtRD/gnpCiCHEiJLOwdmFP+wzCmDEkc9y7NsYxeF4u7Btsn1ZuwgwJGxImImHicJArLP4R0yX4c2KCrMrTA==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-map": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/side-channel-map/-/side-channel-map-1.0.1.tgz", + "integrity": "sha512-VCjCNfgMsby3tTdo02nbjtM/ewra6jPHmpThenkTYh8pG9ucZ/1P8So4u4FGBek/BjpOVsDCMoLA/iuBKIFXRA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/side-channel-weakmap": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/side-channel-weakmap/-/side-channel-weakmap-1.0.2.tgz", + "integrity": "sha512-WPS/HvHQTYnHisLo9McqBHOJk2FkHO/tlpvldyrnem4aeQp4hai3gythswg6p01oSoTl58rcpiFAjF2br2Ak2A==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "es-errors": "^1.3.0", + "get-intrinsic": "^1.2.5", + "object-inspect": "^1.13.3", + "side-channel-map": "^1.0.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/stable-hash": { + "version": "0.0.5", + "resolved": "https://registry.npmjs.org/stable-hash/-/stable-hash-0.0.5.tgz", + "integrity": "sha512-+L3ccpzibovGXFK+Ap/f8LOS0ahMrHTf3xu7mMLSpEGU0EO9ucaysSylKo9eRDFNhWve/y275iPmIZ4z39a9iA==", + "dev": true, + "license": "MIT" + }, + "node_modules/stop-iteration-iterator": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/stop-iteration-iterator/-/stop-iteration-iterator-1.1.0.tgz", + "integrity": "sha512-eLoXW/DHyl62zxY4SCaIgnRhuMr6ri4juEYARS8E6sCEqzKpOiE521Ucofdx+KnDZl5xmvGYaaKCk5FEOxJCoQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "es-errors": "^1.3.0", + "internal-slot": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/string.prototype.includes": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/string.prototype.includes/-/string.prototype.includes-2.0.1.tgz", + "integrity": "sha512-o7+c9bW6zpAdJHTtujeePODAhkuicdAryFsfVKwA+wGw89wJ4GTY484WTucM9hLtDEOpOvI+aHnzqnC5lHp4Rg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.3" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/string.prototype.matchall": { + "version": "4.0.12", + "resolved": "https://registry.npmjs.org/string.prototype.matchall/-/string.prototype.matchall-4.0.12.tgz", + "integrity": "sha512-6CC9uyBL+/48dYizRf7H7VAYCMCNTBeM78x/VTUe9bFEaxBepPJDa1Ow99LqI/1yF7kuy7Q3cQsYMrcjGUcskA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.3", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.6", + "es-errors": "^1.3.0", + "es-object-atoms": "^1.0.0", + "get-intrinsic": "^1.2.6", + "gopd": "^1.2.0", + "has-symbols": "^1.1.0", + "internal-slot": "^1.1.0", + "regexp.prototype.flags": "^1.5.3", + "set-function-name": "^2.0.2", + "side-channel": "^1.1.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.repeat": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/string.prototype.repeat/-/string.prototype.repeat-1.0.0.tgz", + "integrity": "sha512-0u/TldDbKD8bFCQ/4f5+mNRrXwZ8hg2w7ZR8wa16e8z9XpePWl3eGEcUD0OXpEH/VJH/2G3gjUtR3ZOiBe2S/w==", + "dev": true, + "license": "MIT", + "dependencies": { + "define-properties": "^1.1.3", + "es-abstract": "^1.17.5" + } + }, + "node_modules/string.prototype.trim": { + "version": "1.2.10", + "resolved": "https://registry.npmjs.org/string.prototype.trim/-/string.prototype.trim-1.2.10.tgz", + "integrity": "sha512-Rs66F0P/1kedk5lyYyH9uBzuiI/kNRmwJAR9quK6VOtIpZ2G+hMZd+HQbbv25MgCA6gEffoMZYxlTod4WcdrKA==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.2", + "define-data-property": "^1.1.4", + "define-properties": "^1.2.1", + "es-abstract": "^1.23.5", + "es-object-atoms": "^1.0.0", + "has-property-descriptors": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimend": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/string.prototype.trimend/-/string.prototype.trimend-1.0.9.tgz", + "integrity": "sha512-G7Ok5C6E/j4SGfyLCloXTrngQIQU3PWtXGst3yM7Bea9FRURf1S42ZHlZZtsNque2FN2PoUhfZXYLNWwEr4dLQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "call-bound": "^1.0.2", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/string.prototype.trimstart": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/string.prototype.trimstart/-/string.prototype.trimstart-1.0.8.tgz", + "integrity": "sha512-UXSH262CSZY1tfu3G3Secr6uGLCFVPMhIqHjlgCUtCCcgihYc/xKs9djMTMUOb2j1mVSeU8EU6NWc/iQKU6Gfg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "define-properties": "^1.2.1", + "es-object-atoms": "^1.0.0" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/strip-bom": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/strip-bom/-/strip-bom-3.0.0.tgz", + "integrity": "sha512-vavAMRXOgBVNF6nyEEmL3DBK19iRpDcoIwW+swQ+CbGiu7lju6t+JklA1MHweoWtadgt4ISVUsXLyDq34ddcwA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/styled-jsx": { + "version": "5.1.6", + "resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.6.tgz", + "integrity": "sha512-qSVyDTeMotdvQYoHWLNGwRFJHC+i+ZvdBRYosOFgC+Wg1vx4frN2/RG/NA7SYqqvKNLf39P2LSRA2pu6n0XYZA==", + "license": "MIT", + "dependencies": { + "client-only": "0.0.1" + }, + "engines": { + "node": ">= 12.0.0" + }, + "peerDependencies": { + "react": ">= 16.8.0 || 17.x.x || ^18.0.0-0 || ^19.0.0-0" + }, + "peerDependenciesMeta": { + "@babel/core": { + "optional": true + }, + "babel-plugin-macros": { + "optional": true + } + } + }, + "node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dev": true, + "license": "MIT", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/supports-preserve-symlinks-flag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz", + "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/tailwindcss": { + "version": "4.1.18", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.1.18.tgz", + "integrity": "sha512-4+Z+0yiYyEtUVCScyfHCxOYP06L5Ne+JiHhY2IjR2KWMIWhJOYZKLSGZaP5HkZ8+bY0cxfzwDE5uOmzFXyIwxw==", + "dev": true, + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.0.tgz", + "integrity": "sha512-g9ljZiwki/LfxmQADO3dEY1CbpmXT5Hm2fJ+QaGKwSXUylMybePR7/67YW7jOrrvjEgL1Fmz5kzyAjWVWLlucg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.15", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.15.tgz", + "integrity": "sha512-j2Zq4NyQYG5XMST4cbs02Ak8iJUdxRM0XI5QyxXuZOzKOINmWurp3smXu3y5wDcJrptwpSjgXHzIQxR0omXljQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.3" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/tinyglobby/node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/tinyglobby/node_modules/picomatch": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.3.tgz", + "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/ts-api-utils": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.1.0.tgz", + "integrity": "sha512-CUgTZL1irw8u29bzrOD/nH85jqyc74D6SshFgujOIA7osm2Rz7dYH77agkx7H4FBNxDq7Cjf+IjaX/8zwFW+ZQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, + "node_modules/tsconfig-paths": { + "version": "3.15.0", + "resolved": "https://registry.npmjs.org/tsconfig-paths/-/tsconfig-paths-3.15.0.tgz", + "integrity": "sha512-2Ac2RgzDe/cn48GvOe3M+o82pEFewD3UPbyoUHHdKasHwJKjds4fLXWf/Ux5kATBKN20oaFGu+jbElp1pos0mg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@types/json5": "^0.0.29", + "json5": "^1.0.2", + "minimist": "^1.2.6", + "strip-bom": "^3.0.0" + } + }, + "node_modules/tsconfig-paths/node_modules/json5": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/json5/-/json5-1.0.2.tgz", + "integrity": "sha512-g1MWMLBiz8FKi1e4w0UyVL3w+iJceWAFBAaBnnGKOpNa5f8TLktkbre1+s6oICydWAm+HRUGTmI+//xv2hvXYA==", + "dev": true, + "license": "MIT", + "dependencies": { + "minimist": "^1.2.0" + }, + "bin": { + "json5": "lib/cli.js" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "license": "0BSD" + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/typed-array-buffer": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-buffer/-/typed-array-buffer-1.0.3.tgz", + "integrity": "sha512-nAYYwfY3qnzX30IkA6AQZjVbtK6duGontcQm1WSG1MD94YLqK0515GNApXkoxKOWMusVssAHWLh9SeaoefYFGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "es-errors": "^1.3.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + } + }, + "node_modules/typed-array-byte-length": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/typed-array-byte-length/-/typed-array-byte-length-1.0.3.tgz", + "integrity": "sha512-BaXgOuIxz8n8pIq3e7Atg/7s+DpiYrxn4vdot3w9KbnBhcRQq6o3xemQdIfynqSeXeDrF32x+WvfzmOjPiY9lg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.8", + "for-each": "^0.3.3", + "gopd": "^1.2.0", + "has-proto": "^1.2.0", + "is-typed-array": "^1.1.14" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-byte-offset": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/typed-array-byte-offset/-/typed-array-byte-offset-1.0.4.tgz", + "integrity": "sha512-bTlAFB/FBYMcuX81gbL4OcpH5PmlFHqlCCpAl8AlEzMz5k53oNDvN8p1PNOWLEmI2x4orp3raOFB51tv9X+MFQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "for-each": "^0.3.3", + "gopd": "^1.2.0", + "has-proto": "^1.2.0", + "is-typed-array": "^1.1.15", + "reflect.getprototypeof": "^1.0.9" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typed-array-length": { + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/typed-array-length/-/typed-array-length-1.0.7.tgz", + "integrity": "sha512-3KS2b+kL7fsuk/eJZ7EQdnEmQoaho/r6KUef7hxvltNA5DR8NAUM+8wJMbJyZ4G9/7i3v5zPBIMN5aybAh2/Jg==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bind": "^1.0.7", + "for-each": "^0.3.3", + "gopd": "^1.0.1", + "is-typed-array": "^1.1.13", + "possible-typed-array-names": "^1.0.0", + "reflect.getprototypeof": "^1.0.6" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/typescript": { + "version": "5.9.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", + "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/typescript-eslint": { + "version": "8.50.1", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.50.1.tgz", + "integrity": "sha512-ytTHO+SoYSbhAH9CrYnMhiLx8To6PSSvqnvXyPUgPETCvB6eBKmTI9w6XMPS3HsBRGkwTVBX+urA8dYQx6bHfQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.50.1", + "@typescript-eslint/parser": "8.50.1", + "@typescript-eslint/typescript-estree": "8.50.1", + "@typescript-eslint/utils": "8.50.1" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0", + "typescript": ">=4.8.4 <6.0.0" + } + }, + "node_modules/unbox-primitive": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/unbox-primitive/-/unbox-primitive-1.1.0.tgz", + "integrity": "sha512-nWJ91DjeOkej/TA8pXQ3myruKpKEYgqvpw9lz4OPHj/NWFNluYrjbz9j01CJ8yKQd2g4jFoOkINCTW2I5LEEyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.3", + "has-bigints": "^1.0.2", + "has-symbols": "^1.1.0", + "which-boxed-primitive": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/undici-types": { + "version": "6.21.0", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.21.0.tgz", + "integrity": "sha512-iwDZqg0QAGrg9Rav5H4n0M64c3mkR59cJ6wQp+7C4nI0gsmExaedaYLNO44eT4AtBBwjbTiGPMlt2Md0T9H9JQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/unrs-resolver": { + "version": "1.11.1", + "resolved": "https://registry.npmjs.org/unrs-resolver/-/unrs-resolver-1.11.1.tgz", + "integrity": "sha512-bSjt9pjaEBnNiGgc9rUiHGKv5l4/TGzDmYw3RhnkJGtLhbnnA/5qJj7x3dNDCRx/PJxu774LlH8lCOlB4hEfKg==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "napi-postinstall": "^0.3.0" + }, + "funding": { + "url": "https://opencollective.com/unrs-resolver" + }, + "optionalDependencies": { + "@unrs/resolver-binding-android-arm-eabi": "1.11.1", + "@unrs/resolver-binding-android-arm64": "1.11.1", + "@unrs/resolver-binding-darwin-arm64": "1.11.1", + "@unrs/resolver-binding-darwin-x64": "1.11.1", + "@unrs/resolver-binding-freebsd-x64": "1.11.1", + "@unrs/resolver-binding-linux-arm-gnueabihf": "1.11.1", + "@unrs/resolver-binding-linux-arm-musleabihf": "1.11.1", + "@unrs/resolver-binding-linux-arm64-gnu": "1.11.1", + "@unrs/resolver-binding-linux-arm64-musl": "1.11.1", + "@unrs/resolver-binding-linux-ppc64-gnu": "1.11.1", + "@unrs/resolver-binding-linux-riscv64-gnu": "1.11.1", + "@unrs/resolver-binding-linux-riscv64-musl": "1.11.1", + "@unrs/resolver-binding-linux-s390x-gnu": "1.11.1", + "@unrs/resolver-binding-linux-x64-gnu": "1.11.1", + "@unrs/resolver-binding-linux-x64-musl": "1.11.1", + "@unrs/resolver-binding-wasm32-wasi": "1.11.1", + "@unrs/resolver-binding-win32-arm64-msvc": "1.11.1", + "@unrs/resolver-binding-win32-ia32-msvc": "1.11.1", + "@unrs/resolver-binding-win32-x64-msvc": "1.11.1" + } + }, + "node_modules/update-browserslist-db": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/which-boxed-primitive": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/which-boxed-primitive/-/which-boxed-primitive-1.1.1.tgz", + "integrity": "sha512-TbX3mj8n0odCBFVlY8AxkqcHASw3L60jIuF8jFP78az3C2YhmGvqbHBpAjTRH2/xqYunrJ9g1jSyjCjpoWzIAA==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-bigint": "^1.1.0", + "is-boolean-object": "^1.2.1", + "is-number-object": "^1.1.1", + "is-string": "^1.1.1", + "is-symbol": "^1.1.1" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-builtin-type": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/which-builtin-type/-/which-builtin-type-1.2.1.tgz", + "integrity": "sha512-6iBczoX+kDQ7a3+YJBnh3T+KZRxM/iYNPXicqk66/Qfm1b93iu+yOImkg0zHbj5LNOcNv1TEADiZ0xa34B4q6Q==", + "dev": true, + "license": "MIT", + "dependencies": { + "call-bound": "^1.0.2", + "function.prototype.name": "^1.1.6", + "has-tostringtag": "^1.0.2", + "is-async-function": "^2.0.0", + "is-date-object": "^1.1.0", + "is-finalizationregistry": "^1.1.0", + "is-generator-function": "^1.0.10", + "is-regex": "^1.2.1", + "is-weakref": "^1.0.2", + "isarray": "^2.0.5", + "which-boxed-primitive": "^1.1.0", + "which-collection": "^1.0.2", + "which-typed-array": "^1.1.16" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-collection": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/which-collection/-/which-collection-1.0.2.tgz", + "integrity": "sha512-K4jVyjnBdgvc86Y6BkaLZEN933SwYOuBFkdmBu9ZfkcAbdVbpITnDmjvZ/aQjRXQrv5EPkTnD1s39GiiqbngCw==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-map": "^2.0.3", + "is-set": "^2.0.3", + "is-weakmap": "^2.0.2", + "is-weakset": "^2.0.3" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/which-typed-array": { + "version": "1.1.19", + "resolved": "https://registry.npmjs.org/which-typed-array/-/which-typed-array-1.1.19.tgz", + "integrity": "sha512-rEvr90Bck4WZt9HHFC4DJMsjvu7x+r6bImz0/BrbWb7A2djJ8hnZMrWnHo9F8ssv0OMErasDhftrfROTyqSDrw==", + "dev": true, + "license": "MIT", + "dependencies": { + "available-typed-arrays": "^1.0.7", + "call-bind": "^1.0.8", + "call-bound": "^1.0.4", + "for-each": "^0.3.5", + "get-proto": "^1.0.1", + "gopd": "^1.2.0", + "has-tostringtag": "^1.0.2" + }, + "engines": { + "node": ">= 0.4" + }, + "funding": { + "url": "https://github.com/sponsors/ljharb" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.2.1.tgz", + "integrity": "sha512-0wZ1IRqGGhMP76gLqz8EyfBXKk0J2qo2+H3fi4mcUP/KtTocoX08nmIAHl1Z2kJIZbZee8KOpBCSNPRgauucjw==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-validation-error": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/zod-validation-error/-/zod-validation-error-4.0.2.tgz", + "integrity": "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + } + } + } +} diff --git a/frontend/package.json b/frontend/package.json new file mode 100644 index 0000000000000000000000000000000000000000..8322115f635b612299d3f0a39de0c061c3babe67 --- /dev/null +++ b/frontend/package.json @@ -0,0 +1,28 @@ +{ + "name": "frontend", + "version": "0.1.0", + "private": true, + "scripts": { + "dev": "next dev", + "build": "next build", + "start": "next start", + "lint": "eslint" + }, + "dependencies": { + "chess.js": "^1.4.0", + "next": "16.1.1", + "react": "19.2.3", + "react-chessboard": "^5.8.6", + "react-dom": "19.2.3" + }, + "devDependencies": { + "@tailwindcss/postcss": "^4", + "@types/node": "^20", + "@types/react": "^19", + "@types/react-dom": "^19", + "eslint": "^9", + "eslint-config-next": "16.1.1", + "tailwindcss": "^4", + "typescript": "^5" + } +} diff --git a/frontend/postcss.config.mjs b/frontend/postcss.config.mjs new file mode 100644 index 0000000000000000000000000000000000000000..61e36849cf7cfa9f1f71b4a3964a4953e3e243d3 --- /dev/null +++ b/frontend/postcss.config.mjs @@ -0,0 +1,7 @@ +const config = { + plugins: { + "@tailwindcss/postcss": {}, + }, +}; + +export default config; diff --git a/frontend/public/file.svg b/frontend/public/file.svg new file mode 100644 index 0000000000000000000000000000000000000000..004145cddf3f9db91b57b9cb596683c8eb420862 --- /dev/null +++ b/frontend/public/file.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/public/globe.svg b/frontend/public/globe.svg new file mode 100644 index 0000000000000000000000000000000000000000..567f17b0d7c7fb662c16d4357dd74830caf2dccb --- /dev/null +++ b/frontend/public/globe.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/public/next.svg b/frontend/public/next.svg new file mode 100644 index 0000000000000000000000000000000000000000..5174b28c565c285e3e312ec5178be64fbeca8398 --- /dev/null +++ b/frontend/public/next.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/public/vercel.svg b/frontend/public/vercel.svg new file mode 100644 index 0000000000000000000000000000000000000000..77053960334e2e34dc584dea8019925c3b4ccca9 --- /dev/null +++ b/frontend/public/vercel.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/public/window.svg b/frontend/public/window.svg new file mode 100644 index 0000000000000000000000000000000000000000..b2b2a44f6ebc70c450043c05a002e7a93ba5d651 --- /dev/null +++ b/frontend/public/window.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/frontend/tsconfig.json b/frontend/tsconfig.json new file mode 100644 index 0000000000000000000000000000000000000000..3a13f90a773b0facb675bf5b1a8239c8f33d36f5 --- /dev/null +++ b/frontend/tsconfig.json @@ -0,0 +1,34 @@ +{ + "compilerOptions": { + "target": "ES2017", + "lib": ["dom", "dom.iterable", "esnext"], + "allowJs": true, + "skipLibCheck": true, + "strict": true, + "noEmit": true, + "esModuleInterop": true, + "module": "esnext", + "moduleResolution": "bundler", + "resolveJsonModule": true, + "isolatedModules": true, + "jsx": "react-jsx", + "incremental": true, + "plugins": [ + { + "name": "next" + } + ], + "paths": { + "@/*": ["./*"] + } + }, + "include": [ + "next-env.d.ts", + "**/*.ts", + "**/*.tsx", + ".next/types/**/*.ts", + ".next/dev/types/**/*.ts", + "**/*.mts" + ], + "exclude": ["node_modules"] +} diff --git a/model.int8.onnx b/model.int8.onnx new file mode 100644 index 0000000000000000000000000000000000000000..0168573244bd1110bc221c360b4a7044182a4f6d --- /dev/null +++ b/model.int8.onnx @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:fd429262f8c7fae72e7cd6f9298c7a49c2829bf860dea044dbf17b5ee1fc599a +size 15933605 diff --git a/model/model.safetensors b/model/model.safetensors deleted file mode 100644 index f032d8a02c9a9aa245f5346833d8562341b968bb..0000000000000000000000000000000000000000 --- a/model/model.safetensors +++ /dev/null @@ -1,3 +0,0 @@ -version https://git-lfs.github.com/spec/v1 -oid sha256:732158f7144cf7a09059add087ac3ee3cbdede94b01cdd04a518b7df11fdadfa -size 46631616 diff --git a/model/model_config.json b/model/model_config.json deleted file mode 100644 index 5fb553210b756b36efdfdada49759ccd7e0784ee..0000000000000000000000000000000000000000 --- a/model/model_config.json +++ /dev/null @@ -1,9 +0,0 @@ -{ - "vocab_size": 13, - "embed_dim": 256, - "nb_transformer_layers": 16, - "num_heads": 8, - "dropout": 0.05, - "kvq_bias": false, - "layer_drop": 0.1 -} \ No newline at end of file diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index c02378e950827569aae0d2122559bd2b533e26a5..0000000000000000000000000000000000000000 --- a/requirements.txt +++ /dev/null @@ -1,10 +0,0 @@ -# Slim CPU runtime for the Space. The chesstransformer package source is -# vendored next to app.py (see prepare.sh), so only the runtime deps of the -# inference path are needed here — not the full training stack. -torch>=2.2 -numpy>=1.26 -python-chess>=1.999 -safetensors>=0.4 -tokenizers>=0.15 -gradio>=5.49.0 -gradio-chessboard>=0.0.10 diff --git a/rust/Cargo.lock b/rust/Cargo.lock new file mode 100644 index 0000000000000000000000000000000000000000..9d5316e7efb195c2c87166ad5b9842a33e55fda7 --- /dev/null +++ b/rust/Cargo.lock @@ -0,0 +1,2648 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aho-corasick" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301" +dependencies = [ + "memchr", +] + +[[package]] +name = "anstream" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d" +dependencies = [ + "anstyle", + "anstyle-parse", + "anstyle-query", + "anstyle-wincon", + "colorchoice", + "is_terminal_polyfill", + "utf8parse", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "anstyle-parse" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e" +dependencies = [ + "utf8parse", +] + +[[package]] +name = "anstyle-query" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "anstyle-wincon" +version = "3.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d" +dependencies = [ + "anstyle", + "once_cell_polyfill", + "windows-sys 0.61.2", +] + +[[package]] +name = "anyhow" +version = "1.0.102" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c" + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-util", + "itoa", + "matchit", + "memchr", + "mime", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "sync_wrapper", + "tokio", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64ct" +version = "1.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2af50177e190e07a26ab74f8b1efbfe2ef87da2116221318cb1c2e82baf7de06" + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" + +[[package]] +name = "btoi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dd6407f73a9b8b6162d8a2ef999fe6afd7cc15902ebf42c5cd296addf17e0ad" +dependencies = [ + "num-traits", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "bytes" +version = "1.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" + +[[package]] +name = "cc" +version = "1.2.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dad887fd958be91b5098c0248def011f4523ab786cd411be668777e55063501f" +dependencies = [ + "find-msvc-tools", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "cfg_aliases" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724" + +[[package]] +name = "chess-core" +version = "0.1.0" +dependencies = [ + "anyhow", + "rand 0.8.6", + "shakmaty", + "shakmaty-syzygy", +] + +[[package]] +name = "clap" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51" +dependencies = [ + "clap_builder", + "clap_derive", +] + +[[package]] +name = "clap_builder" +version = "4.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f" +dependencies = [ + "anstream", + "anstyle", + "clap_lex", + "strsim", +] + +[[package]] +name = "clap_derive" +version = "4.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "clap_lex" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9" + +[[package]] +name = "colorchoice" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570" + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "ct-bot" +version = "0.1.0" +dependencies = [ + "anyhow", + "axum", + "chess-core", + "clap", + "env_logger", + "futures-util", + "log", + "ndarray 0.17.2", + "ort", + "rand 0.8.6", + "reqwest", + "serde", + "serde_json", + "shakmaty", + "shakmaty-syzygy", + "tokio", + "tower-http", +] + +[[package]] +name = "der" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "71fd89660b2dc699704064e59e9dba0147b903e85319429e131620d022be411b" +dependencies = [ + "pem-rfc7468", + "zeroize", +] + +[[package]] +name = "displaydoc" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "env_filter" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e90c2accc4b07a8456ea0debdc2e7587bdd890680d71173a15d4ae604f6eef" +dependencies = [ + "log", + "regex", +] + +[[package]] +name = "env_logger" +version = "0.11.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0621c04f2196ac3f488dd583365b9c09be011a4ab8b9f37248ffcc8f6198b56a" +dependencies = [ + "anstream", + "anstyle", + "env_filter", + "jiff", + "log", +] + +[[package]] +name = "equivalent" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "fastrand" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6" + +[[package]] +name = "find-msvc-tools" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures-channel" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d" +dependencies = [ + "futures-core", +] + +[[package]] +name = "futures-core" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d" + +[[package]] +name = "futures-io" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718" + +[[package]] +name = "futures-macro" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e835b70203e41293343137df5c0664546da5745f82ec9b84d40be8336958447b" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "futures-sink" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893" + +[[package]] +name = "futures-task" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393" + +[[package]] +name = "futures-util" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6" +dependencies = [ + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 5.3.0", + "wasip2", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", + "wasip2", + "wasip3", +] + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hmac-sha256" +version = "1.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec9d92d097f4749b64e8cc33d924d9f40a2d4eb91402b458014b781f5733d60f" + +[[package]] +name = "http" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "http-range-header" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9171a2ea8a68358193d15dd5d70c1c10a2afc3e7e4c5bc92bc9f025cebd7359c" + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498" +dependencies = [ + "atomic-waker", + "bytes", + "futures-channel", + "futures-core", + "http", + "http-body", + "httparse", + "httpdate", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0" +dependencies = [ + "base64", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[package]] +name = "icu_collections" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_locale_core" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_normalizer" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38" + +[[package]] +name = "icu_properties" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de" +dependencies = [ + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14" + +[[package]] +name = "icu_provider" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421" +dependencies = [ + "displaydoc", + "icu_locale_core", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "id-arena" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "indexmap" +version = "2.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", + "serde", + "serde_core", +] + +[[package]] +name = "indoc" +version = "2.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706" +dependencies = [ + "rustversion", +] + +[[package]] +name = "ipnet" +version = "2.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2" + +[[package]] +name = "is_terminal_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695" + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jiff" +version = "0.2.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4603d3033e49e2b0e31229fcab20a5d40089c607d975cd9c80551dc69eed9102" +dependencies = [ + "jiff-static", + "log", + "portable-atomic", + "portable-atomic-util", + "serde_core", +] + +[[package]] +name = "jiff-static" +version = "0.2.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "782d32378dddf207193ac91cefb848ad41abb58195c95168e1291227a0832b47" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "js-sys" +version = "0.3.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2025f20d7a4fa7785846e7b63d10a76d3f1cee98ee5cb79ea59703f95e42162" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "leb128fmt" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2" + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "libloading" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "754ca22de805bb5744484a5b151a9e1a8e837d5dc232c2d7d8c2e3492edc8b60" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0" + +[[package]] +name = "log" +version = "0.4.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "953f07c43838f8e6f9758cab68bf5bed85465e7587ebe0b823f1bcd81978ad3a" + +[[package]] +name = "lru-slab" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154" + +[[package]] +name = "lzma-rust2" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e20f57f9918e5bd7bc58c22cdd70a6afc7375d4dd9683af5f2b34bd3d2bba619" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "matrixmultiply" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06de3016e9fae57a36fd14dba131fccf49f74b40b7fbdb472f96e361ec71a08" +dependencies = [ + "autocfg", + "rawpointer", +] + +[[package]] +name = "memchr" +version = "2.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "mio" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda" +dependencies = [ + "libc", + "wasi", + "windows-sys 0.61.2", +] + +[[package]] +name = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "ndarray" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "882ed72dce9365842bf196bdeedf5055305f11fc8c03dee7bb0194a6cad34841" +dependencies = [ + "matrixmultiply", + "num-complex", + "num-integer", + "num-traits", + "portable-atomic", + "portable-atomic-util", + "rawpointer", +] + +[[package]] +name = "ndarray" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520080814a7a6b4a6e9070823bb24b4531daac8c4627e08ba5de8c5ef2f2752d" +dependencies = [ + "matrixmultiply", + "num-complex", + "num-integer", + "num-traits", + "portable-atomic", + "portable-atomic-util", + "rawpointer", +] + +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "numpy" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b94caae805f998a07d33af06e6a3891e38556051b8045c615470a71590e13e78" +dependencies = [ + "libc", + "ndarray 0.16.1", + "num-complex", + "num-integer", + "num-traits", + "pyo3", + "rustc-hash", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "once_cell_polyfill" +version = "1.70.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" + +[[package]] +name = "openssl" +version = "0.10.81" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77823a27f0babb03091cb9ed9ef80af3b39dbc82f97e8fa530374b7dafd87a45" +dependencies = [ + "bitflags", + "cfg-if", + "foreign-types", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "openssl-probe" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe" + +[[package]] +name = "openssl-sys" +version = "0.9.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b47e7e6bb2c38cd930d25a23b40fa52e068c10e85f3e03a7f5ba5aaca5713695" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "ort" +version = "2.0.0-rc.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4336a1e2b38848325241c72889086886004e589b7c74f335e60a8e8db5138a0b" +dependencies = [ + "libloading", + "ndarray 0.17.2", + "ort-sys", + "smallvec", + "tracing", + "ureq", +] + +[[package]] +name = "ort-sys" +version = "2.0.0-rc.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf211e3776eea6aec988552fa118dd746d70e1b1e5e244058d1c98015f3e5872" +dependencies = [ + "hmac-sha256", + "lzma-rust2", + "ureq", +] + +[[package]] +name = "pem-rfc7468" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6305423e0e7738146434843d1694d621cce767262b2a86910beab705e4493d9" +dependencies = [ + "base64ct", +] + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pkg-config" +version = "0.3.33" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19f132c84eca552bf34cab8ec81f1c1dcc229b811638f9d283dceabe58c5569e" + +[[package]] +name = "portable-atomic" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" + +[[package]] +name = "portable-atomic-util" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564" +dependencies = [ + "zerovec", +] + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn", +] + +[[package]] +name = "proc-macro2" +version = "1.0.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pyo3" +version = "0.23.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7778bffd85cf38175ac1f545509665d0b9b92a198ca7941f131f85f7a4f9a872" +dependencies = [ + "cfg-if", + "indoc", + "libc", + "memoffset", + "once_cell", + "portable-atomic", + "pyo3-build-config", + "pyo3-ffi", + "pyo3-macros", + "unindent", +] + +[[package]] +name = "pyo3-build-config" +version = "0.23.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94f6cbe86ef3bf18998d9df6e0f3fc1050a8c5efa409bf712e661a4366e010fb" +dependencies = [ + "once_cell", + "target-lexicon", +] + +[[package]] +name = "pyo3-ffi" +version = "0.23.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f1b4c431c0bb1c8fb0a338709859eed0d030ff6daa34368d3b152a63dfdd8d" +dependencies = [ + "libc", + "pyo3-build-config", +] + +[[package]] +name = "pyo3-macros" +version = "0.23.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbc2201328f63c4710f68abdf653c89d8dbc2858b88c5d88b0ff38a75288a9da" +dependencies = [ + "proc-macro2", + "pyo3-macros-backend", + "quote", + "syn", +] + +[[package]] +name = "pyo3-macros-backend" +version = "0.23.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fca6726ad0f3da9c9de093d6f116a93c1a38e417ed73bf138472cf4064f72028" +dependencies = [ + "heck", + "proc-macro2", + "pyo3-build-config", + "quote", + "syn", +] + +[[package]] +name = "quinn" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash", + "rustls", + "socket2", + "thiserror", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "434b42fec591c96ef50e21e886936e66d3cc3f737104fdb9b737c40ffb94c098" +dependencies = [ + "bytes", + "getrandom 0.3.4", + "lru-slab", + "rand 0.9.4", + "ring", + "rustc-hash", + "rustls", + "rustls-pki-types", + "slab", + "thiserror", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.60.2", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +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 = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[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 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rawpointer" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" + +[[package]] +name = "regex" +version = "1.12.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" + +[[package]] +name = "rustix" +version = "1.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190" +dependencies = [ + "bitflags", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef86cd5876211988985292b91c96a8f2d298df24e75989a43a3c73f2d4d8168b" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30a7197ae7eb376e574fe940d068c30fe0462554a3ddbe4eca7838e049c937a9" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "schannel" +version = "0.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91c1b7e4904c873ef0710c1f407dde2e6287de2bebc1bbbf7d430bb7cbffd939" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "selfplay-core" +version = "0.1.0" +dependencies = [ + "chess-core", + "numpy", + "pyo3", + "rand 0.8.6", + "serde", + "serde_json", + "shakmaty", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.150" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "shakmaty" +version = "0.27.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f414cadc4e727893d1a3b0dca62aaef4c1c821dcbd969f0b10a92e12d684d53a" +dependencies = [ + "arrayvec", + "bitflags", + "btoi", + "nohash-hasher", + "serde", +] + +[[package]] +name = "shakmaty-syzygy" +version = "0.25.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c029d0ba61da1e7767d5b4e190b6adb9e9c6f72dc01e690e68aede6889d05c2d" +dependencies = [ + "arrayvec", + "bitflags", + "byteorder", + "libc", + "once_cell", + "rustc-hash", + "shakmaty", + "tracing", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "smallvec" +version = "1.15.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90" + +[[package]] +name = "socket2" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "socks" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0c3dbbd9ae980613c6dd8e28a9407b50509d3803b57624d5dfe8315218cd58b" +dependencies = [ + "byteorder", + "libc", + "winapi", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "strsim" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f" + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[package]] +name = "synstructure" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "target-lexicon" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.2", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "thiserror" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4" +dependencies = [ + "thiserror-impl", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tinystr" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +dependencies = [ + "tinyvec_macros", +] + +[[package]] +name = "tinyvec_macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20" + +[[package]] +name = "tokio" +version = "1.52.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "signal-hook-registry", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" +dependencies = [ + "bytes", + "futures-core", + "futures-sink", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags", + "bytes", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "http-range-header", + "httpdate", + "mime", + "mime_guess", + "percent-encoding", + "pin-project-lite", + "tokio", + "tokio-util", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "unindent" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7264e107f553ccae879d21fbea1d6724ac785e8c3bfc762137959b5802826ef3" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[package]] +name = "ureq" +version = "3.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dea7109cdcd5864d4eeb1b58a1648dc9bf520360d7af16ec26d0a9354bafcfc0" +dependencies = [ + "base64", + "der", + "log", + "native-tls", + "percent-encoding", + "rustls-pki-types", + "socks", + "ureq-proto", + "utf8-zero", + "webpki-root-certs", +] + +[[package]] +name = "ureq-proto" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e994ba84b0bd1b1b0cf92878b7ef898a5c1760108fe7b6010327e274917a808c" +dependencies = [ + "base64", + "http", + "httparse", + "log", +] + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "utf8-zero" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8c0a043c9540bae7c578c88f91dda8bd82e59ae27c21baca69c8b191aaf5a6e" + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "utf8parse" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "want" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e" +dependencies = [ + "try-lock", +] + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen 0.57.1", +] + +[[package]] +name = "wasip3" +version = "0.4.0+wasi-0.3.0-rc-2026-01-06" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5" +dependencies = [ + "wit-bindgen 0.51.0", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.123" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a254a4b10c19a76f09a27640e7ffbf9bc30bf67e16a3bf28aaefa4920fe81563" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.73" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54568702fabf5d4849ce2b90fadfa64168a097eaf4b351ce9df8b687a0086aaf" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.123" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24a40fc75b0ec6f3746ceb10d36f53a93dcd68a93b11b6445983945d79eba0dc" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.123" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "908f34bd9b9ce3d4caf07b72dfab63d61504d156856c6bd3cd87fa350cf3985b" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.123" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7acbf7616c27b194bbb550bf77ed0c2c3e5b7fd1260a93082b95fb7f47959b92" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wasm-encoder" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319" +dependencies = [ + "leb128fmt", + "wasmparser", +] + +[[package]] +name = "wasm-metadata" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" +dependencies = [ + "anyhow", + "indexmap", + "wasm-encoder", + "wasmparser", +] + +[[package]] +name = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "wasmparser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" +dependencies = [ + "bitflags", + "hashbrown 0.15.5", + "indexmap", + "semver", +] + +[[package]] +name = "web-sys" +version = "0.3.100" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e0871acf327f283dc6da28a1696cdc64fb355ba9f935d052021fa77f35cce69" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webpki-root-certs" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31141ce3fc3e300ae89b78c0dd67f9708061d1d2eda54b8209346fd6be9a92c" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webpki-roots" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52f5ee44c96cf55f1b349600768e3ece3a8f26010c05265ab73f945bb1a2eb9d" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[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.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[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.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[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.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "wit-bindgen" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5" +dependencies = [ + "wit-bindgen-rust-macro", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wit-bindgen-core" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc" +dependencies = [ + "anyhow", + "heck", + "wit-parser", +] + +[[package]] +name = "wit-bindgen-rust" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" +dependencies = [ + "anyhow", + "heck", + "indexmap", + "prettyplease", + "syn", + "wasm-metadata", + "wit-bindgen-core", + "wit-component", +] + +[[package]] +name = "wit-bindgen-rust-macro" +version = "0.51.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a" +dependencies = [ + "anyhow", + "prettyplease", + "proc-macro2", + "quote", + "syn", + "wit-bindgen-core", + "wit-bindgen-rust", +] + +[[package]] +name = "wit-component" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" +dependencies = [ + "anyhow", + "bitflags", + "indexmap", + "log", + "serde", + "serde_derive", + "serde_json", + "wasm-encoder", + "wasm-metadata", + "wasmparser", + "wit-parser", +] + +[[package]] +name = "wit-parser" +version = "0.244.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" +dependencies = [ + "anyhow", + "id-arena", + "indexmap", + "log", + "semver", + "serde", + "serde_derive", + "serde_json", + "unicode-xid", + "wasmparser", +] + +[[package]] +name = "writeable" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4" + +[[package]] +name = "yoke" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zerocopy" +version = "0.8.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1" +dependencies = [ + "proc-macro2", + "quote", + "syn", + "synstructure", +] + +[[package]] +name = "zeroize" +version = "1.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0" + +[[package]] +name = "zerotrie" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239" +dependencies = [ + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/rust/Cargo.toml b/rust/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..cd918d87220d75edf2e5739d077883426f67d52a --- /dev/null +++ b/rust/Cargo.toml @@ -0,0 +1,14 @@ +[workspace] +members = ["chess-core", "selfplay-core", "ct-bot"] +resolver = "2" + +[workspace.dependencies] +shakmaty = "0.27" +rand = "0.8" +serde = { version = "1", features = ["derive"] } +serde_json = "1" + +# Profiles only apply from the workspace root (cargo ignores them in members). +[profile.release] +lto = true +codegen-units = 1 diff --git a/rust/chess-core/Cargo.toml b/rust/chess-core/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..744c9b057ffbcc1d7f24a52615b501175967d051 --- /dev/null +++ b/rust/chess-core/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "chess-core" +version = "0.1.0" +edition = "2021" + +[dependencies] +shakmaty = { workspace = true } +shakmaty-syzygy = "0.25.3" +rand = { workspace = true } +anyhow = "1" diff --git a/rust/chess-core/src/encoding.rs b/rust/chess-core/src/encoding.rs new file mode 100644 index 0000000000000000000000000000000000000000..08d63b07f25ce7088bebb8daa0cc8c702e8655e9 --- /dev/null +++ b/rust/chess-core/src/encoding.rs @@ -0,0 +1,150 @@ +//! Position/move encodings — must match the Python tokenizers exactly +//! (`PostionTokenizer`, `alphazero_move_encoder.move_to_action_plane`). + +use shakmaty::zobrist::{Zobrist64, ZobristHash}; +use shakmaty::{CastlingSide, Chess, Color, EnPassantMode, Move, Position, Role}; + +pub const NUM_PLANES: usize = 73; + +pub fn piece_token(role: Role, color: Color) -> u8 { + let base = match role { + Role::Pawn => 1, + Role::Knight => 2, + Role::Bishop => 3, + Role::Rook => 4, + Role::Queen => 5, + Role::King => 6, + }; + if color == Color::White { + base + } else { + base + 6 + } +} + +/// (from_sq, to_sq, promotion) in python-chess conventions: castling is the +/// king's two-square move (e1g1), squares indexed a1=0..h8=63. +pub fn move_coords(m: &Move) -> (usize, usize, Option) { + match m { + Move::Castle { king, rook } => { + let k = u32::from(*king) as usize; + let r = u32::from(*rook) as usize; + let to = if r > k { k + 2 } else { k - 2 }; + (k, to, None) + } + _ => ( + u32::from(m.from().expect("no drops in chess")) as usize, + u32::from(m.to()) as usize, + m.promotion(), + ), + } +} + +/// AlphaZero 8x8x73 action plane (mirror of move_to_action_plane). +pub fn action_plane(from: usize, to: usize, promo: Option) -> usize { + let df = (to % 8) as i32 - (from % 8) as i32; + let dr = (to / 8) as i32 - (from / 8) as i32; + + if let Some(p) = promo { + if p != Role::Queen { + let dir_idx = (df + 1) as usize; + let piece_idx = match p { + Role::Knight => 0, + Role::Bishop => 1, + Role::Rook => 2, + _ => unreachable!("queen handled above"), + }; + return 64 + dir_idx * 3 + piece_idx; + } + } + + const KNIGHT_JUMPS: [(i32, i32); 8] = [ + (1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2), + ]; + if let Some(i) = KNIGHT_JUMPS.iter().position(|&d| d == (df, dr)) { + return 56 + i; + } + + const QUEEN_DIRS: [(i32, i32); 8] = [ + (0, 1), (1, 1), (1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0), (-1, 1), + ]; + let dist = df.abs().max(dr.abs()); + let dir_f = if df != 0 { df / dist } else { 0 }; + let dir_r = if dr != 0 { dr / dist } else { 0 }; + let dir_idx = QUEEN_DIRS.iter().position(|&d| d == (dir_f, dir_r)).unwrap(); + dir_idx * 7 + (dist as usize - 1) +} + +pub fn encode_position(pos: &Chess) -> ([u8; 64], u8, u8, u8) { + let mut tokens = [0u8; 64]; + let board = pos.board(); + for sq in board.occupied() { + let piece = board.piece_at(sq).unwrap(); + tokens[u32::from(sq) as usize] = piece_token(piece.role, piece.color); + } + let player = if pos.turn() == Color::White { 1 } else { 0 }; + let castles = pos.castles(); + let mut castling = 0u8; + if castles.has(Color::White, CastlingSide::KingSide) { + castling |= 1; + } + if castles.has(Color::White, CastlingSide::QueenSide) { + castling |= 2; + } + if castles.has(Color::Black, CastlingSide::KingSide) { + castling |= 4; + } + if castles.has(Color::Black, CastlingSide::QueenSide) { + castling |= 8; + } + let ep = pos + .ep_square(EnPassantMode::Legal) + .map(|s| (u32::from(s) % 8) as u8) + .unwrap_or(8); + (tokens, player, castling, ep) +} + +pub fn zobrist(pos: &Chess) -> u64 { + let h: Zobrist64 = pos.zobrist_hash(EnPassantMode::Legal); + h.0 +} + +/// Terminal value from the side-to-move POV, or None. `keys` is the sequence +/// of zobrist keys of all positions seen (game history + search path), +/// including the current position — mirrors python-chess is_repetition(3) +/// seeing the search pushes on the shared board. +pub fn terminal_value(pos: &Chess, keys: &[u64], current: u64) -> Option { + if pos.legal_moves().is_empty() { + return Some(if pos.is_check() { -1.0 } else { 0.0 }); + } + if pos.is_insufficient_material() || pos.halfmoves() >= 100 { + return Some(0.0); + } + if keys.iter().filter(|&&k| k == current).count() >= 3 { + return Some(0.0); + } + None +} + +/// `terminal_value` for a position inside a search tree (Lc0's two-fold rule). +/// A position that repeats one already on the search path — root included, +/// i.e. `keys[root_idx..]` — is a draw at its second occurrence: whoever could +/// have deviated chose to repeat, and can keep repeating. Without this the +/// search sees perpetuals and repetition draws only once the cycle comes +/// round a third time, 4+ plies deeper than it needs to. Repetitions that +/// reach back into the pre-root game history still need the full threefold. +pub fn search_terminal_value(pos: &Chess, keys: &[u64], current: u64, root_idx: usize) -> Option { + if let Some(t) = terminal_value(pos, keys, current) { + return Some(t); + } + let prior = &keys[..keys.len().saturating_sub(1)]; + if prior.len() > root_idx && prior[root_idx..].contains(¤t) { + return Some(0.0); + } + None +} + +/// Half-move index of the position (0 = white's first move). +pub fn halfmove(pos: &Chess) -> u32 { + 2 * (u32::from(pos.fullmoves()) - 1) + if pos.turn() == Color::White { 0 } else { 1 } +} diff --git a/rust/chess-core/src/eval.rs b/rust/chess-core/src/eval.rs new file mode 100644 index 0000000000000000000000000000000000000000..aeaed4ad2ff3bc2b77c82938e35a3bf6ba824962 --- /dev/null +++ b/rust/chess-core/src/eval.rs @@ -0,0 +1,41 @@ +//! The network interface the search is written against: encoded positions in, +//! flat policy logits and a side-to-move value out. Implemented by ct-bot's +//! ONNX Runtime evaluator, by test doubles, and -- for the batched match runner +//! in selfplay-core -- by nothing at all: that driver steps the search itself +//! (`Search::step` / `Search::resolve`) and runs the forward in Python. + +use anyhow::Result; + +pub struct EvalRequest { + pub tokens: [u8; 64], + pub player: u8, + pub castling: u8, + pub ep: u8, + /// The legal moves' flat logit indices (from_sq * 73 + plane), in the + /// search's move order -- filled only with `SearchParams::legal_in_requests`, + /// so a batched driver can gather those logits on the GPU and send back a + /// few dozen floats per position instead of 4672. + pub legal: Vec, +} + +pub struct EvalOutput { + /// Either the flat [64*73] logits for one position (from_sq * 73 + plane), + /// or exactly one logit per legal move in the order of the request's + /// `legal` (a position never has 4672 legal moves, so the length says which). + pub logits: Vec, + pub value: f32, +} + +/// Batched position evaluation. +pub trait Evaluator { + fn eval_batch(&mut self, batch: &[EvalRequest]) -> Result>; +} + +/// For searches driven step by step, whose evaluations arrive through `resolve`. +pub struct NoEval; + +impl Evaluator for NoEval { + fn eval_batch(&mut self, _batch: &[EvalRequest]) -> Result> { + anyhow::bail!("NoEval: this search is driven with step()/resolve(), not go()") + } +} diff --git a/rust/chess-core/src/lib.rs b/rust/chess-core/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..9a5e2c3a6f0966255f8a9552f23a55a6485c9363 --- /dev/null +++ b/rust/chess-core/src/lib.rs @@ -0,0 +1,17 @@ +//! Shared chess primitives for the ChessTransformer Rust crates: model +//! position/move encodings (exact mirrors of the Python tokenizers), the +//! edge-centric MCTS tree with PUCT selection / virtual-loss backup, and the +//! bot's search itself (`search`). +//! +//! Used by `selfplay-core` (PyO3 generation engine and batched match runner) +//! and `ct-bot` (standalone bot binary). The match runner and the deployed bot +//! run the same `search::Search`, so a gate measures the search that plays on +//! lichess. Encoding parity with Python is guarded by +//! `scripts/check_rust_parity.py`. + +pub mod encoding; +pub mod eval; +pub mod matchplay; +pub mod search; +pub mod selfplay; +pub mod tree; diff --git a/rust/chess-core/src/matchplay.rs b/rust/chess-core/src/matchplay.rs new file mode 100644 index 0000000000000000000000000000000000000000..b61adc832475de088d12e91fba2d5e4f1d4a07c2 --- /dev/null +++ b/rust/chess-core/src/matchplay.rs @@ -0,0 +1,374 @@ +//! One game between two networks, each side played the way the deployed bot +//! plays a lichess game, with its search driven one wave at a time so that a +//! batched runner (selfplay-core `MatchEngine`) can evaluate the waves of many +//! games together. +//! +//! The move flow is ct-bot's lichess loop (branch lichess-levers, the deployed +//! build), with the clock plan pinned at the per-speed cap -- 81-100 % of live +//! moves are cap-bound: +//! +//! * our turn: `set_position` re-roots the kept tree (ponder hit or reuse), +//! then a search of `effective_sims(cap, warm visits, total_cap)` sims; +//! * after our move: ponder the position after it for +//! `ponder_budget(ponder_sims, warm visits, total_cap)` sims, unless the +//! game is over; +//! * the opponent's move stops our ponder after its current wave. +//! +//! Both sides advance one wave per round: two engines thinking and pondering +//! concurrently on equal hardware. + +use crate::encoding::{terminal_value, zobrist}; +use crate::search::{ + effective_sims, ponder_budget, EvalOutput, EvalRequest, Job, NoEval, Search, SearchParams, Step, +}; +use shakmaty::{CastlingMode, Chess, Color, Move, Position}; + +/// Search settings of one side (ct-bot flags). +#[derive(Clone, Copy)] +pub struct SideParams { + pub c_puct: f64, + pub fpu: f64, + pub prior_temp: f32, + pub sim_batch: usize, + pub tt_cap: usize, +} + +impl SideParams { + fn search_params(&self) -> SearchParams { + SearchParams { + c_puct: self.c_puct, + fpu: self.fpu, + prior_temp: self.prior_temp, + sim_batch: self.sim_batch, + tt_cap: self.tt_cap, + legal_in_requests: true, + ..SearchParams::default() + } + } +} + +/// The budget rules both sides play under. +#[derive(Clone, Copy)] +pub struct MatchRules { + /// Per-move fresh-sims cap (ct-bot `--max-sims`). + pub sims: u32, + /// Ponder budget (ct-bot `--ponder-max-sims`); 0 = no pondering. + pub ponder_sims: u32, + /// Total root-visit ceiling: `sims` + PONDER_HEADROOM. + pub total_cap: u32, + /// Draw after this many plies from the start position (0 = none). + pub max_plies: u32, +} + +struct Side { + search: Search, + job: Option, + pondering: bool, + /// The requests of the eval this side has out. + out: Option>, + /// The opponent has moved: stop pondering and search our move. + must_move: bool, +} + +pub struct MatchGame { + pub id: usize, + pub a_white: bool, + start: Chess, + moves: Vec, + moves_uci: Vec, + pos: Chess, + history: Vec, + sides: [Side; 2], // 0 = network A, 1 = network B + end: Option<(f32, &'static str)>, +} + +impl MatchGame { + pub fn new(id: usize, start: Chess, a_white: bool, params: SideParams) -> Self { + let side = || Side { + search: Search::new(NoEval, params.search_params()), + job: None, + pondering: false, + out: None, + must_move: false, + }; + let mut g = MatchGame { + id, + a_white, + history: vec![zobrist(&start)], + pos: start.clone(), + start, + moves: Vec::new(), + moves_uci: Vec::new(), + sides: [side(), side()], + end: None, + }; + g.check_end(0); + if g.end.is_none() { + let s = g.to_move(); + g.sides[s].must_move = true; + } + g + } + + /// (z from white's POV, reason) once the game is over. + pub fn end(&self) -> Option<(f32, &'static str)> { + self.end + } + + pub fn moves_uci(&self) -> &[String] { + &self.moves_uci + } + + /// The eval side `s` (0 = A) is waiting for, if any. + pub fn pending(&self, s: usize) -> Option<&[EvalRequest]> { + self.sides[s].out.as_deref() + } + + /// Outputs for side `s`'s pending eval, in its order. + pub fn resolve(&mut self, s: usize, outputs: Vec) { + let side = &mut self.sides[s]; + side.out = None; + side.search.resolve(side.job.as_mut().expect("eval out without a job"), outputs); + } + + fn to_move(&self) -> usize { + if (self.pos.turn() == Color::White) == self.a_white { 0 } else { 1 } + } + + fn check_end(&mut self, max_plies: u32) { + let key = *self.history.last().unwrap(); + if let Some(t) = terminal_value(&self.pos, &self.history, key) { + // Mate scores -1 for the side to move; the side that just moved wins. + let z = if t < 0.0 { + if self.pos.turn() == Color::Black { 1.0 } else { -1.0 } + } else { + 0.0 + }; + self.end = Some((z, "terminal")); + } else if max_plies > 0 && self.moves.len() as u32 >= max_plies { + self.end = Some((0.0, "max_plies")); + } + } + + /// Step both sides until each waits on an eval or idles, or the game ends. + /// Within a pass the side searching its move goes first and the pondering + /// side second, so a ponder sees the opponent's move as soon as it is + /// played -- whichever network is which. + pub fn advance(&mut self, rules: &MatchRules) { + while self.end.is_none() { + let mut progressed = false; + for ponder_phase in [false, true] { + for s in 0..2 { + let side = &self.sides[s]; + if self.end.is_some() || side.out.is_some() { + continue; + } + if (side.job.is_some() && side.pondering) != ponder_phase { + continue; + } + progressed |= self.step_side(s, rules); + } + } + if !progressed { + break; + } + } + } + + /// Whether the game is live but neither side has anything to do -- a bug. + pub fn stalled(&self) -> bool { + self.end.is_none() && self.sides.iter().all(|s| s.out.is_none()) + } + + /// One step of side `s`. Returns whether anything moved on without an eval. + fn step_side(&mut self, s: usize, rules: &MatchRules) -> bool { + let side = &mut self.sides[s]; + let Some(job) = side.job.as_mut() else { + if side.must_move { + side.must_move = false; + self.begin_move(s, rules); + return true; + } + return false; + }; + if side.pondering && side.must_move { + job.stop(); // the opponent's move arrived + } + match side.search.step(job) { + Step::Eval(reqs) => { + side.out = Some(reqs); + false + } + Step::Wave => true, + Step::Done => { + let job = side.job.take().unwrap(); + let result = side.search.finish(job); + if side.pondering { + side.pondering = false; + } else { + self.play(s, result.best, rules); + } + true + } + } + } + + /// Our turn: re-root onto the game (ponder hit or plain reuse), then search + /// the effective budget. + fn begin_move(&mut self, s: usize, rules: &MatchRules) { + let side = &mut self.sides[s]; + side.search.set_position(self.start.clone(), &self.moves); + let sims = if rules.ponder_sims > 0 { + effective_sims(rules.sims, side.search.root_visits(), rules.total_cap) + } else { + rules.sims + }; + side.job = Some(side.search.start(sims)); + side.pondering = false; + } + + fn play(&mut self, s: usize, best: Move, rules: &MatchRules) { + self.moves_uci.push(best.to_uci(CastlingMode::Standard).to_string()); + self.pos.play_unchecked(&best); + self.history.push(zobrist(&self.pos)); + self.moves.push(best); + self.check_end(rules.max_plies); + if self.end.is_some() { + return; + } + if rules.ponder_sims > 0 && !self.pos.is_game_over() { + let side = &mut self.sides[s]; + side.search.set_position(self.start.clone(), &self.moves); + let budget = ponder_budget(rules.ponder_sims, side.search.root_visits(), rules.total_cap); + if budget > 0 { + side.job = Some(side.search.start(budget)); + side.pondering = true; + } + } + self.sides[1 - s].must_move = true; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::encoding::NUM_PLANES; + use crate::search::Evaluator; + use shakmaty::fen::Fen; + use std::sync::atomic::AtomicBool; + + /// A deterministic stand-in network; `salt` makes A and B different players. + struct HashEval(f64); + + impl Evaluator for HashEval { + fn eval_batch(&mut self, batch: &[EvalRequest]) -> anyhow::Result> { + Ok(batch.iter().map(|r| hash_out(self.0, r)).collect()) + } + } + + fn hash_out(salt: f64, r: &EvalRequest) -> EvalOutput { + let mut h = salt + r.player as f64 * 0.7 + r.castling as f64 * 0.3 + r.ep as f64 * 0.11; + for (i, &t) in r.tokens.iter().enumerate() { + h += (t as f64) * ((i as f64) * 0.618).sin(); + } + let logits = (0..64 * NUM_PLANES) + .map(|k| ((h * 0.37 + k as f64 * 0.0131).sin() * 2.5) as f32) + .collect(); + EvalOutput { logits, value: ((h * 0.173).sin() * 0.9) as f32 } + } + + const SALTS: [f64; 2] = [0.0, 1.7]; + + fn pos(fen: &str) -> Chess { + fen.parse::().unwrap().into_position(CastlingMode::Standard).unwrap() + } + + fn params(sim_batch: usize) -> SideParams { + SideParams { c_puct: 1.0, fpu: 0.2, prior_temp: 1.0, sim_batch, tt_cap: 2_000_000 } + } + + /// The batched driver, one game. + fn batched(start: &Chess, a_white: bool, rules: MatchRules, sim_batch: usize) -> Vec { + let mut g = MatchGame::new(0, start.clone(), a_white, params(sim_batch)); + while g.end().is_none() { + g.advance(&rules); + assert!(g.end().is_some() || !g.stalled(), "stalled"); + for s in 0..2 { + if let Some(reqs) = g.pending(s) { + let outs = reqs.iter().map(|r| hash_out(SALTS[s], r)).collect(); + g.resolve(s, outs); + } + } + } + g.moves_uci().to_vec() + } + + /// The bot's own flow, sequentially through `go()`: our search, then our + /// ponder to completion, then the opponent's turn. + fn sequential(start: &Chess, a_white: bool, rules: MatchRules, sim_batch: usize) -> Vec { + let mk = |s: usize| Search::new(HashEval(SALTS[s]), params(sim_batch).search_params()); + let mut sides = [mk(0), mk(1)]; + let mut moves: Vec = Vec::new(); + let mut out = Vec::new(); + let mut p = start.clone(); + let mut history = vec![zobrist(&p)]; + let stop = AtomicBool::new(false); + loop { + let s = if (p.turn() == Color::White) == a_white { 0 } else { 1 }; + let search = &mut sides[s]; + search.set_position(start.clone(), &moves); + let sims = effective_sims(rules.sims, search.root_visits(), rules.total_cap); + let best = search.go(sims, None, &stop).unwrap().best; + out.push(best.to_uci(CastlingMode::Standard).to_string()); + p.play_unchecked(&best); + history.push(zobrist(&p)); + moves.push(best); + let key = *history.last().unwrap(); + if terminal_value(&p, &history, key).is_some() || moves.len() as u32 >= rules.max_plies { + return out; + } + if !p.is_game_over() { + search.set_position(start.clone(), &moves); + let budget = ponder_budget(rules.ponder_sims, search.root_visits(), rules.total_cap); + if budget > 0 { + search.go(budget, None, &stop).unwrap(); + } + } + } + } + + #[test] + fn batched_driver_plays_the_bots_own_moves() { + // A ponder (<= 24 sims, <= 7 waves) always ends before the opponent's search + // (96 sims, >= 7 waves of 16 ... with reuse clipping never below 64): no ponder is + // stopped early, so the sequential flow is the exact reference. + let rules = MatchRules { sims: 96, ponder_sims: 24, total_cap: 96 + 4000, max_plies: 40 }; + for fen in [ + "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1", + "r1bqkbnr/pppp1ppp/2n5/4p3/2B1P3/5N2/PPPP1PPP/RNBQK2R b KQkq - 3 3", + "6k1/5ppp/R7/Q7/3q4/6PP/7K/8 b - - 0 1", + ] { + for a_white in [true, false] { + let start = pos(fen); + let b = batched(&start, a_white, rules, 4); + let r = sequential(&start, a_white, rules, 4); + assert!(b.len() > 4, "{fen}: game too short to test anything"); + assert_eq!(b, r, "{fen} a_white={a_white}"); + } + } + } + + #[test] + fn early_ponder_stop_still_plays_legal_games() { + // Ponder budget above the move budget: ponders get stopped mid-way. + let rules = MatchRules { sims: 64, ponder_sims: 400, total_cap: 64 + 4000, max_plies: 30 }; + let start = pos("rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1"); + let moves = batched(&start, true, rules, 16); + let mut p = start; + for u in &moves { + let m = u.parse::().unwrap().to_move(&p).unwrap(); + p.play_unchecked(&m); + } + assert_eq!(moves.len(), 30); + } +} diff --git a/rust/chess-core/src/search.rs b/rust/chess-core/src/search.rs new file mode 100644 index 0000000000000000000000000000000000000000..68f60f4dc3cc39605edb9dd7ab5c5ea8082c7be0 --- /dev/null +++ b/rust/chess-core/src/search.rs @@ -0,0 +1,1212 @@ +//! Single-game batched MCTS over one position -- the deployed bot's search +//! (moved here from ct-bot so the batched match runner runs the same code). +//! Semantics mirror `Pos2MoveV2MctsBot`: PUCT + FPU, virtual-loss leaf waves +//! with one batched NN forward per wave, zobrist TT for priors + value, +//! threefold/50-move awareness over game history + search path (plus Lc0's +//! two-fold rule for cycles inside the search), and tree reuse across moves +//! (re-root when the new position extends the previous root by 1..=4 +//! expanded plies). +//! +//! `go()` runs a whole search against the `Evaluator`. The same search can be +//! driven one wave at a time -- `start`, then `step` until `Step::Done`, +//! handing each `Step::Eval` batch's outputs to `resolve`, then `finish` -- +//! which is what `go()` itself does, so the two cannot drift apart. That lets +//! a driver interleave hundreds of searches and evaluate all their waves in +//! one forward. + +use std::collections::HashMap; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use anyhow::Result; +use crate::encoding::{ + action_plane, encode_position, halfmove, move_coords, search_terminal_value, zobrist, + NUM_PLANES, +}; +use crate::tree::{backup_vl, puct_select, softmax_priors, Node}; +use rand::prelude::*; +use rand::rngs::StdRng; +use shakmaty::{Chess, Move, Position}; +use shakmaty_syzygy::{AmbiguousWdl, Tablebase, Wdl}; + +pub use crate::eval::{EvalOutput, EvalRequest, Evaluator, NoEval}; + +pub struct SearchParams { + pub c_puct: f64, + pub fpu: f64, + pub prior_temp: f32, + pub sim_batch: usize, + /// Sample the move ∝ visits^(1/temp) for the first `move_temp_plies` + /// half-moves (0.0 = always argmax — the deterministic gauntlet setting). + pub move_temp: f64, + pub move_temp_plies: u32, + pub tt_cap: usize, + /// Fill `EvalRequest::legal` (batched drivers that gather legal logits on + /// the GPU). The bot leaves it off and evaluates full logits. + pub legal_in_requests: bool, + /// Syzygy tables. In-tree, positions reached by a capture or pawn move + /// that the tables cover are scored exactly (WDL) instead of by the value + /// head. At a covered root, a won position plays the DTZ-optimal move + /// outright and a drawn/lost one restricts the search to result-preserving + /// moves (root probing needs the DTZ tables too). + pub syzygy: Option>>, +} + +impl Default for SearchParams { + fn default() -> Self { + SearchParams { + c_puct: 1.0, + fpu: 0.2, + prior_temp: 1.0, + sim_batch: 16, + move_temp: 0.0, + move_temp_plies: 0, + tt_cap: 2_000_000, + legal_in_requests: false, + syzygy: None, + } + } +} + +/// Root Dirichlet noise for one search (self-play exploration, AlphaZero): once +/// the root is expanded its priors become `(1 - eps) * p + eps * Dir(alpha)`. +/// The TT keeps the clean priors. The bot never sets it. +#[derive(Clone, Copy)] +pub struct RootNoise { + pub alpha: f64, + pub eps: f64, + pub seed: u64, +} + +/// Standard normal via Box-Muller (rand 0.8 has no distributions beyond uniform +/// without rand_distr). +pub fn std_normal(rng: &mut StdRng) -> f64 { + let u1 = rng.gen::().max(f64::MIN_POSITIVE); + let u2 = rng.gen::(); + (-2.0 * u1.ln()).sqrt() * (std::f64::consts::TAU * u2).cos() +} + +/// Gamma(alpha, 1) by Marsaglia-Tsang, boosted for alpha < 1. +pub fn sample_gamma(rng: &mut StdRng, alpha: f64) -> f64 { + if alpha < 1.0 { + let u = rng.gen::(); + return sample_gamma(rng, alpha + 1.0) * u.powf(1.0 / alpha); + } + let d = alpha - 1.0 / 3.0; + let c = 1.0 / (9.0 * d).sqrt(); + loop { + let (x, v) = loop { + let x = std_normal(rng); + let v = 1.0 + c * x; + if v > 0.0 { + break (x, v * v * v); + } + }; + let u = rng.gen::(); + if u < 1.0 - 0.0331 * x.powi(4) || u.ln() < 0.5 * x * x + d * (1.0 - v + v.ln()) { + return d * v; + } + } +} + +/// Extra TOTAL-root-visit headroom above the per-move sims cap when pondering. +/// Deployed lichess bot semantics (ct-bot `timeman`, branch lichess-levers): a +/// visit-cap A/B showed capping totals near the fresh-sims cap loses strength, +/// so the headroom only bounds chained-ponder tails. +pub const PONDER_HEADROOM: u32 = 4000; + +/// Fresh-sim budget for a move given `plan` sims from the clock, `warm` +/// visits already on the root and the total-visits ceiling `total_cap` +/// (per-speed max sims + PONDER_HEADROOM). Min-cap form, not `plan - warm`: +/// warm visits cost no clock, so only clip when totals near the edge. +pub fn effective_sims(plan: u32, warm: u32, total_cap: u32) -> u32 { + plan.min(total_cap.saturating_sub(warm)).max(64) +} + +/// Ponder-search budget: like `effective_sims` with no floor -- a ponder root +/// already carrying `total_cap` visits gets 0 sims. +pub fn ponder_budget(max_sims: u32, warm: u32, total_cap: u32) -> u32 { + max_sims.min(total_cap.saturating_sub(warm)) +} + +pub struct SearchResult { + pub best: Move, + /// Root value from the side-to-move POV. + pub value: f32, + pub sims: u32, + pub nn_evals: u32, + pub tt_hits: u32, + /// Tablebase-scored leaves (or 1 when the root move came from the tables). + pub tb_hits: u32, + pub elapsed: Duration, +} + +/// One searched move, as `Search::summarize_tree` reports it. +pub struct TreeSummary { + pub mv: Move, + pub visits: u32, + pub prior: f32, + /// Mean backed-up value for the side that plays `mv`. + pub q: f32, + pub children: Vec, +} + +/// How deep the current tree reaches, in plies from the root. +pub struct DepthStats { + /// Mean plies a simulation descended before its leaf. + pub mean: f32, + /// Longest path any simulation took. + pub max: u32, + /// Length of the line found by always following the most-visited move. + pub main_line: u32, +} + +/// What the tablebases say about the root. +enum RootTb { + /// Not covered (or no tables, or a probe failed): search normally. + Off, + /// Won: play the DTZ-optimal move without searching. + Play(Move), + /// Drawn or lost: search only among the moves that keep the best result. + Restrict(Vec), +} + +enum LeafEval { + /// Index into the deduped NN batch (priors computed after the forward). + Batch(usize), + /// Transposition / reused-subtree hit: priors (legal-move order) + value. + Cached(Vec, f32), +} + +struct PendingLeaf { + node: usize, + path: Vec<(usize, usize)>, + key: u64, + moves: Vec, + eval: LeafEval, +} + +enum Stage { + /// Expand the root (one eval unless the TT has it), then waves. + Root, + /// The root's eval is out: (zobrist key, legal moves). + RootPending(u64, Vec), + /// Leaf waves until the budget is spent or the job is stopped. + Waves, + /// A wave's NN batch is out. + WavePending(Vec), + Done, +} + +/// One search in progress, from `start` to `finish`. +pub struct Job { + sims: u32, + t0: Instant, + sims_done: u32, + nn_evals: u32, + tt_hits: u32, + tb_hits: u32, + restrict: Option>, + tb_move: Option, + stage: Stage, + stopped: bool, + noise: Option, +} + +impl Job { + /// End the search after the wave in progress (go()'s stop flag / deadline). + pub fn stop(&mut self) { + self.stopped = true; + } + + pub fn is_done(&self) -> bool { + matches!(self.stage, Stage::Done) + } +} + +/// What a search needs next. +pub enum Step { + /// Evaluate these positions and pass the outputs, in order, to `resolve`. + Eval(Vec), + /// A wave completed without any NN work (terminal / TB / TT leaves only). + Wave, + /// Budget spent (or stopped, or a tablebase move): call `finish`. + Done, +} + +pub struct Search { + pub params: SearchParams, + eval: E, + tree: Vec, + pos: Chess, + history: Vec, // zobrist of every game position incl. current + tt: HashMap, f32)>, // priors (legal-move order) + stm value + prev_start: Option, + prev_moves: Vec, + rng: StdRng, +} + +impl Search { + pub fn new(eval: E, params: SearchParams) -> Self { + let pos = Chess::default(); + let history = vec![zobrist(&pos)]; + Search { + params, + eval, + tree: vec![Node::default()], + pos, + history, + tt: HashMap::new(), + prev_start: None, + prev_moves: Vec::new(), + rng: StdRng::from_entropy(), + } + } + + pub fn new_game(&mut self) { + self.tree = vec![Node::default()]; + self.tt.clear(); + self.prev_start = None; + self.prev_moves.clear(); + self.set_position(Chess::default(), &[]); + } + + pub fn position(&self) -> &Chess { + &self.pos + } + + /// Visits already on the root (warm visits from tree reuse / pondering). + pub fn root_visits(&self) -> u32 { + if !self.tree[0].expanded { + return 0; + } + self.tree[0].n.iter().sum() + } + + /// Set the root to `start` + `moves`, rebuilding the zobrist history and + /// re-rooting the previous search tree when the new position extends the + /// previous one by 1..=4 plies through expanded nodes. + pub fn set_position(&mut self, start: Chess, moves: &[Move]) { + let mut pos = start.clone(); + let mut history = vec![zobrist(&pos)]; + for m in moves { + pos.play_unchecked(m); + history.push(zobrist(&pos)); + } + + let reused = self.try_reroot(&start, moves); + if !reused { + self.tree = vec![Node::default()]; + } + self.pos = pos; + self.history = history; + self.prev_start = Some(start); + self.prev_moves = moves.to_vec(); + } + + /// Mirror of `Pos2MoveV2MctsBot._take_reuse_root`: accept if the new move + /// list extends the previous root's by 1..=4 plies and every step descends + /// into an expanded child. On success, compacts the subtree into a fresh + /// arena rooted at index 0. + fn try_reroot(&mut self, start: &Chess, moves: &[Move]) -> bool { + let Some(prev_start) = &self.prev_start else { + return false; + }; + if prev_start != start || !self.tree[0].expanded { + return false; + } + let rp = self.prev_moves.len(); + let gap = moves.len() as i64 - rp as i64; + if !(1..=4).contains(&gap) || moves[..rp] != self.prev_moves[..] { + return false; + } + let mut node = 0usize; + for mv in &moves[rp..] { + if !self.tree[node].expanded { + return false; + } + let Some(idx) = self.tree[node].moves.iter().position(|m| m == mv) else { + return false; + }; + let child = self.tree[node].children[idx]; + if child < 0 || !self.tree[child as usize].expanded { + return false; + } + node = child as usize; + } + self.tree = reroot(&self.tree, node); + true + } + + /// Run up to `sims` simulations (or until `deadline` / `stop`, checked + /// between waves; at least one wave always completes). Panics if the root + /// position has no legal moves — callers check game-over first. + pub fn go(&mut self, sims: u32, deadline: Option, stop: &AtomicBool) -> Result { + let mut job = self.start(sims); + loop { + match self.step(&mut job) { + Step::Done => break, + Step::Eval(batch) => { + let root = matches!(job.stage, Stage::RootPending(..)); + let outputs = self.eval.eval_batch(&batch)?; + self.resolve(&mut job, outputs); + if root { + continue; // the stop/deadline checks run between waves only + } + } + Step::Wave => {} + } + if stop.load(Ordering::Relaxed) { + job.stop(); + } else if let Some(d) = deadline { + if Instant::now() >= d { + job.stop(); + } + } + } + Ok(self.finish(job)) + } + + /// Begin a search of up to `sims` simulations from the current position. + pub fn start(&mut self, sims: u32) -> Job { + let mut job = Job { + sims, + t0: Instant::now(), + sims_done: 0, + nn_evals: 0, + tt_hits: 0, + tb_hits: 0, + restrict: None, + tb_move: None, + stage: Stage::Root, + stopped: false, + noise: None, + }; + match self.root_tablebase() { + RootTb::Play(best) => { + job.tb_move = Some(best); + job.tb_hits = 1; + job.stage = Stage::Done; + } + RootTb::Restrict(keep) => { + self.tree = vec![Node::default()]; // a reused root has every move + job.restrict = Some(keep); + } + RootTb::Off => {} + } + job + } + + /// `start`, plus root noise: applied now to a reused root, else as soon as + /// the root is expanded -- before the first wave either way. + pub fn start_with_noise(&mut self, sims: u32, noise: Option) -> Job { + let mut job = self.start(sims); + job.noise = noise; + if self.tree[0].expanded && !job.is_done() { + self.apply_root_noise(&mut job); + } + job + } + + fn legal_of(&self, moves: &[Move]) -> Vec { + if self.params.legal_in_requests { legal_indices(moves) } else { Vec::new() } + } + + /// Seed the move-temperature sampler (the bot keeps its entropy seed). + pub fn seed_rng(&mut self, seed: u64) { + self.rng = StdRng::seed_from_u64(seed); + } + + /// TT entries held (evaluation cache size). + pub fn tt_len(&self) -> usize { + self.tt.len() + } + + fn apply_root_noise(&mut self, job: &mut Job) { + let Some(n) = job.noise.take() else { return }; + if n.alpha <= 0.0 { + return; + } + let mut rng = StdRng::seed_from_u64(n.seed); + let root = &mut self.tree[0]; + let noise: Vec = (0..root.priors.len()).map(|_| sample_gamma(&mut rng, n.alpha)).collect(); + let total: f64 = noise.iter().sum(); + if total > 0.0 { + for (p, x) in root.priors.iter_mut().zip(&noise) { + *p = ((1.0 - n.eps) * (*p as f64) + n.eps * x / total) as f32; + } + } + } + + /// Advance `job` to its next NN batch (or the end of a wave, or the end). + pub fn step(&mut self, job: &mut Job) -> Step { + loop { + match std::mem::replace(&mut job.stage, Stage::Done) { + Stage::Done => return Step::Done, + Stage::RootPending(..) | Stage::WavePending(_) => { + panic!("step() while an eval is out: call resolve() first") + } + Stage::Root => { + job.stage = Stage::Waves; + if self.tree[0].expanded { + continue; + } + let key = *self.history.last().unwrap(); + let moves: Vec = self.pos.legal_moves().to_vec(); + assert!(!moves.is_empty(), "go() on a terminal position"); + if let Some((priors, _)) = self.tt.get(&key).cloned() { + job.tt_hits += 1; + self.expand_root(job, moves, priors); + continue; + } + let (tokens, player, castling, ep) = encode_position(&self.pos); + let legal = self.legal_of(&moves); + job.stage = Stage::RootPending(key, moves); + return Step::Eval(vec![EvalRequest { tokens, player, castling, ep, legal }]); + } + Stage::Waves => { + if job.stopped || job.sims_done >= job.sims { + return Step::Done; + } + let (pending, batch) = self.collect_wave(job); + if batch.is_empty() { + self.resolve_wave(job, pending, Vec::new()); + job.stage = Stage::Waves; + return Step::Wave; + } + job.stage = Stage::WavePending(pending); + return Step::Eval(batch); + } + } + } + } + + /// Hand back the outputs for the batch `step` returned, in its order. + pub fn resolve(&mut self, job: &mut Job, outputs: Vec) { + match std::mem::replace(&mut job.stage, Stage::Waves) { + Stage::RootPending(key, moves) => { + let out = outputs.into_iter().next().expect("one output for the root"); + job.nn_evals += 1; + let priors = priors_for(&moves, &out.logits, self.params.prior_temp); + self.insert_tt(key, priors.clone(), out.value); + self.expand_root(job, moves, priors); + } + Stage::WavePending(pending) => { + job.nn_evals += outputs.len() as u32; + self.resolve_wave(job, pending, outputs); + } + _ => panic!("resolve() with no eval out"), + } + } + + /// The move and stats of a finished (or stopped) search. + pub fn finish(&mut self, job: Job) -> SearchResult { + if let Some(best) = job.tb_move { + return SearchResult { + best, + value: 1.0, + sims: 0, + nn_evals: 0, + tt_hits: 0, + tb_hits: 1, + elapsed: job.t0.elapsed(), + }; + } + let root = &self.tree[0]; + let best_idx = if self.params.move_temp > 0.0 + && halfmove(&self.pos) < self.params.move_temp_plies + { + let weights: Vec = root + .n + .iter() + .map(|&n| (n as f64).powf(1.0 / self.params.move_temp)) + .collect(); + let total: f64 = weights.iter().sum(); + if total > 0.0 { + let mut r = self.rng.gen::() * total; + let mut pick = root.n.len() - 1; + for (i, w) in weights.iter().enumerate() { + if r < *w { + pick = i; + break; + } + r -= w; + } + pick + } else { + 0 + } + } else { + (0..root.n.len()).max_by_key(|&i| root.n[i]).unwrap_or(0) + }; + let value = if root.n[best_idx] > 0 { + (-root.w[best_idx] / root.n[best_idx] as f64) as f32 + } else { + 0.0 + }; + + SearchResult { + best: root.moves[best_idx].clone(), + value, + sims: job.sims_done, + nn_evals: job.nn_evals, + tt_hits: job.tt_hits, + tb_hits: job.tb_hits, + elapsed: job.t0.elapsed(), + } + } + + /// The most-visited part of the current tree, for display: at depth `d` + /// each node keeps its `widths[d]` most-visited children, dropping any + /// with fewer than `min_visits`. Read-only; call it after a search. + pub fn summarize_tree(&self, widths: &[usize], min_visits: u32) -> Vec { + self.summarize_node(0, widths, min_visits) + } + + /// Depth reached by the current tree (warm visits from tree reuse included). + /// Each simulation adds one visit to every edge on its path, so the summed + /// edge visits over the root's visits is the mean simulation depth. + pub fn depth_stats(&self) -> DepthStats { + let total: u64 = self.tree[0].n.iter().map(|&n| n as u64).sum(); + let (mut edge_visits, mut max) = (0u64, 0u32); + let mut stack = vec![(0usize, 0u32)]; + while let Some((idx, depth)) = stack.pop() { + let nd = &self.tree[idx]; + if !nd.expanded { + continue; + } + for i in 0..nd.moves.len() { + if nd.n[i] == 0 { + continue; + } + edge_visits += nd.n[i] as u64; + max = max.max(depth + 1); + if nd.children[i] >= 0 { + stack.push((nd.children[i] as usize, depth + 1)); + } + } + } + let mut main_line = 0; + let mut node = 0usize; + loop { + let nd = &self.tree[node]; + let best = if nd.expanded { (0..nd.n.len()).max_by_key(|&i| nd.n[i]) } else { None }; + let Some(i) = best.filter(|&i| nd.n[i] > 0) else { break }; + main_line += 1; + if nd.children[i] < 0 { + break; + } + node = nd.children[i] as usize; + } + DepthStats { + mean: if total > 0 { (edge_visits as f64 / total as f64) as f32 } else { 0.0 }, + max, + main_line, + } + } + + fn summarize_node(&self, node: usize, widths: &[usize], min_visits: u32) -> Vec { + let Some((&width, deeper)) = widths.split_first() else { + return Vec::new(); + }; + let nd = &self.tree[node]; + if !nd.expanded { + return Vec::new(); + } + let mut order: Vec = (0..nd.moves.len()).filter(|&i| nd.n[i] >= min_visits.max(1)).collect(); + order.sort_by(|&a, &b| nd.n[b].cmp(&nd.n[a])); + order.truncate(width); + order + .into_iter() + .map(|i| TreeSummary { + mv: nd.moves[i].clone(), + visits: nd.n[i], + prior: nd.priors[i], + q: (-nd.w[i] / nd.n[i] as f64) as f32, + children: match nd.children[i] { + c if c >= 0 => self.summarize_node(c as usize, deeper, min_visits), + _ => Vec::new(), + }, + }) + .collect() + } + + fn expand_root(&mut self, job: &mut Job, moves: Vec, priors: Vec) { + let (moves, priors) = match &job.restrict { + Some(keep) => restrict_moves(moves, priors, keep), + None => (moves, priors), + }; + self.tree[0].expand(moves, priors); + self.apply_root_noise(job); + } + + /// Descend one wave of leaves. Terminal and tablebase leaves are backed up + /// at once; the rest wait for the wave's NN batch. + fn collect_wave(&mut self, job: &mut Job) -> (Vec, Vec) { + let wave = (self.params.sim_batch as u32).min(job.sims - job.sims_done) as usize; + let mut pending: Vec = Vec::with_capacity(wave); + let mut batch: Vec = Vec::new(); + let mut batch_index: HashMap = HashMap::new(); + + for _ in 0..wave { + let (node_idx, path, pos, path_keys) = self.descend(); + let key = zobrist(&pos); + let mut all_keys = self.history.clone(); + all_keys.extend_from_slice(&path_keys); + let root_idx = self.history.len() - 1; + if let Some(t) = search_terminal_value(&pos, &all_keys, key, root_idx) { + backup_vl(&mut self.tree, &path, t); + job.sims_done += 1; + continue; + } + if let Some(t) = self.leaf_tablebase(&pos) { + backup_vl(&mut self.tree, &path, t); + job.sims_done += 1; + job.tb_hits += 1; + continue; + } + let moves: Vec = pos.legal_moves().to_vec(); + // Defer cached (TT) hits and NN leaves alike: their virtual loss + // stays applied through the wave so concurrent descents diversify + // (mirrors Pos2MoveV2MctsBot._run_batch). Backing TT hits up + // immediately collapses search breadth once the TT fills, which + // wrecks play at high sim counts. + let eval = if let Some((priors, value)) = self.tt.get(&key).cloned() { + job.tt_hits += 1; + LeafEval::Cached(priors, value) + } else { + let legal_in_requests = self.params.legal_in_requests; + let batch_idx = *batch_index.entry(key).or_insert_with(|| { + let (tokens, player, castling, ep) = encode_position(&pos); + let legal = if legal_in_requests { legal_indices(&moves) } else { Vec::new() }; + batch.push(EvalRequest { tokens, player, castling, ep, legal }); + batch.len() - 1 + }); + LeafEval::Batch(batch_idx) + }; + pending.push(PendingLeaf { node: node_idx, path, key, moves, eval }); + } + (pending, batch) + } + + fn resolve_wave(&mut self, job: &mut Job, pending: Vec, outputs: Vec) { + for leaf in pending { + let prior_temp = self.params.prior_temp; + let (priors, value) = match leaf.eval { + LeafEval::Cached(priors, value) => (priors, value), + // A later leaf in this wave may have inserted the key; prefer + // the TT entry so transpositions share one eval. + LeafEval::Batch(bi) => match self.tt.get(&leaf.key) { + Some(hit) => hit.clone(), + None => { + let priors = priors_for(&leaf.moves, &outputs[bi].logits, prior_temp); + self.insert_tt(leaf.key, priors.clone(), outputs[bi].value); + (priors, outputs[bi].value) + } + }, + }; + if !self.tree[leaf.node].expanded { + self.tree[leaf.node].expand(leaf.moves, priors); + } + backup_vl(&mut self.tree, &leaf.path, value); + job.sims_done += 1; + } + } + + /// Exact WDL for a leaf the tables cover, from its side-to-move POV. Only + /// probed straight after a capture or pawn move (halfmove clock 0), where + /// WDL is exact under the 50-move rule; cursed wins and blessed losses + /// score as the draws they are. + fn leaf_tablebase(&self, pos: &Chess) -> Option { + let tb = self.params.syzygy.as_ref()?; + if pos.halfmoves() != 0 || pos.board().occupied().count() > tb.max_pieces() { + return None; + } + Some(match tb.probe_wdl_after_zeroing(pos).ok()? { + Wdl::Win => 1.0, + Wdl::Loss => -1.0, + Wdl::CursedWin | Wdl::Draw | Wdl::BlessedLoss => 0.0, + }) + } + + fn root_tablebase(&self) -> RootTb { + let Some(tb) = &self.params.syzygy else { + return RootTb::Off; + }; + if self.pos.board().occupied().count() > tb.max_pieces() { + return RootTb::Off; + } + // Each move's result for us under the 50-move rule from the current + // clock: +1 win, 0 draw, -1 loss. Ambiguous (DTZ-rounded) verdicts are + // read pessimistically for us. + let moves = self.pos.legal_moves(); + let mut verdicts = Vec::with_capacity(moves.len()); + for m in &moves { + let mut after = self.pos.clone(); + after.play_unchecked(m); + let v = match tb.probe_wdl(&after) { + Ok(AmbiguousWdl::Loss) => 1, + Ok(AmbiguousWdl::Win | AmbiguousWdl::MaybeWin) => -1, + Ok(_) => 0, + Err(_) => return RootTb::Off, + }; + verdicts.push(v); + } + let Some(&best) = verdicts.iter().max() else { + return RootTb::Off; + }; + if best == 1 { + return match tb.best_move(&self.pos) { + Ok(Some((m, _))) => RootTb::Play(m), + _ => RootTb::Off, + }; + } + RootTb::Restrict( + moves + .iter() + .zip(&verdicts) + .filter(|&(_, &v)| v == best) + .map(|(m, _)| m.clone()) + .collect(), + ) + } + + /// Virtual-loss descent to an unexpanded node; returns (leaf node index, + /// path edges, leaf position, zobrist keys pushed en route). + fn descend(&mut self) -> (usize, Vec<(usize, usize)>, Chess, Vec) { + let mut node_idx = 0usize; + let mut pos = self.pos.clone(); + let mut path = Vec::new(); + let mut keys = Vec::new(); + loop { + if !self.tree[node_idx].expanded { + return (node_idx, path, pos, keys); + } + let idx = puct_select(&self.tree[node_idx], self.params.c_puct, self.params.fpu); + { + let node = &mut self.tree[node_idx]; + node.n[idx] += 1; // virtual loss + node.w[idx] += 1.0; + } + path.push((node_idx, idx)); + let mv = self.tree[node_idx].moves[idx].clone(); + pos.play_unchecked(&mv); + keys.push(zobrist(&pos)); + let child = self.tree[node_idx].children[idx]; + node_idx = if child >= 0 { + child as usize + } else { + self.tree.push(Node::default()); + let new_idx = self.tree.len() - 1; + self.tree[node_idx].children[idx] = new_idx as i32; + new_idx + }; + } + } + + /// Root children as (move, visits, Q from the root side-to-move POV, prior), + /// most-visited first. Diagnostic only. + pub fn root_stats(&self) -> Vec<(Move, u32, f64, f32)> { + let root = &self.tree[0]; + let mut out: Vec<_> = (0..root.moves.len()) + .map(|i| { + let q = if root.n[i] > 0 { -root.w[i] / root.n[i] as f64 } else { f64::NAN }; + (root.moves[i].clone(), root.n[i], q, root.priors[i]) + }) + .collect(); + out.sort_by(|a, b| b.1.cmp(&a.1)); + out + } + + /// Most-visited line from the root as (move, visits, Q from the mover's + /// POV). Diagnostic only. + pub fn pv(&self, max_len: usize) -> Vec<(Move, u32, f64)> { + let mut out = Vec::new(); + let mut node = 0usize; + while out.len() < max_len && self.tree[node].expanded { + let nd = &self.tree[node]; + let Some(i) = (0..nd.moves.len()).max_by_key(|&i| nd.n[i]) else { break }; + if nd.n[i] == 0 { + break; + } + out.push((nd.moves[i].clone(), nd.n[i], -nd.w[i] / nd.n[i] as f64)); + if nd.children[i] < 0 { + break; + } + node = nd.children[i] as usize; + } + out + } + + /// Raw value-head estimate for a position (side-to-move POV), no search. + pub fn raw_value(&mut self, pos: &Chess) -> Result { + let (tokens, player, castling, ep) = encode_position(pos); + Ok(self + .eval + .eval_batch(&[EvalRequest { tokens, player, castling, ep, legal: Vec::new() }])? + .remove(0) + .value) + } + + fn insert_tt(&mut self, key: u64, priors: Vec, value: f32) { + if self.tt.len() >= self.params.tt_cap { + self.tt.clear(); // crude but rare; avoids unbounded growth + } + self.tt.insert(key, (priors, value)); + } +} + +/// Flat logit index of each move, in order. +pub fn legal_indices(moves: &[Move]) -> Vec { + moves + .iter() + .map(|m| { + let (f, t, p) = move_coords(m); + (f * NUM_PLANES + action_plane(f, t, p)) as u16 + }) + .collect() +} + +/// Softmax priors over `moves` from full logits, or from logits already +/// gathered in move order (see `EvalOutput::logits`) -- the same floats either way. +fn priors_for(moves: &[Move], logits: &[f32], prior_temp: f32) -> Vec { + let mut scores: Vec = if logits.len() == 64 * NUM_PLANES { + moves + .iter() + .map(|m| { + let (f, t, p) = move_coords(m); + logits[f * NUM_PLANES + action_plane(f, t, p)] + }) + .collect() + } else { + assert_eq!(logits.len(), moves.len(), "gathered logits do not match the legal moves"); + logits.to_vec() + }; + softmax_priors(&mut scores, prior_temp); + scores +} + +/// Keep only `keep` (with their priors, renormalized) from a root expansion. +fn restrict_moves(moves: Vec, priors: Vec, keep: &[Move]) -> (Vec, Vec) { + let (moves, mut priors): (Vec, Vec) = + moves.into_iter().zip(priors).filter(|(m, _)| keep.contains(m)).unzip(); + let total: f32 = priors.iter().sum(); + let k = priors.len() as f32; + for p in priors.iter_mut() { + *p = if total > 0.0 { *p / total } else { 1.0 / k }; + } + (moves, priors) +} + +/// Copy the subtree under `root` into a fresh arena with the root at index 0. +fn reroot(tree: &[Node], root: usize) -> Vec { + let mut map: HashMap = HashMap::new(); + let mut order = vec![root]; + map.insert(root, 0); + let mut i = 0; + while i < order.len() { + let old = order[i]; + i += 1; + for &c in &tree[old].children { + if c >= 0 && !map.contains_key(&(c as usize)) { + map.insert(c as usize, order.len()); + order.push(c as usize); + } + } + } + order + .iter() + .map(|&old| { + let node = &tree[old]; + Node { + expanded: node.expanded, + moves: node.moves.clone(), + priors: node.priors.clone(), + n: node.n.clone(), + w: node.w.clone(), + children: node + .children + .iter() + .map(|&c| if c >= 0 { map[&(c as usize)] as i32 } else { -1 }) + .collect(), + } + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + use shakmaty::fen::Fen; + use shakmaty::uci::UciMove; + use shakmaty::CastlingMode; + + /// Uniform priors, constant value — search behavior then depends only on + /// the game-theoretic terminal values. + struct UniformEval; + + impl Evaluator for UniformEval { + fn eval_batch(&mut self, batch: &[EvalRequest]) -> Result> { + Ok(batch + .iter() + .map(|_| EvalOutput { logits: vec![0.0; 64 * NUM_PLANES], value: 0.0 }) + .collect()) + } + } + + fn pos(fen: &str) -> Chess { + fen.parse::() + .unwrap() + .into_position(CastlingMode::Standard) + .unwrap() + } + + fn mv(p: &Chess, uci: &str) -> Move { + UciMove::from_ascii(uci.as_bytes()) + .unwrap() + .to_move(p) + .unwrap() + } + + #[test] + fn finds_mate_in_one() { + // Back-rank: Ra1-a8 is mate. + let p = pos("6k1/5ppp/8/8/8/8/8/R5K1 w - - 0 1"); + let mut s = Search::new(UniformEval, SearchParams::default()); + s.set_position(p, &[]); + let r = s.go(256, None, &AtomicBool::new(false)).unwrap(); + assert_eq!( + r.best.to_uci(CastlingMode::Standard).to_string(), + "a1a8", + "should find the back-rank mate" + ); + assert!(r.value > 0.9, "root value should be near +1, got {}", r.value); + } + + #[test] + fn tree_summary_follows_the_search() { + let p = pos("6k1/5ppp/8/8/8/8/8/R5K1 w - - 0 1"); + let mut s = Search::new(UniformEval, SearchParams::default()); + s.set_position(p, &[]); + let r = s.go(256, None, &AtomicBool::new(false)).unwrap(); + let tree = s.summarize_tree(&[3, 2], 2); + assert!(!tree.is_empty() && tree.len() <= 3); + assert_eq!(tree[0].mv, r.best, "the most-visited branch is the move played"); + assert!(tree.windows(2).all(|w| w[0].visits >= w[1].visits)); + assert!(tree[0].q > 0.9, "mate scores for the side that plays it"); + assert!(tree.iter().all(|t| t.children.len() <= 2 && t.children.iter().all(|c| c.children.is_empty()))); + } + + #[test] + fn depth_stats_measure_the_tree() { + let mut s = Search::new(UniformEval, SearchParams::default()); + s.set_position(pos("4k3/8/8/8/8/8/8/R3K3 w Q - 0 1"), &[]); + s.go(512, None, &AtomicBool::new(false)).unwrap(); + let d = s.depth_stats(); + assert!(d.mean >= 1.0 && d.mean <= d.max as f32, "mean {} max {}", d.mean, d.max); + assert!(d.main_line >= 1 && d.main_line <= d.max); + assert!(d.max > 2, "512 sims should reach past two plies, got {}", d.max); + } + + #[test] + fn detects_threefold_in_search() { + // K+R vs K: after the same position has occurred twice in the game + // history, the search must see that one more repetition is a draw + // (value 0), not a win. + let start = pos("8/8/8/4k3/8/8/4K3/7R w - - 0 1"); + // Rh1-g1-h1 with king shuffles e5-d5: reaches the start position + // (w to move) a 2nd time; a 3rd occurrence inside the search is a draw. + let mut moves = Vec::new(); + let mut p = start.clone(); + for u in ["h1g1", "e5d5", "g1h1", "d5e5"] { + let m = mv(&p, u); + p.play_unchecked(&m); + moves.push(m); + } + let mut s = Search::new(UniformEval, SearchParams::default()); + s.set_position(start, &moves); + let r = s.go(128, None, &AtomicBool::new(false)).unwrap(); + // With a uniform NN the absolute move doesn't matter; the search must + // simply terminate (repetition leaves are terminal, not NN-evaluated) + // and the root value must be drawish, not a fantasy win. + assert!(r.value.abs() < 0.5, "root value should be drawish, got {}", r.value); + assert_eq!(r.sims, 128); + } + + /// Value = material balance from the side to move's POV; policy = uniform + /// plus a bonus for checking moves. A crude stand-in for a real net, but + /// one that can tell winning from losing and looks at forcing moves first. + struct CheckingMaterialEval; + + fn request_to_pos(r: &EvalRequest) -> Chess { + const CH: &[u8; 13] = b".PNBRQKpnbrqk"; + let mut fen = String::new(); + for rank in (0..8).rev() { + let mut empty = 0; + for file in 0..8 { + match r.tokens[rank * 8 + file] { + 0 => empty += 1, + t => { + if empty > 0 { + fen.push_str(&empty.to_string()); + empty = 0; + } + fen.push(CH[t as usize] as char); + } + } + } + if empty > 0 { + fen.push_str(&empty.to_string()); + } + if rank > 0 { + fen.push('/'); + } + } + fen.push_str(if r.player == 1 { " w - - 0 1" } else { " b - - 0 1" }); + pos(&fen) + } + + impl Evaluator for CheckingMaterialEval { + fn eval_batch(&mut self, batch: &[EvalRequest]) -> Result> { + const VAL: [f32; 7] = [0.0, 1.0, 3.0, 3.0, 5.0, 9.0, 0.0]; + Ok(batch + .iter() + .map(|r| { + let white: f32 = r + .tokens + .iter() + .map(|&t| match t { + 1..=6 => VAL[t as usize], + 7..=12 => -VAL[t as usize - 6], + _ => 0.0, + }) + .sum(); + let stm = if r.player == 1 { white } else { -white }; + let p = request_to_pos(r); + let mut logits = vec![0.0; 64 * NUM_PLANES]; + for m in p.legal_moves() { + let mut after = p.clone(); + after.play_unchecked(&m); + if after.is_check() { + let (f, t, pr) = move_coords(&m); + logits[f * NUM_PLANES + action_plane(f, t, pr)] = 3.0; + } + } + EvalOutput { logits, value: (stm / 3.0).tanh() } + }) + .collect()) + } + } + + #[test] + fn finds_perpetual_via_twofold() { + // Black is a queen and rook down; per Stockfish (d26) every move loses + // (-6.5 or worse) except Qf2+ Kh1 Qf1+ Kh2 Qf2+, a perpetual. With the + // two-fold rule that cycle scores as a draw 5 plies in; threefold-only + // needs 9, which this budget does not reach. + let p = pos("6k1/5ppp/R7/Q7/3q4/6PP/7K/8 b - - 0 1"); + let mut s = Search::new(CheckingMaterialEval, SearchParams::default()); + s.set_position(p, &[]); + let r = s.go(3000, None, &AtomicBool::new(false)).unwrap(); + let best = r.best.to_uci(CastlingMode::Standard).to_string(); + assert_eq!(best, "d4f2", "should take the perpetual (value {})", r.value); + assert!(r.value > -0.2, "perpetual should score near 0, got {}", r.value); + } + + #[test] + fn twofold_only_counts_repeats_inside_the_search() { + use crate::encoding::search_terminal_value; + let p = Chess::default(); // non-terminal; only the key sequence matters + let (a, b, c, d) = (1u64, 2, 3, 4); + // Cycle entirely after the root (root at index 0): draw. + assert_eq!(search_terminal_value(&p, &[a, b, c, d, a], a, 0), Some(0.0)); + // The earlier occurrence predates the root: only one repeat, play on. + assert_eq!(search_terminal_value(&p, &[a, b, c, d, a], a, 1), None); + // ... unless it is the third occurrence overall. + assert_eq!(search_terminal_value(&p, &[a, b, a, c, d, a], a, 3), Some(0.0)); + // No repeat at all. + assert_eq!(search_terminal_value(&p, &[a, b, c, d], d, 0), None); + } + + /// Tables from $SYZYGY_PATH (3-4-piece is enough for these tests). + fn syzygy() -> Arc> { + let path = std::env::var("SYZYGY_PATH").expect("set SYZYGY_PATH to run tablebase tests"); + let mut tb = Tablebase::new(); + for dir in path.split(':') { + tb.add_directory(dir).unwrap(); + } + Arc::new(tb) + } + + fn tb_params() -> SearchParams { + SearchParams { syzygy: Some(syzygy()), ..SearchParams::default() } + } + + /// The opponent's WDL after `m` is played from `p`. + fn wdl_after(tb: &Tablebase, p: &Chess, m: &Move) -> AmbiguousWdl { + let mut after = p.clone(); + after.play_unchecked(m); + tb.probe_wdl(&after).unwrap() + } + + #[test] + #[ignore = "needs SYZYGY_PATH"] + fn tablebase_win_at_root_plays_without_search() { + let p = pos("8/2K5/8/8/4k3/8/8/6R1 w - - 0 1"); // KRvK, DTZ 25 + let mut s = Search::new(UniformEval, tb_params()); + s.set_position(p.clone(), &[]); + let r = s.go(800, None, &AtomicBool::new(false)).unwrap(); + assert_eq!((r.sims, r.tb_hits), (0, 1), "should not search a won TB root"); + assert_eq!(wdl_after(&syzygy(), &p, &r.best), AmbiguousWdl::Loss); + } + + #[test] + #[ignore = "needs SYZYGY_PATH"] + fn tablebase_draw_at_root_keeps_the_draw() { + // Drawn KRvKR where 11 of 19 moves lose, all of them quiet: in-tree + // probes (zeroing moves only) cannot see these, root filtering must. + let p = pos("8/7r/8/8/3K4/8/3k4/4R3 w - - 0 1"); + let tb = syzygy(); + let mut s = Search::new(UniformEval, tb_params()); + s.set_position(p.clone(), &[]); + let r = s.go(400, None, &AtomicBool::new(false)).unwrap(); + assert_eq!(s.root_stats().len(), 8, "root should hold only the 8 drawing moves"); + assert!( + !matches!(wdl_after(&tb, &p, &r.best), AmbiguousWdl::Win | AmbiguousWdl::MaybeWin), + "played a losing move" + ); + } + + #[test] + #[ignore = "needs SYZYGY_PATH"] + fn tablebase_scores_captures_into_covered_endgames() { + // 5 pieces at the root (beyond 3-4-piece tables): searched normally, + // but Kxd2/Qxd2 land in KQvKR and must be scored from the tables. + let p = pos("8/8/8/3k4/8/2r5/3p4/3QK3 w - - 0 1"); + let mut s = Search::new(UniformEval, tb_params()); + s.set_position(p, &[]); + let r = s.go(400, None, &AtomicBool::new(false)).unwrap(); + assert!(r.sims == 400 && r.tb_hits > 0, "sims {} tb hits {}", r.sims, r.tb_hits); + } + + #[test] + fn tree_reuse_reroots() { + let start = Chess::default(); + let mut s = Search::new(UniformEval, SearchParams::default()); + s.set_position(start.clone(), &[]); + s.go(128, None, &AtomicBool::new(false)).unwrap(); + let nodes_before = s.tree.len(); + assert!(nodes_before > 1); + + // Advance by one ply; the tree should re-root into the e2e4 subtree + // (visited >5 times at 128 sims over 20 root moves), not reset. + let m1 = mv(s.position(), "e2e4"); + s.set_position(start, &[m1]); + assert!( + s.tree[0].expanded, + "re-rooted tree should keep the searched subtree" + ); + assert!(s.tree.len() < nodes_before, "subtree must be a strict subset"); + } +} diff --git a/rust/chess-core/src/selfplay.rs b/rust/chess-core/src/selfplay.rs new file mode 100644 index 0000000000000000000000000000000000000000..be3cc3236835964e5a74877016da715481c30358 --- /dev/null +++ b/rust/chess-core/src/selfplay.rs @@ -0,0 +1,406 @@ +//! One self-play game on the deployed bot's search (`search::Search`), driven +//! one wave at a time so that a batched runner (selfplay-core +//! `SelfPlayEngine`) can evaluate the waves of many games together. +//! +//! The search is the bot's: virtual-loss waves of `sim_batch` leaves with TT +//! hits deferred to the end of the wave, the two-fold rule inside the tree, +//! and the tree kept and re-rooted from move to move (one tree per game: both +//! sides are the same network). On top of it, the expert-iteration options: +//! +//! * playout cap randomization (KataGo): each move is a full search of +//! `num_sims` with probability `full_frac`, else `fast_sims`. Only full +//! searches are policy targets (the `full` flag). A budget counts fresh sims, +//! or, with `cap_total_full` / `cap_total_fast`, the root's total visits: +//! the reused tree's warm visits count toward it and only the rest is +//! searched (none when the tree already holds the budget); +//! * root Dirichlet noise on full searches (`search::RootNoise`); +//! * move temperature for the first `temp_plies` half-moves (the bot's own +//! sampler, seeded); +//! * resignation once the root value stays past `resign_threshold` for +//! `resign_plies` plies, except in a `no_resign_frac` share of games. +//! +//! A record is the position before the move, the search's root value and the +//! root visit counts -- warm visits from the reused tree included, as Lc0 +//! trains on them. + +use rand::prelude::*; +use rand::rngs::StdRng; +use shakmaty::{CastlingMode, Chess, Color, Move, Position}; + +use crate::encoding::{action_plane, encode_position, halfmove, move_coords, terminal_value, zobrist, + NUM_PLANES}; +use crate::search::{EvalOutput, EvalRequest, Job, NoEval, RootNoise, Search, SearchParams, Step}; + +#[derive(Clone, Copy)] +pub struct SelfPlayRules { + pub num_sims: u32, + pub fast_sims: u32, + pub full_frac: f64, + pub dirichlet_alpha: f64, + pub dirichlet_eps: f64, + pub move_temp: f64, + pub temp_plies: u32, + pub resign_threshold: f32, + pub resign_plies: u32, + pub no_resign_frac: f64, + pub max_plies: u32, + pub sim_batch: usize, + pub c_puct: f64, + pub fpu: f64, + pub prior_temp: f32, + pub tt_cap: usize, + /// The full / fast budget caps the root's total visits, warm ones included, + /// instead of counting fresh sims. + pub cap_total_full: bool, + pub cap_total_fast: bool, +} + +pub struct Record { + pub tokens: [u8; 64], + pub player: u8, + pub castling: u8, + pub ep: u8, + pub halfmove: u16, + pub root_v: f32, + pub full: u8, + pub visit_idx: Vec, // from_sq * 73 + plane + pub visit_cnt: Vec, +} + +pub struct SelfPlayGame { + pub id: usize, + pub opening: usize, + start: Chess, + moves: Vec, + moves_uci: Vec, + pos: Chess, + history: Vec, + search: Search, + job: Option, + full: bool, + out: Option>, + rng: StdRng, + resign_allowed: bool, + resign_streak: u32, + resign_sign: i32, + records: Vec, + end: Option<(f32, &'static str)>, +} + +impl SelfPlayGame { + /// All of the game's randomness (budgets, noise, temperature, resignation) + /// derives from `seed`. + pub fn new(id: usize, opening: usize, start: Chess, rules: &SelfPlayRules, seed: u64) -> Self { + let mut rng = StdRng::seed_from_u64(seed); + let params = SearchParams { + c_puct: rules.c_puct, + fpu: rules.fpu, + prior_temp: rules.prior_temp, + sim_batch: rules.sim_batch, + move_temp: rules.move_temp, + move_temp_plies: rules.temp_plies, + tt_cap: rules.tt_cap, + legal_in_requests: true, + ..SearchParams::default() + }; + let mut search = Search::new(NoEval, params); + search.seed_rng(rng.gen()); + let resign_allowed = rng.gen::() >= rules.no_resign_frac; + let mut g = SelfPlayGame { + id, + opening, + history: vec![zobrist(&start)], + pos: start.clone(), + start, + moves: Vec::new(), + moves_uci: Vec::new(), + search, + job: None, + full: true, + out: None, + rng, + resign_allowed, + resign_streak: 0, + resign_sign: 0, + records: Vec::new(), + end: None, + }; + g.check_end(rules); + g + } + + /// (z from white's POV, reason) once the game is over. + pub fn end(&self) -> Option<(f32, &'static str)> { + self.end + } + + pub fn moves_uci(&self) -> &[String] { + &self.moves_uci + } + + pub fn records(&self) -> &[Record] { + &self.records + } + + pub fn resign_allowed(&self) -> bool { + self.resign_allowed + } + + pub fn tt_len(&self) -> usize { + self.search.tt_len() + } + + pub fn pending(&self) -> Option<&[EvalRequest]> { + self.out.as_deref() + } + + pub fn resolve(&mut self, outputs: Vec) { + self.out = None; + self.search.resolve(self.job.as_mut().expect("eval out without a job"), outputs); + } + + /// Whether the game is live but has nothing to do -- a bug. + pub fn stalled(&self) -> bool { + self.end.is_none() && self.out.is_none() + } + + /// (budget, full) for the next move. + fn draw_budget(&mut self, rules: &SelfPlayRules) -> (u32, bool) { + if rules.fast_sims == 0 || self.rng.gen::() < rules.full_frac { + (rules.num_sims, true) + } else { + (rules.fast_sims, false) + } + } + + /// Step the search until it waits on an eval or the game ends. + pub fn advance(&mut self, rules: &SelfPlayRules) { + while self.end.is_none() && self.out.is_none() { + if self.job.is_none() { + self.search.set_position(self.start.clone(), &self.moves); + let (budget, full) = self.draw_budget(rules); + let cap_total = if full { rules.cap_total_full } else { rules.cap_total_fast }; + let sims = if cap_total { budget.saturating_sub(self.search.root_visits()) } else { budget }; + let noise = (full && rules.dirichlet_alpha > 0.0).then(|| RootNoise { + alpha: rules.dirichlet_alpha, + eps: rules.dirichlet_eps, + seed: self.rng.gen(), + }); + self.full = full; + self.job = Some(self.search.start_with_noise(sims, noise)); + } + match self.search.step(self.job.as_mut().unwrap()) { + Step::Eval(reqs) => self.out = Some(reqs), + Step::Wave => {} + Step::Done => { + let job = self.job.take().unwrap(); + let result = self.search.finish(job); + self.record(result.value); + self.play(result.best, result.value, rules); + } + } + } + } + + fn record(&mut self, root_v: f32) { + let (tokens, player, castling, ep) = encode_position(&self.pos); + let (mut visit_idx, mut visit_cnt) = (Vec::new(), Vec::new()); + for (mv, n, _, _) in self.search.root_stats() { + if n > 0 { + let (f, t, p) = move_coords(&mv); + visit_idx.push((f * NUM_PLANES + action_plane(f, t, p)) as u16); + visit_cnt.push(n.min(u16::MAX as u32) as u16); + } + } + self.records.push(Record { + tokens, + player, + castling, + ep, + halfmove: halfmove(&self.pos).min(u16::MAX as u32) as u16, + root_v, + full: self.full as u8, + visit_idx, + visit_cnt, + }); + } + + fn play(&mut self, best: Move, root_v: f32, rules: &SelfPlayRules) { + let white_to_move = self.pos.turn() == Color::White; + self.moves_uci.push(best.to_uci(CastlingMode::Standard).to_string()); + self.pos.play_unchecked(&best); + self.history.push(zobrist(&self.pos)); + self.moves.push(best); + + // Resign bookkeeping on the white-POV root value. + let v_white = if white_to_move { root_v } else { -root_v }; + if v_white.abs() >= rules.resign_threshold { + let sign = if v_white > 0.0 { 1 } else { -1 }; + self.resign_streak = if sign == self.resign_sign { self.resign_streak + 1 } else { 1 }; + self.resign_sign = sign; + } else { + self.resign_streak = 0; + } + self.check_end(rules); + } + + fn check_end(&mut self, rules: &SelfPlayRules) { + let key = *self.history.last().unwrap(); + self.end = if let Some(t) = terminal_value(&self.pos, &self.history, key) { + // Mate scores -1 for the side to move; the side that just moved wins. + let z = if t < 0.0 { + if self.pos.turn() == Color::Black { 1.0 } else { -1.0 } + } else { + 0.0 + }; + Some((z, "terminal")) + } else if self.resign_allowed && self.resign_streak >= rules.resign_plies { + Some((self.resign_sign as f32, "resign")) + } else if self.moves.len() as u32 >= rules.max_plies { + Some((0.0, "max_plies")) + } else { + None + }; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::search::Evaluator; + use shakmaty::fen::Fen; + use std::sync::atomic::AtomicBool; + + struct HashEval; + + impl Evaluator for HashEval { + fn eval_batch(&mut self, batch: &[EvalRequest]) -> anyhow::Result> { + Ok(batch.iter().map(hash_out).collect()) + } + } + + fn hash_out(r: &EvalRequest) -> EvalOutput { + let mut h = r.player as f64 * 0.7 + r.castling as f64 * 0.3 + r.ep as f64 * 0.11; + for (i, &t) in r.tokens.iter().enumerate() { + h += (t as f64) * ((i as f64) * 0.618).sin(); + } + let logits = (0..64 * NUM_PLANES) + .map(|k| ((h * 0.37 + k as f64 * 0.0131).sin() * 2.5) as f32) + .collect(); + EvalOutput { logits, value: ((h * 0.173).sin() * 0.9) as f32 } + } + + fn rules() -> SelfPlayRules { + SelfPlayRules { + num_sims: 64, fast_sims: 16, full_frac: 0.3, dirichlet_alpha: 0.0, dirichlet_eps: 0.25, + move_temp: 1.0, temp_plies: 10, resign_threshold: 2.0, resign_plies: 6, + no_resign_frac: 0.1, max_plies: 40, sim_batch: 16, c_puct: 1.0, fpu: 0.2, + prior_temp: 1.0, tt_cap: 2_000_000, cap_total_full: false, cap_total_fast: false, + } + } + + fn start() -> Chess { + "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1" + .parse::().unwrap().into_position(CastlingMode::Standard).unwrap() + } + + fn batched(rules: &SelfPlayRules, seed: u64) -> SelfPlayGame { + let mut g = SelfPlayGame::new(0, 0, start(), rules, seed); + while g.end().is_none() { + g.advance(rules); + if let Some(reqs) = g.pending() { + let outs = reqs.iter().map(hash_out).collect(); + g.resolve(outs); + } + } + g + } + + /// The bot's own flow through go() with the same draws as `SelfPlayGame` + /// (search rng, resign flag, then one budget draw per move), tree reuse + /// through set_position, temperature through the bot's own sampler: + /// (moves, full flags, warm root visits before each search). + fn reference(r: &SelfPlayRules, seed: u64, plies: usize) -> (Vec, Vec, Vec) { + let mut rng = StdRng::seed_from_u64(seed); + let params = SearchParams { sim_batch: r.sim_batch, move_temp: r.move_temp, + move_temp_plies: r.temp_plies, ..SearchParams::default() }; + let mut s = Search::new(HashEval, params); + s.seed_rng(rng.gen()); + let _resign_allowed = rng.gen::() >= r.no_resign_frac; + let (mut moves, mut want, mut fulls, mut warms) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for _ in 0..plies { + s.set_position(start(), &moves); + let full = rng.gen::() < r.full_frac; + let budget = if full { r.num_sims } else { r.fast_sims }; + let warm = s.root_visits(); + let capped = if full { r.cap_total_full } else { r.cap_total_fast }; + let sims = if capped { budget.saturating_sub(warm) } else { budget }; + let res = s.go(sims, None, &AtomicBool::new(false)).unwrap(); + want.push(res.best.to_uci(CastlingMode::Standard).to_string()); + fulls.push(full as u8); + warms.push(warm); + moves.push(res.best); + } + (want, fulls, warms) + } + + #[test] + fn batched_game_is_the_bots_search_move_for_move() { + for (cap_total_full, cap_total_fast) in [(false, false), (false, true), (true, true)] { + let r = SelfPlayRules { cap_total_full, cap_total_fast, ..rules() }; + let g = batched(&r, 11); + let (want, fulls, _) = reference(&r, 11, g.moves_uci().len()); + assert!(want.len() > 10); + assert_eq!(g.moves_uci(), &want[..], "caps {cap_total_full} {cap_total_fast}"); + assert_eq!(g.records().iter().map(|r| r.full).collect::>(), fulls); + } + } + + #[test] + fn capped_budgets_count_the_warm_visits() { + let r = SelfPlayRules { move_temp: 0.0, cap_total_full: true, cap_total_fast: true, ..rules() }; + let g = batched(&r, 3); + let (_, _, warms) = reference(&r, 3, g.moves_uci().len()); + let (mut topped_up, mut skipped) = (0, 0); + for (rec, &warm) in g.records().iter().zip(&warms) { + let budget = if rec.full == 1 { r.num_sims } else { r.fast_sims }; + let n: u32 = rec.visit_cnt.iter().map(|&c| c as u32).sum(); + // Searched up to the budget, or not at all when the reused tree held it. + assert_eq!(n, budget.max(warm), "warm {warm} budget {budget}"); + if warm >= budget { skipped += 1 } else if warm > 0 { topped_up += 1 } + } + assert!(topped_up > 0 && skipped > 0, "topped up {topped_up}, skipped {skipped}"); + } + + #[test] + fn visits_cover_the_fresh_budget_and_reuse_adds_warm_ones() { + let r = SelfPlayRules { move_temp: 0.0, ..rules() }; + let g = batched(&r, 3); + let sums: Vec = g.records().iter() + .map(|x| x.visit_cnt.iter().map(|&c| c as u32).sum()).collect(); + let first = &g.records()[0]; + // A fresh tree: exactly the budget (the root expansion is not a visit). + assert_eq!(sums[0], if first.full == 1 { r.num_sims } else { r.fast_sims }); + for (rec, &n) in g.records().iter().zip(&sums) { + assert!(n >= if rec.full == 1 { r.num_sims } else { r.fast_sims }); + } + assert!(g.records().iter().zip(&sums).any(|(rec, &n)| n > if rec.full == 1 { r.num_sims } + else { r.fast_sims }), + "tree reuse never carried a warm visit"); + } + + #[test] + fn noise_changes_full_searches_only_and_is_seeded() { + let quiet = SelfPlayRules { move_temp: 0.0, ..rules() }; + let noisy = SelfPlayRules { dirichlet_alpha: 0.3, ..quiet }; + let a = batched(&noisy, 5); + assert_eq!(a.moves_uci(), batched(&noisy, 5).moves_uci(), "noise must follow the seed"); + let b = batched(&quiet, 5); + // Same budget draws; up to the first full search the games must agree. + let first_full = a.records().iter().position(|r| r.full == 1).unwrap(); + assert_eq!(a.moves_uci()[..first_full], b.moves_uci()[..first_full]); + let differs = (0..a.records().len().min(b.records().len())) + .any(|i| a.records()[i].visit_cnt != b.records()[i].visit_cnt); + assert!(differs, "noise left every full search unchanged"); + } +} diff --git a/rust/chess-core/src/tree.rs b/rust/chess-core/src/tree.rs new file mode 100644 index 0000000000000000000000000000000000000000..2ede721986d69af06a0f0e4c83b0553aec7c4d8b --- /dev/null +++ b/rust/chess-core/src/tree.rs @@ -0,0 +1,81 @@ +//! Edge-centric MCTS tree primitives: node storage, PUCT selection with FPU, +//! virtual-loss backup, and prior softmax. Semantics mirror +//! `Pos2MoveV2MctsBot` exactly. + +use shakmaty::Move; + +#[derive(Default)] +pub struct Node { + pub expanded: bool, + pub moves: Vec, + pub priors: Vec, + pub n: Vec, + pub w: Vec, + pub children: Vec, // -1 = not materialized +} + +impl Node { + pub fn expand(&mut self, moves: Vec, priors: Vec) { + let k = moves.len(); + self.moves = moves; + self.priors = priors; + self.n = vec![0; k]; + self.w = vec![0.0; k]; + self.children = vec![-1; k]; + self.expanded = true; + } +} + +pub fn softmax_priors(scores: &mut [f32], temp: f32) { + let mut max = f32::NEG_INFINITY; + for s in scores.iter_mut() { + *s /= temp; + max = max.max(*s); + } + let mut sum = 0.0; + for s in scores.iter_mut() { + *s = (*s - max).exp(); + sum += *s; + } + for s in scores.iter_mut() { + *s /= sum; + } +} + +/// PUCT child selection: maximize Q + c_puct * sqrt(1+N) * P / (1+n), with +/// unvisited children valued at parent_Q - fpu (first-play urgency). +pub fn puct_select(node: &Node, c_puct: f64, fpu: f64) -> usize { + let total: u32 = node.n.iter().sum(); + let sqrt_total = (1.0 + total as f64).sqrt(); + let parent_q = if total > 0 { + -node.w.iter().sum::() / total as f64 + } else { + 0.0 + }; + let mut best = 0usize; + let mut best_score = f64::NEG_INFINITY; + for i in 0..node.moves.len() { + let q = if node.n[i] > 0 { + -node.w[i] / node.n[i] as f64 + } else { + parent_q - fpu + }; + let u = c_puct * sqrt_total * node.priors[i] as f64 / (1.0 + node.n[i] as f64); + let s = q + u; + if s > best_score { + best_score = s; + best = i; + } + } + best +} + +/// Negamax backup along a virtual-lossed path: N was already counted by the +/// virtual loss during descent; undo the +1.0 on W and apply the real value. +pub fn backup_vl(tree: &mut [Node], path: &[(usize, usize)], value: f32) { + let mut v = value as f64; + for &(node_idx, idx) in path.iter().rev() { + tree[node_idx].w[idx] += v - 1.0; + v = -v; + } +} diff --git a/rust/ct-bot/Cargo.toml b/rust/ct-bot/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..dc3f9e091b526b670188ed3e47632603afeb87da --- /dev/null +++ b/rust/ct-bot/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "ct-bot" +version = "0.1.0" +edition = "2021" + +[dependencies] +chess-core = { path = "../chess-core" } +shakmaty = { workspace = true } +shakmaty-syzygy = "0.25.3" +rand = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } +ort = { version = "=2.0.0-rc.13", features = ["ndarray"] } +ndarray = "0.17" +clap = { version = "4.5", features = ["derive", "env"] } +anyhow = "1" +tokio = { version = "1", features = ["rt-multi-thread", "macros", "time", "signal"] } +reqwest = { version = "0.12", default-features = false, features = ["json", "stream", "rustls-tls"] } +futures-util = "0.3" +env_logger = "0.11" +log = "0.4" +axum = { version = "0.8", default-features = false, features = ["http1", "json", "tokio"] } +tower-http = { version = "0.6", features = ["cors", "fs"] } + +[features] +cuda = ["ort/cuda", "ort/load-dynamic"] diff --git a/rust/ct-bot/Dockerfile b/rust/ct-bot/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..319729ada1aa961a8d3b98b21218722453477163 --- /dev/null +++ b/rust/ct-bot/Dockerfile @@ -0,0 +1,32 @@ +# Rust backend for the ChessTransformer web app (replaces backend/Dockerfile). +# Build from the repo root: docker build -f rust/ct-bot/Dockerfile . + +FROM rust:1.92-slim-trixie AS builder + +# ort's build script downloads the prebuilt ONNX Runtime over TLS (via ureq + +# native-tls, hence libssl-dev/pkg-config at build time). +# g++ provides libstdc++, which the statically-linked ONNX Runtime needs at link time. +RUN apt-get update && apt-get install -y --no-install-recommends \ + pkg-config ca-certificates libssl-dev g++ && rm -rf /var/lib/apt/lists/* + +WORKDIR /build +COPY rust/ ./rust/ +RUN cargo build --release --manifest-path rust/Cargo.toml -p ct-bot + +FROM debian:trixie-slim + +RUN apt-get update && apt-get install -y --no-install-recommends \ + curl ca-certificates && rm -rf /var/lib/apt/lists/* + +WORKDIR /app +COPY --from=builder /build/rust/target/release/ct-bot /usr/local/bin/ct-bot +# ONNX Runtime (CPU) is statically linked; only the model is needed at runtime. +# Base int8 model — the single model used across all deliveries (default, serve, +# lichess): ~1.75x faster on the CPU EP, and the base net scales with search far +# better than EMA (generate with: export_onnx.py --quantize). +COPY data/models/pos2move_v2.1/model.int8.onnx ./model.int8.onnx + +EXPOSE 5001 +ENV RUST_LOG=info + +CMD ["ct-bot", "serve", "--model", "/app/model.int8.onnx", "--port", "5001"] diff --git a/rust/ct-bot/src/bench.rs b/rust/ct-bot/src/bench.rs new file mode 100644 index 0000000000000000000000000000000000000000..1faee6436578828018fb94a98b495cb239d2c558 --- /dev/null +++ b/rust/ct-bot/src/bench.rs @@ -0,0 +1,136 @@ +//! Throughput benchmark: raw NN evals/sec at several batch sizes, and (once +//! the search exists) per-move search timings at several sim budgets. + +use std::time::Instant; + +use anyhow::Result; +use rand::prelude::*; +use rand::rngs::StdRng; +use shakmaty::{Chess, Position}; + +use crate::nn::{EvalRequest, Evaluator}; +use crate::BenchArgs; + +/// Random reachable positions (random playouts from the start position). +fn random_positions(n: usize, seed: u64) -> Vec { + let mut rng = StdRng::seed_from_u64(seed); + let mut out = Vec::with_capacity(n); + while out.len() < n { + let mut pos = Chess::default(); + for _ in 0..rng.gen_range(10..80) { + let moves = pos.legal_moves(); + if moves.is_empty() { + break; + } + pos.play_unchecked(moves.choose(&mut rng).unwrap()); + if pos.is_game_over() { + break; + } + } + out.push(pos); + } + out +} + +fn requests(positions: &[Chess]) -> Vec { + positions + .iter() + .map(|p| { + let (tokens, player, castling, ep) = chess_core::encoding::encode_position(p); + EvalRequest { tokens, player, castling, ep, legal: Vec::new() } + }) + .collect() +} + +pub fn run(args: &BenchArgs) -> Result<()> { + let mut eval = args.model.evaluator()?; + let positions = random_positions(256, 0); + let reqs = requests(&positions); + + println!("── NN throughput ({}) ──", args.model.model.display()); + println!("{:>6} {:>12} {:>12}", "batch", "ms/batch", "evals/s"); + for &batch in &[1usize, 8, 16, 32, 64, 128] { + // warmup + for chunk in reqs.chunks(batch).take(3) { + eval.eval_batch(chunk)?; + } + let t0 = Instant::now(); + let mut evals = 0usize; + while t0.elapsed().as_secs_f64() < 2.0 { + for chunk in reqs.chunks(batch) { + if chunk.len() < batch { + break; + } + eval.eval_batch(chunk)?; + evals += batch; + if t0.elapsed().as_secs_f64() >= 2.0 { + break; + } + } + } + let el = t0.elapsed().as_secs_f64(); + println!( + "{:>6} {:>12.2} {:>12.0}", + batch, + el / (evals as f64 / batch as f64) * 1e3, + evals as f64 / el + ); + } + + bench_search(args) +} + +/// Per-move search timings at each sim budget on startpos + 3 middlegame +/// positions. +fn bench_search(args: &BenchArgs) -> Result<()> { + use crate::search::{Search, SearchParams}; + use shakmaty::fen::Fen; + use shakmaty::CastlingMode; + use std::sync::atomic::AtomicBool; + + const FENS: [&str; 3] = [ + // Italian, Najdorf and QGD middlegames. + "r1bqk2r/pppp1ppp/2n2n2/2b1p3/2B1P3/2N2N2/PPPP1PPP/R1BQ1RK1 b kq - 5 5", + "rn1qkb1r/1p2pppp/p2p1n2/8/3NP1b1/2N1B3/PPP2PPP/R2QKB1R w KQkq - 2 7", + "r1bq1rk1/pp2bppp/2n1pn2/3p2B1/2PP4/2N1PN2/PP3PPP/R2QKB1R w KQ - 6 8", + ]; + + println!("\n── Search throughput (sim_batch={}) ──", args.sim_batch); + println!( + "{:>7} {:>10} {:>10} {:>10} {:>9}", + "sims", "s/move", "sims/s", "nn evals", "tt hits" + ); + let stop = AtomicBool::new(false); + for &sims in &args.sims { + let eval = args.model.evaluator()?; + let mut search = Search::new( + eval, + SearchParams { sim_batch: args.sim_batch, ..SearchParams::default() }, + ); + let (mut secs, mut nn, mut hits) = (0.0f64, 0u64, 0u64); + for fen in [None, Some(FENS[0]), Some(FENS[1]), Some(FENS[2])] { + let pos = match fen { + None => Chess::default(), + Some(f) => f + .parse::() + .unwrap() + .into_position(CastlingMode::Standard) + .unwrap(), + }; + search.set_position(pos, &[]); + let r = search.go(sims, None, &stop)?; + secs += r.elapsed.as_secs_f64(); + nn += r.nn_evals as u64; + hits += r.tt_hits as u64; + } + println!( + "{:>7} {:>10.2} {:>10.0} {:>10} {:>9}", + sims, + secs / 4.0, + sims as f64 * 4.0 / secs, + nn / 4, + hits / 4 + ); + } + Ok(()) +} diff --git a/rust/ct-bot/src/lichess.rs b/rust/ct-bot/src/lichess.rs new file mode 100644 index 0000000000000000000000000000000000000000..f292a0102f409d4ea4ee0197411c5e1f5a7e0d8e --- /dev/null +++ b/rust/ct-bot/src/lichess.rs @@ -0,0 +1,392 @@ +//! Lichess Bot API client: streams account events, accepts challenges by +//! policy, and plays each game over its own ndjson game stream with the +//! batched MCTS search (one Search + ONNX session per concurrent game). +//! +//! Docs: https://lichess.org/api#tag/Bot + +use std::collections::HashSet; +use std::sync::atomic::AtomicBool; +use std::sync::Arc; +use std::time::Duration; + +use anyhow::{Context, Result}; +use serde_json::Value; +use shakmaty::uci::UciMove; +use shakmaty::{fen::Fen, CastlingMode, Chess, Color, Move, Position}; +use tokio::sync::Mutex; + +use crate::nn::OnnxEvaluator; +use crate::search::{Search, SearchParams}; +use crate::timeman::TimeManager; +use crate::LichessArgs; + +#[derive(Clone)] +struct Client { + http: reqwest::Client, + base: String, +} + +impl Client { + fn new(base: &str, token: &str) -> Result { + let mut headers = reqwest::header::HeaderMap::new(); + let mut auth = reqwest::header::HeaderValue::from_str(&format!("Bearer {token}"))?; + auth.set_sensitive(true); + headers.insert(reqwest::header::AUTHORIZATION, auth); + Ok(Client { + http: reqwest::Client::builder() + .default_headers(headers) + .user_agent("ct-bot (ChessTransformer)") + .build()?, + base: base.trim_end_matches('/').to_string(), + }) + } + + async fn get_json(&self, path: &str) -> Result { + let resp = self.http.get(format!("{}{path}", self.base)).send().await?; + anyhow::ensure!(resp.status().is_success(), "GET {path}: {}", resp.status()); + Ok(resp.json().await?) + } + + async fn post(&self, path: &str, form: &[(&str, &str)]) -> Result<()> { + let resp = self + .http + .post(format!("{}{path}", self.base)) + .form(form) + .send() + .await?; + let status = resp.status(); + if !status.is_success() { + let body = resp.text().await.unwrap_or_default(); + anyhow::bail!("POST {path}: {status} {body}"); + } + Ok(()) + } + + async fn stream(&self, path: &str) -> Result { + let resp = self.http.get(format!("{}{path}", self.base)).send().await?; + anyhow::ensure!(resp.status().is_success(), "GET {path}: {}", resp.status()); + Ok(NdjsonStream { resp, buf: Vec::new() }) + } +} + +/// Newline-delimited JSON stream; empty lines are lichess keep-alives. +struct NdjsonStream { + resp: reqwest::Response, + buf: Vec, +} + +impl NdjsonStream { + async fn next(&mut self) -> Result> { + loop { + if let Some(i) = self.buf.iter().position(|&b| b == b'\n') { + let line: Vec = self.buf.drain(..=i).collect(); + let line = &line[..line.len() - 1]; + if line.is_empty() { + continue; + } + return Ok(Some(serde_json::from_slice(line)?)); + } + match self.resp.chunk().await? { + Some(chunk) => self.buf.extend_from_slice(&chunk), + None => return Ok(None), + } + } + } +} + +fn s<'a>(v: &'a Value, path: &[&str]) -> &'a str { + let mut cur = v; + for p in path { + cur = &cur[p]; + } + cur.as_str().unwrap_or("") +} + +struct Bot { + client: Client, + args: LichessArgs, + syzygy: Option>>, + our_id: String, + active: Arc>>, +} + +pub fn run(args: &LichessArgs) -> Result<()> { + let rt = tokio::runtime::Runtime::new()?; + rt.block_on(run_async(args.clone())) +} + +async fn run_async(args: LichessArgs) -> Result<()> { + let client = Client::new(&args.base_url, &args.token)?; + let account = client.get_json("/api/account").await.context("auth check")?; + let our_id = s(&account, &["id"]).to_string(); + let title = s(&account, &["title"]); + anyhow::ensure!(!our_id.is_empty(), "could not read account id"); + if title != "BOT" { + log::warn!("account '{our_id}' has no BOT title — upgrade it first (see README)"); + } + log::info!("connected as {our_id} ({title})"); + + let syzygy = crate::load_syzygy(&args.syzygy_path)?; + let bot = Arc::new(Bot { + client, + syzygy, + args, + our_id, + active: Arc::new(Mutex::new(HashSet::new())), + }); + + loop { + match bot.client.stream("/api/stream/event").await { + Ok(mut events) => loop { + match events.next().await { + Ok(Some(ev)) => bot.clone().handle_event(ev).await, + Ok(None) => break, + Err(e) => { + log::warn!("event stream error: {e:#}"); + break; + } + } + }, + Err(e) => log::warn!("event stream connect failed: {e:#}"), + } + log::info!("event stream closed; reconnecting in 5s"); + tokio::time::sleep(Duration::from_secs(5)).await; + } +} + +impl Bot { + async fn handle_event(self: Arc, ev: Value) { + match s(&ev, &["type"]) { + "challenge" => { + let c = &ev["challenge"]; + let id = s(c, &["id"]).to_string(); + if s(c, &["challenger", "id"]) == self.our_id { + return; // our own outgoing challenge + } + match self.challenge_verdict(c).await { + None => { + log::info!( + "accepting challenge {id} from {} ({} {})", + s(c, &["challenger", "id"]), + s(c, &["speed"]), + if c["rated"].as_bool().unwrap_or(false) { "rated" } else { "casual" }, + ); + if let Err(e) = self + .client + .post(&format!("/api/challenge/{id}/accept"), &[]) + .await + { + log::warn!("accept {id}: {e:#}"); + } + } + Some(reason) => { + log::info!("declining challenge {id}: {reason}"); + let _ = self + .client + .post(&format!("/api/challenge/{id}/decline"), &[("reason", reason)]) + .await; + } + } + } + "gameStart" => { + let game_id = s(&ev, &["game", "gameId"]).to_string(); + let game_id = if game_id.is_empty() { + s(&ev, &["game", "id"]).to_string() + } else { + game_id + }; + let mut active = self.active.lock().await; + if !active.insert(game_id.clone()) { + return; // already playing it + } + drop(active); + let bot = self.clone(); + tokio::spawn(async move { + if let Err(e) = bot.play_game(&game_id).await { + log::error!("game {game_id}: {e:#}"); + } + bot.active.lock().await.remove(&game_id); + log::info!("game {game_id} finished"); + }); + } + _ => {} + } + } + + /// None = accept; Some(reason) = decline reason for the API. + async fn challenge_verdict(&self, c: &Value) -> Option<&'static str> { + if s(c, &["variant", "key"]) != "standard" { + return Some("variant"); + } + if !self.args.speeds.iter().any(|sp| sp == s(c, &["speed"])) { + return Some("timeControl"); + } + if c["rated"].as_bool().unwrap_or(false) && !self.args.allow_rated { + return Some("casual"); + } + if self.active.lock().await.len() >= self.args.max_games { + return Some("later"); + } + None + } + + async fn play_game(&self, game_id: &str) -> Result<()> { + let eval = OnnxEvaluator::new( + &self.args.model.model, + self.args.model.threads, + self.args.model.device == "cuda", + )?; + let params = SearchParams { + sim_batch: self.args.sim_batch, + move_temp: self.args.move_temp, + move_temp_plies: self.args.move_temp_plies, + syzygy: self.syzygy.clone(), + ..SearchParams::default() + }; + let mut search = Some(Search::new(eval, params)); + let mut tm = TimeManager::new(self.args.initial_sims_per_sec); + + let mut start = Chess::default(); + let mut our_color = Color::White; + // Cumulative `moves` makes mid-game stream reconnects stateless. + let mut attempts = 0u32; + loop { + let mut stream = match self + .client + .stream(&format!("/api/bot/game/stream/{game_id}")) + .await + { + Ok(s) => s, + Err(e) => { + attempts += 1; + anyhow::ensure!(attempts < 5, "game stream connect failed repeatedly: {e:#}"); + tokio::time::sleep(Duration::from_secs(2)).await; + continue; + } + }; + + while let Some(msg) = stream.next().await? { + let state = match s(&msg, &["type"]) { + "gameFull" => { + // challenge_verdict declines non-standard challenges, but + // games that start without the accept flow (e.g. an AI + // challenge) can still be a variant we can't play. Resign + // cleanly instead of erroring out / hanging on the clock. + let variant = s(&msg, &["variant", "key"]); + if !variant.is_empty() && variant != "standard" { + log::warn!("game {game_id}: unsupported variant '{variant}'; resigning"); + let _ = self + .client + .post(&format!("/api/bot/game/{game_id}/resign"), &[]) + .await; + return Ok(()); + } + our_color = if s(&msg, &["white", "id"]) == self.our_id { + Color::White + } else { + Color::Black + }; + let initial = s(&msg, &["initialFen"]); + start = if initial.is_empty() || initial == "startpos" { + Chess::default() + } else { + initial + .parse::()? + .into_position(CastlingMode::Standard)? + }; + log::info!("game {game_id}: playing {our_color:?}"); + msg["state"].clone() + } + "gameState" => msg.clone(), + "opponentGone" => { + if msg["claimWinInSeconds"].as_u64() == Some(0) { + let _ = self + .client + .post(&format!("/api/bot/game/{game_id}/claim-victory"), &[]) + .await; + } + continue; + } + _ => continue, // chatLine etc. + }; + + let status = s(&state, &["status"]); + if status != "started" && !status.is_empty() { + log::info!("game {game_id}: over ({status})"); + return Ok(()); + } + + let moves = parse_moves(&start, s(&state, &["moves"]))?; + let pos_after = { + let mut p = start.clone(); + for m in &moves { + p.play_unchecked(m); + } + p + }; + if pos_after.turn() != our_color || pos_after.is_game_over() { + continue; + } + + let (our_ms, our_inc) = if our_color == Color::White { + (state["wtime"].as_u64(), state["winc"].as_u64()) + } else { + (state["btime"].as_u64(), state["binc"].as_u64()) + }; + let (sims, deadline) = tm.plan( + Duration::from_millis(our_ms.unwrap_or(60_000)), + Duration::from_millis(our_inc.unwrap_or(0)), + ); + + // Search on a blocking thread; Search moves in and out. + let mut sr = search.take().expect("search in use"); + let start_clone = start.clone(); + let (sr, result) = tokio::task::spawn_blocking(move || { + sr.set_position(start_clone, &moves); + let r = sr.go(sims, Some(deadline), &AtomicBool::new(false)); + (sr, r) + }) + .await?; + search = Some(sr); + let result = result?; + tm.update(result.sims, result.elapsed); + + let uci = result.best.to_uci(CastlingMode::Standard).to_string(); + log::info!( + "game {game_id}: {uci} value={:+.3} sims={} ({} nn evals, {} tb hits, {:.2}s, ~{:.0} sims/s)", + result.value, + result.sims, + result.nn_evals, + result.tb_hits, + result.elapsed.as_secs_f64(), + tm.sims_per_sec(), + ); + let path = format!("/api/bot/game/{game_id}/move/{uci}"); + if let Err(e) = self.client.post(&path, &[]).await { + log::warn!("game {game_id}: move post failed ({e:#}); retrying once"); + tokio::time::sleep(Duration::from_millis(500)).await; + if let Err(e) = self.client.post(&path, &[]).await { + // Typically the game ended (resign/abort) under us. + log::warn!("game {game_id}: move post failed again: {e:#}"); + } + } + } + + attempts += 1; + anyhow::ensure!(attempts < 20, "game stream kept dropping"); + log::info!("game {game_id}: stream dropped; reconnecting"); + tokio::time::sleep(Duration::from_secs(2)).await; + } + } +} + +fn parse_moves(start: &Chess, moves_str: &str) -> Result> { + let mut pos = start.clone(); + let mut moves = Vec::new(); + for t in moves_str.split_whitespace() { + let m = UciMove::from_ascii(t.as_bytes())?.to_move(&pos)?; + pos.play_unchecked(&m); + moves.push(m); + } + Ok(moves) +} diff --git a/rust/ct-bot/src/main.rs b/rust/ct-bot/src/main.rs new file mode 100644 index 0000000000000000000000000000000000000000..86268398bceddbe4d15f01fbc9c9450baae48d8e --- /dev/null +++ b/rust/ct-bot/src/main.rs @@ -0,0 +1,313 @@ +//! ct-bot: standalone Rust bot for the ChessTransformer Pos2MoveV2 model. +//! +//! Subcommands: `uci` (engine for gauntlets/cutechess), `lichess` (Bot API +//! client), `bench` (NN + search throughput), `eval` (single-position parity +//! probe used by scripts/check_onnx_parity.py). + +mod bench; +mod lichess; +mod nn; +mod search; +mod serve; +mod timeman; +mod uci; + +use std::path::PathBuf; +use std::sync::Arc; + +use anyhow::{Context, Result}; +use clap::{Args, Parser, Subcommand}; +use shakmaty::Chess; +use shakmaty_syzygy::Tablebase; + +const DEFAULT_MODEL: &str = "data/models/pos2move_v2.1/model.int8.onnx"; + +#[derive(Parser)] +#[command(name = "ct-bot", about = "ChessTransformer Rust bot")] +struct Cli { + #[command(subcommand)] + cmd: Cmd, +} + +#[derive(Args, Clone)] +struct ModelArgs { + /// Path to the ONNX model + #[arg(long, default_value = DEFAULT_MODEL)] + model: PathBuf, + /// Intra-op threads for ONNX Runtime (0 = auto) + #[arg(long, default_value_t = 0)] + threads: usize, + /// Inference device + #[arg(long, default_value = "cpu", value_parser = ["cpu", "cuda"])] + device: String, +} + +impl ModelArgs { + fn evaluator(&self) -> Result { + nn::OnnxEvaluator::new(&self.model, self.threads, self.device == "cuda") + } +} + +/// Load Syzygy tables from a ':'-separated list of directories (the UCI +/// `SyzygyPath` convention). Empty means none. +pub fn load_syzygy(paths: &str) -> Result>>> { + let dirs: Vec<&str> = paths.split(':').filter(|d| !d.trim().is_empty()).collect(); + if dirs.is_empty() { + return Ok(None); + } + let mut tb = Tablebase::new(); + let mut n = 0; + for dir in &dirs { + n += tb.add_directory(dir).with_context(|| format!("syzygy path {dir}"))?; + } + log::info!("syzygy: {n} table files from {paths} (up to {} pieces)", tb.max_pieces()); + Ok(Some(Arc::new(tb))) +} + +#[derive(Subcommand)] +enum Cmd { + /// UCI engine mode + Uci(UciArgs), + /// Lichess bot client + Lichess(LichessArgs), + /// NN + search throughput benchmark + Bench(BenchArgs), + /// HTTP backend for the web frontend (replaces backend/api.py) + Serve(ServeArgs), + /// Evaluate one FEN; print value + per-move priors as JSON (parity probe) + #[command(hide = true)] + Eval(EvalArgs), + /// Search one FEN from scratch at several budgets; print the top root + /// moves (visits, Q, prior) per budget (search-behavior probe) + #[command(hide = true)] + Probe(ProbeArgs), +} + +#[derive(Args)] +struct UciArgs { + #[command(flatten)] + model: ModelArgs, + /// Default simulations per move (when `go` has no nodes/time limits) + #[arg(long, default_value_t = 800)] + sims: u32, + /// Leaves per NN wave + #[arg(long, default_value_t = 16)] + sim_batch: usize, + #[arg(long, default_value_t = 1.0)] + c_puct: f64, + #[arg(long, default_value_t = 0.2)] + fpu: f64, + #[arg(long, default_value_t = 1.0)] + prior_temp: f32, + /// Seed for the clock-mode sims/sec estimate (refined after every move) + #[arg(long, default_value_t = 400.0)] + initial_sims_per_sec: f64, + /// Syzygy tablebase directories, ':'-separated (UCI option SyzygyPath) + #[arg(long, default_value = "")] + syzygy_path: String, +} + +#[derive(Args, Clone)] +struct LichessArgs { + #[command(flatten)] + model: ModelArgs, + /// API token of the BOT account (falls back to $LICHESS_BOT_TOKEN) + #[arg(long, env = "LICHESS_BOT_TOKEN", hide_env_values = true)] + token: String, + /// Accept rated challenges (casual is always accepted) + #[arg(long)] + allow_rated: bool, + /// Accepted challenge speeds + #[arg(long, value_delimiter = ',', default_values_t = + ["bullet".to_string(), "blitz".to_string(), "rapid".to_string(), "classical".to_string()])] + speeds: Vec, + /// Maximum concurrent games + #[arg(long, default_value_t = 1)] + max_games: usize, + /// Leaves per NN wave + #[arg(long, default_value_t = 16)] + sim_batch: usize, + /// Opening variety: sample moves ∝ visits^(1/temp) for the first + /// `--move-temp-plies` half-moves (0.0 = deterministic argmax) + #[arg(long, default_value_t = 0.0)] + move_temp: f64, + #[arg(long, default_value_t = 16)] + move_temp_plies: u32, + /// Seed for the sims/sec estimate (refined after every move) + #[arg(long, default_value_t = 400.0)] + initial_sims_per_sec: f64, + /// Lichess server (override for testing) + #[arg(long, default_value = "https://lichess.org")] + base_url: String, + /// Syzygy tablebase directories, ':'-separated + #[arg(long, default_value = "")] + syzygy_path: String, +} + +#[derive(Args)] +struct BenchArgs { + #[command(flatten)] + model: ModelArgs, + /// Simulation budgets for the search benchmark + #[arg(long, num_args = 1.., default_values_t = [800u32, 3200, 12800])] + sims: Vec, + /// Leaves per NN wave + #[arg(long, default_value_t = 16)] + sim_batch: usize, +} + +#[derive(Args, Clone)] +struct ServeArgs { + #[command(flatten)] + model: ModelArgs, + #[arg(long, default_value_t = 5001, env = "PORT")] + port: u16, + /// MCTS simulations per /api/move request + #[arg(long, default_value_t = 800, env = "MCTS_SIMS")] + sims: u32, + /// Leaves per NN wave + #[arg(long, default_value_t = 16)] + sim_batch: usize, + /// Reported in /api/health for the frontend display + #[arg(long, default_value_t = 2100)] + approx_elo: u32, + /// Syzygy tablebase directories, ':'-separated + #[arg(long, default_value = "", env = "SYZYGY_PATH")] + syzygy_path: String, + /// Also serve the web frontend's static build (Next.js `out/`) from this + /// directory, so one process hosts the whole demo (Hugging Face Space). + #[arg(long, env = "STATIC_DIR")] + static_dir: Option, +} + +#[derive(Args)] +struct EvalArgs { + #[command(flatten)] + model: ModelArgs, + #[arg(long)] + fen: String, +} + +#[derive(Args)] +struct ProbeArgs { + #[command(flatten)] + model: ModelArgs, + #[arg(long, default_value = "rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1")] + fen: String, + #[arg(long, num_args = 1.., default_values_t = [800u32, 3200, 12800])] + sims: Vec, + #[arg(long, default_value_t = 16)] + sim_batch: usize, + #[arg(long, default_value_t = 1.0)] + c_puct: f64, + #[arg(long, default_value_t = 0.2)] + fpu: f64, + #[arg(long, default_value_t = 1.0)] + prior_temp: f32, + /// Root moves to print per budget + #[arg(long, default_value_t = 6)] + top: usize, + /// Syzygy tablebase directories, ':'-separated + #[arg(long, default_value = "")] + syzygy_path: String, +} + +fn cmd_probe(args: &ProbeArgs) -> Result<()> { + use shakmaty::{fen::Fen, CastlingMode, Chess}; + use std::sync::atomic::AtomicBool; + + let fen: Fen = args.fen.parse()?; + let pos: Chess = fen.into_position(CastlingMode::Standard)?; + let params = search::SearchParams { + c_puct: args.c_puct, + fpu: args.fpu, + prior_temp: args.prior_temp, + sim_batch: args.sim_batch, + syzygy: load_syzygy(&args.syzygy_path)?, + ..search::SearchParams::default() + }; + let mut s = search::Search::new(args.model.evaluator()?, params); + for &sims in &args.sims { + s.new_game(); + s.set_position(pos.clone(), &[]); + let r = s.go(sims, None, &AtomicBool::new(false))?; + println!( + "sims {:>6} best {} value {:+.3} tb hits {} ({:.1}s)", + r.sims, + r.best.to_uci(CastlingMode::Standard), + r.value, + r.tb_hits, + r.elapsed.as_secs_f64() + ); + let pv: Vec = s + .pv(16) + .iter() + .map(|(m, n, q)| format!("{}({n},{q:+.2})", m.to_uci(CastlingMode::Standard))) + .collect(); + println!(" pv {}", pv.join(" ")); + for (m, n, q, p) in s.root_stats().into_iter().take(args.top) { + println!( + " {:<6} n {:>6} q {:+.3} prior {:.3}", + m.to_uci(CastlingMode::Standard).to_string(), + n, + q, + p + ); + } + } + Ok(()) +} + +fn cmd_eval(args: &EvalArgs) -> Result<()> { + use chess_core::encoding::{action_plane, encode_position, move_coords, NUM_PLANES}; + use nn::Evaluator; + use shakmaty::{fen::Fen, CastlingMode, Chess, Position}; + + let fen: Fen = args.fen.parse()?; + let pos: Chess = fen.into_position(CastlingMode::Standard)?; + let (tokens, player, castling, ep) = encode_position(&pos); + + let mut eval = args.model.evaluator()?; + let out = eval + .eval_batch(&[nn::EvalRequest { tokens, player, castling, ep, legal: Vec::new() }])? + .remove(0); + + let moves = pos.legal_moves(); + let mut scores: Vec = moves + .iter() + .map(|m| { + let (f, t, p) = move_coords(m); + out.logits[f * NUM_PLANES + action_plane(f, t, p)] + }) + .collect(); + chess_core::tree::softmax_priors(&mut scores, 1.0); + + let moves_json: Vec = moves + .iter() + .zip(scores.iter()) + .map(|(m, p)| { + serde_json::json!({ + "uci": m.to_uci(CastlingMode::Standard).to_string(), + "prior": p, + }) + }) + .collect(); + println!( + "{}", + serde_json::json!({ "value": out.value, "moves": moves_json }) + ); + Ok(()) +} + +fn main() -> Result<()> { + env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("warn")).init(); + let cli = Cli::parse(); + match &cli.cmd { + Cmd::Eval(args) => cmd_eval(args), + Cmd::Probe(args) => cmd_probe(args), + Cmd::Bench(args) => bench::run(args), + Cmd::Uci(args) => uci::run(args), + Cmd::Lichess(args) => lichess::run(args), + Cmd::Serve(args) => serve::run(args), + } +} diff --git a/rust/ct-bot/src/nn.rs b/rust/ct-bot/src/nn.rs new file mode 100644 index 0000000000000000000000000000000000000000..57ee3629543f008346e90c880bbedb52efb65d8b --- /dev/null +++ b/rust/ct-bot/src/nn.rs @@ -0,0 +1,107 @@ +//! ONNX Runtime evaluator for the Pos2MoveV2 model. +//! +//! Inputs (all i64): board_tokens [n,64], player_token [n], castling_token [n], +//! en_passant_token [n]. Outputs: move_logits [n,64,73] f32, value [n,1] f32. +//! Parity with python-onnxruntime is guarded by scripts/check_onnx_parity.py +//! --rust-bin. + +use std::path::Path; + +use anyhow::{Context, Result}; +use ndarray::{Array1, Array2, Array3}; +use ort::session::{builder::GraphOptimizationLevel, Session}; + +// The interface the search is written against lives in chess-core with it. +pub use chess_core::eval::{EvalOutput, EvalRequest, Evaluator}; + +pub struct OnnxEvaluator { + session: Session, +} + +/// ort builder errors carry a non-Send recovery payload; strip it for anyhow. +fn ort_ok(r: std::result::Result>) -> Result { + r.map_err(|e| anyhow::anyhow!("ort: {e}")) +} + +impl OnnxEvaluator { + pub fn new(model: &Path, intra_threads: usize, use_cuda: bool) -> Result { + let threads = if intra_threads == 0 { + (std::thread::available_parallelism().map_or(4, |n| n.get()) / 2).clamp(1, 8) + } else { + intra_threads + }; + #[allow(unused_mut)] + let mut builder = ort_ok( + ort_ok(ort_ok(Session::builder())?.with_optimization_level(GraphOptimizationLevel::Level3))? + .with_intra_threads(threads), + )?; + if use_cuda { + #[cfg(feature = "cuda")] + { + use ort::ep::CUDA; + builder = ort_ok(builder.with_execution_providers([CUDA::default().build()]))?; + log::info!("CUDA execution provider requested (falls back to CPU if unavailable)"); + } + #[cfg(not(feature = "cuda"))] + { + anyhow::bail!("--device cuda requires building with --features cuda"); + } + } + let session = ort_ok(builder.commit_from_file(model)) + .with_context(|| format!("loading ONNX model {}", model.display()))?; + log::info!("ONNX model loaded: {} ({} intra threads)", model.display(), threads); + Ok(Self { session }) + } + + fn eval_batch_impl(&mut self, batch: &[EvalRequest]) -> Result> { + let n = batch.len(); + if n == 0 { + return Ok(Vec::new()); + } + let mut boards = Array2::::zeros((n, 64)); + let mut player = Array1::::zeros(n); + let mut castling = Array1::::zeros(n); + let mut ep = Array1::::zeros(n); + for (i, r) in batch.iter().enumerate() { + for (j, &t) in r.tokens.iter().enumerate() { + boards[[i, j]] = t as i64; + } + player[i] = r.player as i64; + castling[i] = r.castling as i64; + ep[i] = r.ep as i64; + } + + let outputs = self.session.run(ort::inputs![ + "board_tokens" => ort::value::Tensor::from_array(boards)?, + "player_token" => ort::value::Tensor::from_array(player)?, + "castling_token" => ort::value::Tensor::from_array(castling)?, + "en_passant_token" => ort::value::Tensor::from_array(ep)?, + ])?; + + let logits: Array3 = outputs["move_logits"] + .try_extract_array::()? + .into_dimensionality()? + .to_owned(); + let value: Array2 = outputs["value"] + .try_extract_array::()? + .into_dimensionality()? + .to_owned(); + + Ok((0..n) + .map(|i| EvalOutput { + logits: logits + .index_axis(ndarray::Axis(0), i) + .iter() + .copied() + .collect(), + value: value[[i, 0]], + }) + .collect()) + } +} + +impl Evaluator for OnnxEvaluator { + fn eval_batch(&mut self, batch: &[EvalRequest]) -> Result> { + self.eval_batch_impl(batch) + } +} diff --git a/rust/ct-bot/src/search.rs b/rust/ct-bot/src/search.rs new file mode 100644 index 0000000000000000000000000000000000000000..3a484278b838524b5ee53bdbe09f26cc85668031 --- /dev/null +++ b/rust/ct-bot/src/search.rs @@ -0,0 +1,3 @@ +//! The bot's MCTS lives in `chess_core::search`, shared with selfplay-core's +//! batched match runner so that gates play exactly the search deployed here. +pub use chess_core::search::*; diff --git a/rust/ct-bot/src/serve.rs b/rust/ct-bot/src/serve.rs new file mode 100644 index 0000000000000000000000000000000000000000..c04b8b1d9d1d2c957847b893b0c5d0b8a781c220 --- /dev/null +++ b/rust/ct-bot/src/serve.rs @@ -0,0 +1,277 @@ +//! HTTP backend for the web frontend — a drop-in replacement for the FastAPI +//! server in backend/api.py (same routes, same JSON shapes), serving moves +//! from the Rust MCTS instead of the Python bot. +//! +//! Like the Python version, one session board is retained so the search keeps +//! its move history (threefold awareness) and tree reuse across requests; a +//! FEN that doesn't extend the session simply starts a fresh history. + +use std::sync::Arc; + +use anyhow::Result; +use axum::extract::State; +use axum::http::StatusCode; +use axum::routing::{get, post}; +use axum::Json; +use serde::Deserialize; +use serde_json::{json, Value}; +use shakmaty::{fen::Fen, CastlingMode, Chess, Color, EnPassantMode, Move, Position}; +use tokio::sync::Mutex; + +use crate::nn::OnnxEvaluator; +use crate::search::{Search, SearchParams, TreeSummary}; +use crate::ServeArgs; + +struct Session { + search: Search, + start: Chess, + moves: Vec, + pos: Chess, // start with moves applied +} + +struct App { + session: Mutex, + sims: u32, + model_name: String, + approx_elo: u32, +} + +fn fen_of(pos: &Chess) -> String { + Fen::from_position(pos.clone(), EnPassantMode::Legal).to_string() +} + +fn game_over(pos: &Chess) -> bool { + pos.is_game_over() || pos.halfmoves() >= 150 +} + +fn result_str(pos: &Chess) -> Option { + if !game_over(pos) { + return None; + } + Some(match pos.outcome() { + Some(shakmaty::Outcome::Decisive { winner: Color::White }) => "1-0".into(), + Some(shakmaty::Outcome::Decisive { winner: Color::Black }) => "0-1".into(), + _ => "1/2-1/2".into(), + }) +} + +/// Branching kept per depth when reporting the search to the frontend: the +/// root's top candidates, a couple of replies each, then the main line. +const TREE_WIDTHS: [usize; 8] = [5, 3, 2, 2, 1, 1, 1, 1]; + +fn tree_json(nodes: &[TreeSummary]) -> Value { + nodes + .iter() + .map(|t| { + json!({ + "move": t.mv.to_uci(CastlingMode::Standard).to_string(), + "visits": t.visits, + "prior": t.prior, + "q": t.q, + "children": tree_json(&t.children), + }) + }) + .collect() +} + +fn parse_fen(fen: &str) -> Result { + fen.parse::() + .map_err(|e| (StatusCode::BAD_REQUEST, format!("Invalid FEN string: {e}")))? + .into_position(CastlingMode::Standard) + .map_err(|e| (StatusCode::BAD_REQUEST, format!("Invalid FEN string: {e}"))) +} + +impl Session { + /// Mirror of api.py `_resolve_board`: keep the session history when the + /// requested FEN equals the session position or extends it by one legal + /// move (the human's reply); otherwise restart history from the FEN. + fn resolve(&mut self, req: &Chess) { + use chess_core::encoding::zobrist; + let want = zobrist(req); + if zobrist(&self.pos) == want { + return; + } + for m in self.pos.legal_moves() { + let mut next = self.pos.clone(); + next.play_unchecked(&m); + if zobrist(&next) == want { + self.moves.push(m); + self.pos = next; + return; + } + } + self.start = req.clone(); + self.moves.clear(); + self.pos = req.clone(); + } + + fn push(&mut self, m: Move) { + self.pos.play_unchecked(&m); + self.moves.push(m); + } +} + +#[derive(Deserialize)] +struct FenReq { + fen: String, +} + +#[derive(Deserialize)] +struct ValidateReq { + fen: String, + #[serde(rename = "move")] + mv: String, +} + +type Resp = Result, (StatusCode, String)>; + +async fn health(State(app): State>) -> Json { + Json(json!({ + "status": "ok", + "bot_type": "CtBot (Rust MCTS)", + "engine": "mcts", + "model": app.model_name, + "sims": app.sims, + "approx_elo": app.approx_elo, + })) +} + +async fn bot_move(State(app): State>, Json(req): Json) -> Resp { + let req_pos = parse_fen(&req.fen)?; + if game_over(&req_pos) { + return Err((StatusCode::BAD_REQUEST, "Game is already over".into())); + } + let sims = app.sims; + let result = tokio::task::spawn_blocking(move || { + let app = app; + let mut session = app.session.blocking_lock(); + session.resolve(&req_pos); + let (start, moves) = (session.start.clone(), session.moves.clone()); + session.search.set_position(start, &moves); + let r = session + .search + .go(sims, None, &std::sync::atomic::AtomicBool::new(false)) + .map_err(|e| e.to_string())?; + let root_visits = session.search.root_visits(); + let tree = session.search.summarize_tree(&TREE_WIDTHS, (root_visits / 100).max(2)); + let depth = session.search.depth_stats(); + session.push(r.best.clone()); + let pos = session.pos.clone(); + Ok::<_, String>(json!({ + "move": r.best.to_uci(CastlingMode::Standard).to_string(), + "probability": r.value, + "fen": fen_of(&pos), + "game_over": game_over(&pos), + "result": result_str(&pos), + "value": r.value, + "search": { + "sims": r.sims, + "visits": root_visits, + "nn_evals": r.nn_evals, + "elapsed_ms": r.elapsed.as_millis() as u64, + "depth": { "mean": depth.mean, "max": depth.max, "main_line": depth.main_line }, + "tree": tree_json(&tree), + }, + })) + }) + .await + .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))? + .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?; + Ok(Json(result)) +} + +async fn new_game(State(app): State>) -> Json { + let mut session = app.session.lock().await; + session.search.new_game(); + session.start = Chess::default(); + session.moves.clear(); + session.pos = Chess::default(); + Json(json!({ "fen": fen_of(&session.pos), "game_over": false })) +} + +async fn validate_move(Json(req): Json) -> Resp { + let pos = parse_fen(&req.fen)?; + let Ok(uci) = shakmaty::uci::UciMove::from_ascii(req.mv.as_bytes()) else { + return Ok(Json(json!({ "valid": false, "error": "Invalid move format" }))); + }; + match uci.to_move(&pos) { + Ok(m) => { + let mut next = pos.clone(); + next.play_unchecked(&m); + Ok(Json(json!({ + "valid": true, + "fen": fen_of(&next), + "game_over": game_over(&next), + "result": result_str(&next), + }))) + } + Err(_) => Ok(Json(json!({ "valid": false, "error": "Illegal move" }))), + } +} + +async fn evaluate(State(app): State>, Json(req): Json) -> Resp { + let pos = parse_fen(&req.fen)?; + let value = tokio::task::spawn_blocking(move || { + let app = app; + let mut session = app.session.blocking_lock(); + session.search.raw_value(&pos).map_err(|e| e.to_string()) + }) + .await + .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e.to_string()))? + .map_err(|e| (StatusCode::INTERNAL_SERVER_ERROR, e))?; + Ok(Json(json!({ "value": value }))) +} + +pub fn run(args: &ServeArgs) -> Result<()> { + let eval = OnnxEvaluator::new( + &args.model.model, + args.model.threads, + args.model.device == "cuda", + )?; + let search = Search::new( + eval, + SearchParams { + sim_batch: args.sim_batch, + syzygy: crate::load_syzygy(&args.syzygy_path)?, + ..SearchParams::default() + }, + ); + let app = Arc::new(App { + session: Mutex::new(Session { + search, + start: Chess::default(), + moves: Vec::new(), + pos: Chess::default(), + }), + sims: args.sims, + model_name: args + .model + .model + .file_stem() + .map(|s| s.to_string_lossy().into_owned()) + .unwrap_or_else(|| "model".into()), + approx_elo: args.approx_elo, + }); + + let mut router = axum::Router::new() + .route("/api/health", get(health)) + .route("/api/move", post(bot_move)) + .route("/api/new-game", post(new_game)) + .route("/api/validate-move", post(validate_move)) + .route("/api/evaluate", post(evaluate)); + if let Some(dir) = &args.static_dir { + router = router.fallback_service(tower_http::services::ServeDir::new(dir)); + } + let router = router + .layer(tower_http::cors::CorsLayer::permissive()) + .with_state(app); + + let rt = tokio::runtime::Runtime::new()?; + rt.block_on(async { + let addr = format!("0.0.0.0:{}", args.port); + let listener = tokio::net::TcpListener::bind(&addr).await?; + log::info!("serving on http://{addr} (sims={})", args.sims); + axum::serve(listener, router).await?; + Ok(()) + }) +} diff --git a/rust/ct-bot/src/timeman.rs b/rust/ct-bot/src/timeman.rs new file mode 100644 index 0000000000000000000000000000000000000000..beb936e3d84df408650ac4c4842784f6d8e56517 --- /dev/null +++ b/rust/ct-bot/src/timeman.rs @@ -0,0 +1,69 @@ +//! Clock → search budget mapping, shared by UCI clock mode and the lichess +//! client. Sims/sec is tracked as an EWMA over completed searches so the +//! budget adapts to the position mix and the hardware. + +use std::time::{Duration, Instant}; + +/// Upper bound on per-move simulations. Past a model-dependent point the search +/// starts exploiting value-head artifacts (over-rated quiet flank moves like +/// 1.h4) and converges onto junk — a model limitation, not a search bug. The +/// EMA net degrades by ~2000 sims; the base net stays sound to ~5000 (gauntlet: +/// both ~2108 Elo @ 800). The deployed bot uses the base int8 model, so cap at +/// 4000 — uses much more of the clock while keeping margin below the ~5k edge. +const MAX_SIMS: u32 = 4000; + +pub struct TimeManager { + ewma_sims_per_sec: f64, +} + +impl TimeManager { + /// `initial_sims_per_sec`: a rough seed until real measurements arrive + /// (updated after every search). + pub fn new(initial_sims_per_sec: f64) -> Self { + TimeManager { ewma_sims_per_sec: initial_sims_per_sec } + } + + pub fn update(&mut self, sims: u32, elapsed: Duration) { + let secs = elapsed.as_secs_f64(); + if secs > 1e-3 && sims > 0 { + let rate = sims as f64 / secs; + self.ewma_sims_per_sec = 0.7 * self.ewma_sims_per_sec + 0.3 * rate; + } + } + + pub fn sims_per_sec(&self) -> f64 { + self.ewma_sims_per_sec + } + + /// Plan a move budget from the remaining clock and increment: + /// (sim budget, hard deadline). The deadline overshoots the soft + /// allocation by 1.5x but never eats more than a third of the clock; the + /// per-wave deadline check in the search bounds overshoot to ~one wave. + pub fn plan(&self, remaining: Duration, inc: Duration) -> (u32, Instant) { + let reserve = Duration::from_millis(150); // network / posting latency + let min_alloc = Duration::from_millis(50); + let usable = remaining.saturating_sub(reserve); + let alloc = (usable / 30 + inc.mul_f64(0.7)).clamp(min_alloc, (usable / 4).max(min_alloc)); + let sims = (alloc.as_secs_f64() * self.ewma_sims_per_sec).round() as u32; + let sims = sims.clamp(64, MAX_SIMS); + let hard = alloc.mul_f64(1.5).min((usable / 3).max(min_alloc)); + (sims, Instant::now() + hard) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn plan_is_sane_across_clocks() { + let tm = TimeManager::new(500.0); + // 3+2 blitz with a full clock: a few seconds of search. + let (sims, _) = tm.plan(Duration::from_secs(180), Duration::from_secs(2)); + assert!((1000..=5000).contains(&sims), "blitz sims: {sims}"); + // Nearly flagged: still spends >= the minimum budget. + let (sims, deadline) = tm.plan(Duration::from_millis(400), Duration::ZERO); + assert_eq!(sims, 64); + assert!(deadline <= Instant::now() + Duration::from_millis(200)); + } +} diff --git a/rust/ct-bot/src/uci.rs b/rust/ct-bot/src/uci.rs new file mode 100644 index 0000000000000000000000000000000000000000..c3388c056516a960788ebb1e874e03d1f92e0a2c --- /dev/null +++ b/rust/ct-bot/src/uci.rs @@ -0,0 +1,353 @@ +//! Minimal-but-correct UCI engine front-end: enough for python-chess +//! `SimpleEngine` (the Stockfish gauntlet / sims-scaling driver) and +//! cutechess-cli. `position` carries the cumulative move list, so the search's +//! threefold history and tree reuse work exactly as in the Python bot. + +use std::io::BufRead; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc; +use std::sync::Arc; +use std::time::{Duration, Instant}; + +use anyhow::Result; +use shakmaty::fen::Fen; +use shakmaty::uci::UciMove; +use shakmaty::{CastlingMode, Chess, Color, Move, Position}; + +use crate::nn::OnnxEvaluator; +use crate::search::{Search, SearchParams}; +use crate::timeman::TimeManager; +use crate::UciArgs; + +fn value_to_cp(v: f32) -> i32 { + (v.clamp(-0.999, 0.999).atanh() * 290.0) as i32 +} + +struct Options { + model: std::path::PathBuf, + syzygy_path: String, + threads: usize, + device_cuda: bool, + sims: u32, + params: SearchParams, +} + +struct Uci { + opts: Options, + search: Option>, + start: Chess, + moves: Vec, + tm: TimeManager, + stop: Arc, +} + +impl Uci { + fn ensure_search(&mut self) -> Result<&mut Search> { + if self.search.is_none() { + let eval = OnnxEvaluator::new(&self.opts.model, self.opts.threads, self.opts.device_cuda)?; + let params = SearchParams { + c_puct: self.opts.params.c_puct, + fpu: self.opts.params.fpu, + prior_temp: self.opts.params.prior_temp, + sim_batch: self.opts.params.sim_batch, + syzygy: self.opts.params.syzygy.clone(), + ..SearchParams::default() + }; + let mut search = Search::new(eval, params); + search.set_position(self.start.clone(), &self.moves); + self.search = Some(search); + } + Ok(self.search.as_mut().unwrap()) + } + + fn cmd_uci(&self) { + println!("id name ChessTransformer-MCTS"); + println!("id author tchauffi"); + println!( + "option name Model type string default {}", + self.opts.model.display() + ); + println!("option name Sims type spin default {} min 1 max 10000000", self.opts.sims); + println!( + "option name SimBatch type spin default {} min 1 max 256", + self.opts.params.sim_batch + ); + println!("option name Threads type spin default {} min 0 max 64", self.opts.threads); + println!("option name CPuct type string default {}", self.opts.params.c_puct); + println!("option name FPU type string default {}", self.opts.params.fpu); + println!("option name PriorTemp type string default {}", self.opts.params.prior_temp); + println!("option name SyzygyPath type string default {}", self.opts.syzygy_path); + println!("uciok"); + } + + fn cmd_setoption(&mut self, line: &str) { + // "setoption name [value ]" + let rest = line.trim_start_matches("setoption").trim(); + let rest = rest.strip_prefix("name").map(str::trim).unwrap_or(rest); + let (name, value) = match rest.split_once(" value ") { + Some((n, v)) => (n.trim(), v.trim()), + None => (rest, ""), + }; + match name.to_ascii_lowercase().as_str() { + "model" => { + self.opts.model = value.into(); + self.search = None; // rebuilt on next isready/go + } + "threads" => { + if let Ok(v) = value.parse() { + self.opts.threads = v; + self.search = None; + } + } + "sims" => { + if let Ok(v) = value.parse() { + self.opts.sims = v; + } + } + "simbatch" => { + if let Ok(v) = value.parse() { + self.opts.params.sim_batch = v; + if let Some(s) = &mut self.search { + s.params.sim_batch = v; + } + } + } + "cpuct" => { + if let Ok(v) = value.parse() { + self.opts.params.c_puct = v; + if let Some(s) = &mut self.search { + s.params.c_puct = v; + } + } + } + "fpu" => { + if let Ok(v) = value.parse() { + self.opts.params.fpu = v; + if let Some(s) = &mut self.search { + s.params.fpu = v; + } + } + } + "priortemp" => { + if let Ok(v) = value.parse() { + self.opts.params.prior_temp = v; + if let Some(s) = &mut self.search { + s.params.prior_temp = v; + } + } + } + "syzygypath" => match crate::load_syzygy(value) { + Ok(tb) => { + self.opts.syzygy_path = value.to_string(); + self.opts.params.syzygy = tb.clone(); + if let Some(s) = &mut self.search { + s.params.syzygy = tb; + } + } + Err(e) => println!("info string SyzygyPath: {e:#}"), + }, + _ => log::warn!("unknown option: {name}"), + } + } + + fn cmd_position(&mut self, line: &str) -> Result<()> { + let mut tokens = line.split_whitespace().skip(1).peekable(); // skip "position" + let start: Chess = match tokens.next() { + Some("startpos") => Chess::default(), + Some("fen") => { + let mut fen_parts = Vec::new(); + while let Some(&t) = tokens.peek() { + if t == "moves" { + break; + } + fen_parts.push(tokens.next().unwrap()); + } + let fen: Fen = fen_parts.join(" ").parse()?; + fen.into_position(CastlingMode::Standard)? + } + other => anyhow::bail!("bad position command: {other:?}"), + }; + let mut moves = Vec::new(); + if tokens.peek() == Some(&"moves") { + tokens.next(); + let mut pos = start.clone(); + for t in tokens { + let m = UciMove::from_ascii(t.as_bytes())?.to_move(&pos)?; + pos.play_unchecked(&m); + moves.push(m); + } + } + self.start = start.clone(); + self.moves = moves; + if self.search.is_some() { + let mvs = self.moves.clone(); + self.ensure_search()?.set_position(start, &mvs); + } + Ok(()) + } + + fn cmd_go(&mut self, line: &str) -> Result<()> { + let mut nodes: Option = None; + let mut movetime: Option = None; + let mut wtime: Option = None; + let mut btime: Option = None; + let mut winc: u64 = 0; + let mut binc: u64 = 0; + let mut infinite = false; + let mut tokens = line.split_whitespace().skip(1); + while let Some(t) = tokens.next() { + let mut next_u64 = || tokens.next().and_then(|v| v.parse::().ok()); + match t { + "nodes" => nodes = next_u64().map(|v| v as u32), + "movetime" => movetime = next_u64(), + "wtime" => wtime = next_u64(), + "btime" => btime = next_u64(), + "winc" => winc = next_u64().unwrap_or(0), + "binc" => binc = next_u64().unwrap_or(0), + "infinite" => infinite = true, + _ => {} + } + } + + let default_sims = self.opts.sims; + let turn = { + let search = self.ensure_search()?; + if search.position().legal_moves().is_empty() { + println!("bestmove 0000"); + return Ok(()); + } + search.position().turn() + }; + let (sims, deadline) = if let Some(n) = nodes { + (n, None) + } else if let Some(ms) = movetime { + let margin = Duration::from_millis(30.min(ms / 10)); + (u32::MAX, Some(Instant::now() + Duration::from_millis(ms) - margin)) + } else if wtime.is_some() || btime.is_some() { + let (our_time, our_inc) = if turn == Color::White { + (wtime.unwrap_or(0), winc) + } else { + (btime.unwrap_or(0), binc) + }; + let (sims, deadline) = self + .tm + .plan(Duration::from_millis(our_time), Duration::from_millis(our_inc)); + (sims, Some(deadline)) + } else if infinite { + (u32::MAX, None) + } else { + (default_sims, None) + }; + + self.stop.store(false, Ordering::Relaxed); + let stop = self.stop.clone(); + let result = self.ensure_search()?.go(sims, deadline, &stop)?; + self.tm.update(result.sims, result.elapsed); + + let ms = result.elapsed.as_millis().max(1); + if result.tb_hits > 0 { + println!("info string tbhits {}", result.tb_hits); + } + println!( + "info depth 1 nodes {} nps {} time {} score cp {} pv {}", + result.sims, + (result.sims as u128 * 1000) / ms, + ms, + value_to_cp(result.value), + result.best.to_uci(CastlingMode::Standard) + ); + println!("bestmove {}", result.best.to_uci(CastlingMode::Standard)); + Ok(()) + } +} + +pub fn run(args: &UciArgs) -> Result<()> { + let stop = Arc::new(AtomicBool::new(false)); + let (tx, rx) = mpsc::channel::(); + + // Reader thread: `stop`/`quit` abort an in-flight search immediately (the + // flag is checked between waves); all lines but `stop` queue in order for + // the main loop, which exits when it reaches `quit`. + { + let stop = stop.clone(); + std::thread::spawn(move || { + let stdin = std::io::stdin(); + for line in stdin.lock().lines() { + let Ok(line) = line else { break }; + let cmd = line.trim(); + if cmd == "stop" || cmd == "quit" { + stop.store(true, Ordering::Relaxed); + if cmd == "stop" { + continue; + } + } + if tx.send(line).is_err() { + break; + } + } + // EOF: behave like quit so the engine exits cleanly. + stop.store(true, Ordering::Relaxed); + let _ = tx.send("quit".to_string()); + }); + } + + let mut uci = Uci { + opts: Options { + model: args.model.model.clone(), + syzygy_path: args.syzygy_path.clone(), + threads: args.model.threads, + device_cuda: args.model.device == "cuda", + sims: args.sims, + params: SearchParams { + sim_batch: args.sim_batch, + c_puct: args.c_puct, + fpu: args.fpu, + prior_temp: args.prior_temp, + syzygy: crate::load_syzygy(&args.syzygy_path)?, + ..SearchParams::default() + }, + }, + search: None, + start: Chess::default(), + moves: Vec::new(), + tm: TimeManager::new(args.initial_sims_per_sec), + stop: stop.clone(), + }; + + for line in rx { + let cmd = line.trim(); + let head = cmd.split_whitespace().next().unwrap_or(""); + let outcome = match head { + "uci" => { + uci.cmd_uci(); + Ok(()) + } + "setoption" => { + uci.cmd_setoption(cmd); + Ok(()) + } + "isready" => uci.ensure_search().map(|_| println!("readyok")), + "ucinewgame" => { + if let Some(s) = &mut uci.search { + s.new_game(); + } + uci.start = Chess::default(); + uci.moves.clear(); + Ok(()) + } + "position" => uci.cmd_position(cmd), + "go" => uci.cmd_go(cmd), + "quit" => break, + "" | "stop" => Ok(()), + _ => { + log::warn!("unknown command: {cmd}"); + Ok(()) + } + }; + if let Err(e) = outcome { + log::error!("{head}: {e:#}"); + println!("info string error: {e}"); + } + } + Ok(()) +} diff --git a/rust/selfplay-core/.gitignore b/rust/selfplay-core/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..2f7896d1d1365eafb0da03d9fe456fac81408487 --- /dev/null +++ b/rust/selfplay-core/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/rust/selfplay-core/Cargo.lock b/rust/selfplay-core/Cargo.lock new file mode 100644 index 0000000000000000000000000000000000000000..638dea9858c10bc0c9c8003298c39ec0112b0670 --- /dev/null +++ b/rust/selfplay-core/Cargo.lock @@ -0,0 +1,450 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "arrayvec" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "bitflags" +version = "2.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8" + +[[package]] +name = "btoi" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9dd6407f73a9b8b6162d8a2ef999fe6afd7cc15902ebf42c5cd296addf17e0ad" +dependencies = [ + "num-traits", +] + +[[package]] +name = "cfg-if" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "libc", + "wasi", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "indoc" +version = "2.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79cf5c93f93228cf8efb3ba362535fb11199ac548a09ce117c9b1adc3030d706" +dependencies = [ + "rustversion", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "libc" +version = "0.2.186" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66" + +[[package]] +name = "matrixmultiply" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a06de3016e9fae57a36fd14dba131fccf49f74b40b7fbdb472f96e361ec71a08" +dependencies = [ + "autocfg", + "rawpointer", +] + +[[package]] +name = "memchr" +version = "2.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b947ae49db0d222b1dbc6b113ce7248a3fc3a6ca21b696717bfc000ba4484d8" + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "ndarray" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "882ed72dce9365842bf196bdeedf5055305f11fc8c03dee7bb0194a6cad34841" +dependencies = [ + "matrixmultiply", + "num-complex", + "num-integer", + "num-traits", + "portable-atomic", + "portable-atomic-util", + "rawpointer", +] + +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "numpy" +version = "0.23.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b94caae805f998a07d33af06e6a3891e38556051b8045c615470a71590e13e78" +dependencies = [ + "libc", + "ndarray", + "num-complex", + "num-integer", + "num-traits", + "pyo3", + "rustc-hash", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "portable-atomic" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c33a9471896f1c69cecef8d20cbe2f7accd12527ce60845ff44c153bb2a21b49" + +[[package]] +name = "portable-atomic-util" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a106d1259c23fac8e543272398ae0e3c0b8d33c88ed73d0cc71b0f1d902618" +dependencies = [ + "portable-atomic", +] + +[[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.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "pyo3" +version = "0.23.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7778bffd85cf38175ac1f545509665d0b9b92a198ca7941f131f85f7a4f9a872" +dependencies = [ + "cfg-if", + "indoc", + "libc", + "memoffset", + "once_cell", + "portable-atomic", + "pyo3-build-config", + "pyo3-ffi", + "pyo3-macros", + "unindent", +] + +[[package]] +name = "pyo3-build-config" +version = "0.23.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94f6cbe86ef3bf18998d9df6e0f3fc1050a8c5efa409bf712e661a4366e010fb" +dependencies = [ + "once_cell", + "target-lexicon", +] + +[[package]] +name = "pyo3-ffi" +version = "0.23.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9f1b4c431c0bb1c8fb0a338709859eed0d030ff6daa34368d3b152a63dfdd8d" +dependencies = [ + "libc", + "pyo3-build-config", +] + +[[package]] +name = "pyo3-macros" +version = "0.23.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbc2201328f63c4710f68abdf653c89d8dbc2858b88c5d88b0ff38a75288a9da" +dependencies = [ + "proc-macro2", + "pyo3-macros-backend", + "quote", + "syn", +] + +[[package]] +name = "pyo3-macros-backend" +version = "0.23.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fca6726ad0f3da9c9de093d6f116a93c1a38e417ed73bf138472cf4064f72028" +dependencies = [ + "heck", + "proc-macro2", + "pyo3-build-config", + "quote", + "syn", +] + +[[package]] +name = "quote" +version = "1.0.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand" +version = "0.8.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" +dependencies = [ + "libc", + "rand_chacha", + "rand_core", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom", +] + +[[package]] +name = "rawpointer" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60a357793950651c4ed0f3f52338f53b2f809f32d83a07f72909fa13e4c6c1e3" + +[[package]] +name = "rustc-hash" +version = "2.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe" + +[[package]] +name = "rustversion" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" + +[[package]] +name = "selfplay-core" +version = "0.1.0" +dependencies = [ + "numpy", + "pyo3", + "rand", + "serde", + "serde_json", + "shakmaty", +] + +[[package]] +name = "serde" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.228" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.150" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "shakmaty" +version = "0.27.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f414cadc4e727893d1a3b0dca62aaef4c1c821dcbd969f0b10a92e12d684d53a" +dependencies = [ + "arrayvec", + "bitflags", + "btoi", + "nohash-hasher", + "serde", +] + +[[package]] +name = "syn" +version = "2.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "target-lexicon" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" + +[[package]] +name = "unicode-ident" +version = "1.0.24" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" + +[[package]] +name = "unindent" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7264e107f553ccae879d21fbea1d6724ac785e8c3bfc762137959b5802826ef3" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "zerocopy" +version = "0.8.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.52" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "zmij" +version = "1.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" diff --git a/rust/selfplay-core/Cargo.toml b/rust/selfplay-core/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..e5f5f35a62aea4618c858378dfe070c5ce959d57 --- /dev/null +++ b/rust/selfplay-core/Cargo.toml @@ -0,0 +1,17 @@ +[package] +name = "selfplay-core" +version = "0.1.0" +edition = "2021" + +[lib] +name = "selfplay_core" +crate-type = ["cdylib"] + +[dependencies] +chess-core = { path = "../chess-core" } +pyo3 = { version = "0.23", features = ["extension-module"] } +numpy = "0.23" +shakmaty = { workspace = true } +rand = { workspace = true } +serde = { workspace = true } +serde_json = { workspace = true } diff --git a/rust/selfplay-core/pyproject.toml b/rust/selfplay-core/pyproject.toml new file mode 100644 index 0000000000000000000000000000000000000000..d7b80e767c4864e937292df986f06e536a8c0847 --- /dev/null +++ b/rust/selfplay-core/pyproject.toml @@ -0,0 +1,11 @@ +# Pins the wheel name: without this, maturin walks up past the cargo workspace +# and adopts the repo-root pyproject.toml (name "chesstransformer"), producing +# a wheel that would shadow the real Python package. +[build-system] +requires = ["maturin>=1.4,<2"] +build-backend = "maturin" + +[project] +name = "selfplay_core" +version = "0.1.0" +requires-python = ">=3.9" diff --git a/rust/selfplay-core/src/lib.rs b/rust/selfplay-core/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..b2f22a5ef18ce6026822f1c37ac3155cc6573c52 --- /dev/null +++ b/rust/selfplay-core/src/lib.rs @@ -0,0 +1,717 @@ +//! Self-play generation core: cross-game batched MCTS over shakmaty boards. +//! +//! Python keeps only the batched NN forward; this crate owns boards, search +//! trees and game lifecycle for many concurrent games. Protocol per round: +//! +//! boards, player, castling, ep = engine.collect() # deduped NN-pending positions +//! logits, values = nn_forward(...) # (n, 64, 73) f32, (n,) f32 +//! engine.apply(logits, values) # expand/backup, play ready moves +//! for game in engine.drain_finished(): ... # completed game records +//! +//! Search semantics mirror `Pos2MoveV2MctsBot` (PUCT + FPU, virtual loss, +//! negamax backup, terminal rules incl. in-search threefold repetition). +//! Encodings and tree primitives live in the shared `chess-core` crate — +//! see the parity test. +//! +//! Two expert-iteration options, both off by default (parity holds): +//! +//! * Playout cap randomization (KataGo): with `fast_sims > 0`, each move is a +//! full search (`num_sims`) with probability `full_frac`, else a fast one +//! (`fast_sims`). Every position is recorded with a `full` flag; only full +//! searches are strong enough to be policy targets, while all of them carry +//! the game outcome. Fast moves buy more games -- more independent value +//! labels -- per GPU hour. +//! * Root Dirichlet noise (AlphaZero): on full searches the root priors are +//! mixed `(1 - eps) * p + eps * Dir(alpha)`. Without it a move under ~0.5 % +//! prior is never visited, so the visit target can only re-confirm the prior. +//! +//! `SelfPlayEngine` (selfplay_engine.rs) runs self-play on the deployed bot's +//! own search instead, and `MatchEngine` (matches.rs) plays matches with it; +//! this engine's search is the older one, kept for comparison. + +use std::collections::HashMap; + +use chess_core::encoding::{ + action_plane, encode_position, halfmove, move_coords, terminal_value, zobrist, NUM_PLANES, +}; +use chess_core::search::sample_gamma; +use chess_core::tree::{backup_vl, puct_select, softmax_priors, Node}; +use numpy::{IntoPyArray, PyArray1, PyArray2, PyArrayMethods, PyReadonlyArray1, PyReadonlyArray3}; +use pyo3::prelude::*; +use pyo3::types::PyDict; +use rand::prelude::*; +use rand::rngs::StdRng; +use serde::Deserialize; +use shakmaty::fen::Fen; +use shakmaty::{CastlingMode, Chess, Color, Move, Position}; + +mod matches; +mod selfplay_engine; + +// ── per-game state ─────────────────────────────────────────────────────── + +struct Rec { + tokens: [u8; 64], + player: u8, + castling: u8, + ep: u8, + halfmove: u16, + root_v: f32, + full: u8, + visit_idx: Vec, // from_sq * 73 + plane + visit_cnt: Vec, +} + +struct Game { + id: usize, + start_fen: String, + pos: Chess, + history: Vec, // zobrist of every position incl. start + tree: Vec, + sims_done: u32, + inflight: u32, + move_sims: u32, // search budget of the current move + full: bool, // current move is a full search (policy target) + noise_applied: bool, // root noise already mixed into this move's root + records: Vec, + moves_uci: Vec, + resign_allowed: bool, + resign_streak: u32, + resign_sign: i32, + plies: u32, + active: bool, +} + +struct Finished { + records: Vec, + moves_uci: Vec, + start_fen: String, + z_white: f32, + end: &'static str, + resign_allowed: bool, + id: usize, +} + +struct NnItem { + key: u64, + tokens: [u8; 64], + player: u8, + castling: u8, + ep: u8, + move_fp: Vec<(usize, usize)>, // (from_sq, plane) per legal move, in move-list order +} + +struct PendingLeaf { + game: usize, + node: usize, + path: Vec<(usize, usize)>, // (node_idx, child_idx) + key: u64, + moves: Vec, +} + +#[derive(Deserialize)] +struct Config { + num_sims: u32, + #[serde(default = "d_games")] num_parallel_games: usize, + #[serde(default = "d_leaves")] leaves_per_wave: u32, + #[serde(default = "d_cpuct")] c_puct: f64, + #[serde(default = "d_fpu")] fpu: f64, + #[serde(default = "d_one")] prior_temp: f32, + #[serde(default = "d_one_f64")] move_temp: f64, + #[serde(default = "d_temp_plies")] temp_plies: u32, + #[serde(default = "d_resign")] resign_threshold: f32, + #[serde(default = "d_resign_plies")] resign_plies: u32, + #[serde(default = "d_noresign")] no_resign_frac: f64, + #[serde(default = "d_max_plies")] max_plies: u32, + #[serde(default = "d_tt_cap")] tt_cap: usize, + #[serde(default)] fast_sims: u32, + #[serde(default = "d_one_f64")] full_frac: f64, + #[serde(default)] dirichlet_alpha: f64, + #[serde(default = "d_dir_eps")] dirichlet_eps: f64, +} +fn d_dir_eps() -> f64 { 0.25 } +fn d_games() -> usize { 64 } +fn d_leaves() -> u32 { 4 } +fn d_cpuct() -> f64 { 1.0 } +fn d_fpu() -> f64 { 0.2 } +fn d_one() -> f32 { 1.0 } +fn d_one_f64() -> f64 { 1.0 } +fn d_temp_plies() -> u32 { 30 } +fn d_resign() -> f32 { 0.93 } +fn d_resign_plies() -> u32 { 6 } +fn d_noresign() -> f64 { 0.1 } +fn d_max_plies() -> u32 { 300 } +fn d_tt_cap() -> usize { 2_000_000 } + +// move_temp is deserialized as f64 for sampling math convenience. + +#[pyclass] +struct Engine { + cfg: Config, + openings: Vec, + opening_fens: Vec, + games: Vec, + pending: Vec, + nn_items: Vec, + nn_index: HashMap, + tt: HashMap, f32)>, // priors (legal-move order) + stm value + // The previous TT generation. A full TT is rotated here instead of cleared, so the + // subtrees of the searches in progress stay cached across the rotation. + tt_old: HashMap, f32)>, + finished: Vec, + rng: StdRng, + started: usize, + completed: usize, + target: usize, + positions_recorded: usize, +} + +impl Engine { + fn fresh_tree() -> Vec { + vec![Node::default()] + } + + /// TT lookup across both generations; an old-generation hit is promoted. + fn tt_get(&mut self, key: u64) -> Option<(Vec, f32)> { + if let Some(e) = self.tt.get(&key) { + return Some(e.clone()); + } + let e = self.tt_old.get(&key)?.clone(); + self.tt.insert(key, e.clone()); + Some(e) + } + + /// (search budget, is_full) for the next move. + fn draw_budget(&mut self) -> (u32, bool) { + if self.cfg.fast_sims == 0 || self.rng.gen::() < self.cfg.full_frac { + (self.cfg.num_sims, true) + } else { + (self.cfg.fast_sims, false) + } + } + + /// Mix Dirichlet noise into the root priors, once per full search, as soon as + /// the root is expanded. Never touches the TT, which keeps the clean priors. + fn maybe_noise_root(&mut self, gi: usize) { + let alpha = self.cfg.dirichlet_alpha; + let g = &self.games[gi]; + if alpha <= 0.0 || !g.full || g.noise_applied || !g.tree[0].expanded { + return; + } + let k = g.tree[0].priors.len(); + let noise: Vec = (0..k).map(|_| sample_gamma(&mut self.rng, alpha)).collect(); + let total: f64 = noise.iter().sum(); + let eps = self.cfg.dirichlet_eps; + let g = &mut self.games[gi]; + if total > 0.0 { + for (p, n) in g.tree[0].priors.iter_mut().zip(&noise) { + *p = ((1.0 - eps) * (*p as f64) + eps * n / total) as f32; + } + } + g.noise_applied = true; + } + + fn new_game(&mut self) -> Game { + let oi = self.rng.gen_range(0..self.openings.len()); + let pos = self.openings[oi].clone(); + let id = self.started; + self.started += 1; + let (move_sims, full) = self.draw_budget(); + Game { + id, + start_fen: self.opening_fens[oi].clone(), + history: vec![zobrist(&pos)], + pos, + tree: Self::fresh_tree(), + sims_done: 0, + inflight: 0, + move_sims, + full, + noise_applied: false, + records: Vec::new(), + moves_uci: Vec::new(), + resign_allowed: self.rng.gen::() >= self.cfg.no_resign_frac, + resign_streak: 0, + resign_sign: 0, + plies: 0, + active: true, + } + } + + /// Descend with virtual loss to an unexpanded node. Returns the leaf node + /// index, the path, the leaf position and the zobrist keys pushed en route. + fn descend(&mut self, gi: usize) -> (usize, Vec<(usize, usize)>, Chess, Vec) { + let mut node_idx = 0usize; + let mut pos = self.games[gi].pos.clone(); + let mut path = Vec::new(); + let mut keys = Vec::new(); + loop { + if !self.games[gi].tree[node_idx].expanded { + return (node_idx, path, pos, keys); + } + let idx = puct_select(&self.games[gi].tree[node_idx], self.cfg.c_puct, self.cfg.fpu); + { + let node = &mut self.games[gi].tree[node_idx]; + node.n[idx] += 1; // virtual loss + node.w[idx] += 1.0; + } + path.push((node_idx, idx)); + let mv = self.games[gi].tree[node_idx].moves[idx].clone(); + pos.play_unchecked(&mv); + keys.push(zobrist(&pos)); + let child = self.games[gi].tree[node_idx].children[idx]; + node_idx = if child >= 0 { + child as usize + } else { + self.games[gi].tree.push(Node::default()); + let new_idx = self.games[gi].tree.len() - 1; + self.games[gi].tree[node_idx].children[idx] = new_idx as i32; + new_idx + }; + } + } + + fn resolve_leaf(game: &mut Game, node_idx: usize, moves: Vec, priors: &[f32], + value: f32, path: &[(usize, usize)]) { + if !game.tree[node_idx].expanded { + game.tree[node_idx].expand(moves, priors.to_vec()); + } + backup_vl(&mut game.tree, path, value); + game.sims_done += 1; + } + + /// Search budget reached: record the position, play the move, handle game + /// end / next-move reset. + fn finish_move(&mut self, gi: usize) { + let cfg_move_temp = self.cfg.move_temp; + let cfg_temp_plies = self.cfg.temp_plies; + + let (tokens, player, castling, ep) = encode_position(&self.games[gi].pos); + let halfmove = halfmove(&self.games[gi].pos); + + // Visit distribution + move selection from the root. + let (best_idx, root_v, visit_idx, visit_cnt) = { + let root = &self.games[gi].tree[0]; + let mut visit_idx = Vec::new(); + let mut visit_cnt = Vec::new(); + for i in 0..root.moves.len() { + if root.n[i] > 0 { + let (f, t, p) = move_coords(&root.moves[i]); + visit_idx.push((f * NUM_PLANES + action_plane(f, t, p)) as u16); + visit_cnt.push(root.n[i].min(u16::MAX as u32) as u16); + } + } + let best = if cfg_move_temp > 0.0 && halfmove < cfg_temp_plies { + let weights: Vec = root + .n + .iter() + .map(|&n| (n as f64).powf(1.0 / cfg_move_temp)) + .collect(); + let total: f64 = weights.iter().sum(); + if total > 0.0 { + let mut r = self.rng.gen::() * total; + let mut pick = root.n.len() - 1; + for (i, w) in weights.iter().enumerate() { + if r < *w { + pick = i; + break; + } + r -= w; + } + pick + } else { + 0 + } + } else { + (0..root.n.len()).max_by_key(|&i| root.n[i]).unwrap_or(0) + }; + let rv = if root.n[best] > 0 { + (-root.w[best] / root.n[best] as f64) as f32 + } else { + 0.0 + }; + (best, rv, visit_idx, visit_cnt) + }; + + let full = self.games[gi].full as u8; + self.games[gi].records.push(Rec { + tokens, player, castling, ep, + halfmove: halfmove.min(u16::MAX as u32) as u16, + root_v, + full, + visit_idx, visit_cnt, + }); + self.positions_recorded += 1; + + let mv = self.games[gi].tree[0].moves[best_idx].clone(); + let uci = mv.to_uci(CastlingMode::Standard).to_string(); + let game = &mut self.games[gi]; + game.moves_uci.push(uci); + game.pos.play_unchecked(&mv); + game.history.push(zobrist(&game.pos)); + game.plies += 1; + + // Resign bookkeeping (white-POV root value). + let v_white = if player == 1 { root_v } else { -root_v }; + if v_white.abs() >= self.cfg.resign_threshold { + let sign = if v_white > 0.0 { 1 } else { -1 }; + game.resign_streak = if sign == game.resign_sign { + game.resign_streak + 1 + } else { + 1 + }; + game.resign_sign = sign; + } else { + game.resign_streak = 0; + } + + // Game over? + let cur_key = *game.history.last().unwrap(); + let term = terminal_value(&game.pos, &game.history, cur_key); + let outcome: Option<(f32, &'static str)> = if let Some(t) = term { + let z = if t < 0.0 { + // side to move is mated; the side that just moved wins + if game.pos.turn() == Color::Black { 1.0 } else { -1.0 } + } else { + 0.0 + }; + Some((z, "terminal")) + } else if game.resign_allowed && game.resign_streak >= self.cfg.resign_plies { + Some((game.resign_sign as f32, "resign")) + } else if game.plies >= self.cfg.max_plies { + Some((0.0, "max_plies")) + } else { + None + }; + + match outcome { + Some((z_white, end)) => { + let game = &mut self.games[gi]; + let fin = Finished { + records: std::mem::take(&mut game.records), + moves_uci: std::mem::take(&mut game.moves_uci), + start_fen: game.start_fen.clone(), + z_white, + end, + resign_allowed: game.resign_allowed, + id: game.id, + }; + self.finished.push(fin); + self.completed += 1; + if self.started < self.target { + self.games[gi] = self.new_game(); + } else { + self.games[gi].active = false; + } + } + None => { + let (move_sims, full) = self.draw_budget(); + let game = &mut self.games[gi]; + game.tree = Self::fresh_tree(); + game.sims_done = 0; + game.move_sims = move_sims; + game.full = full; + game.noise_applied = false; + } + } + } +} + +#[pymethods] +impl Engine { + #[new] + fn new(config_json: &str, openings: Vec, seed: u64, target: usize) -> PyResult { + let cfg: Config = serde_json::from_str(config_json) + .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("config: {e}")))?; + let mut parsed = Vec::new(); + for fen in &openings { + let f: Fen = fen + .parse() + .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("fen {fen}: {e}")))?; + let pos: Chess = f + .into_position(CastlingMode::Standard) + .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("fen {fen}: {e}")))?; + parsed.push(pos); + } + let n_games = cfg.num_parallel_games.min(target.max(1)); + let mut engine = Engine { + cfg, + openings: parsed, + opening_fens: openings, + games: Vec::new(), + pending: Vec::new(), + nn_items: Vec::new(), + nn_index: HashMap::new(), + tt: HashMap::new(), + tt_old: HashMap::new(), + finished: Vec::new(), + rng: StdRng::seed_from_u64(seed), + started: 0, + completed: 0, + target, + positions_recorded: 0, + }; + for _ in 0..n_games { + let g = engine.new_game(); + engine.games.push(g); + } + Ok(engine) + } + + /// Run descent waves over all active games; immediately resolve terminal + /// and TT-cached leaves. Returns encoded positions needing an NN forward + /// (deduped), as numpy arrays. + fn collect<'py>( + &mut self, + py: Python<'py>, + ) -> ( + Bound<'py, PyArray2>, + Bound<'py, PyArray1>, + Bound<'py, PyArray1>, + Bound<'py, PyArray1>, + ) { + for gi in 0..self.games.len() { + if !self.games[gi].active { + continue; + } + for _ in 0..self.cfg.leaves_per_wave { + let g = &self.games[gi]; + if g.sims_done + g.inflight >= g.move_sims { + break; + } + let root_unexpanded = !self.games[gi].tree[0].expanded; + if root_unexpanded && self.games[gi].inflight > 0 { + break; // root eval already queued + } + let (node_idx, path, pos, path_keys) = self.descend(gi); + let key = zobrist(&pos); + let mut all_keys = self.games[gi].history.clone(); + all_keys.extend_from_slice(&path_keys); + if let Some(t) = terminal_value(&pos, &all_keys, key) { + let game = &mut self.games[gi]; + backup_vl(&mut game.tree, &path, t); + game.sims_done += 1; + continue; + } + let moves: Vec = pos.legal_moves().to_vec(); + if let Some((priors, value)) = self.tt_get(key) { + let game = &mut self.games[gi]; + Self::resolve_leaf(game, node_idx, moves, &priors, value, &path); + if node_idx == 0 { + self.maybe_noise_root(gi); + } + continue; + } + self.nn_index.entry(key).or_insert_with(|| { + let (tokens, player, castling, ep) = encode_position(&pos); + let move_fp = moves + .iter() + .map(|m| { + let (f, t, p) = move_coords(m); + (f, action_plane(f, t, p)) + }) + .collect(); + self.nn_items.push(NnItem { key, tokens, player, castling, ep, move_fp }); + self.nn_items.len() - 1 + }); + self.pending.push(PendingLeaf { game: gi, node: node_idx, path, key, moves }); + self.games[gi].inflight += 1; + if root_unexpanded { + break; // nothing else to search until the root is expanded + } + } + } + + let n = self.nn_items.len(); + let mut boards = Vec::with_capacity(n * 64); + let mut player = Vec::with_capacity(n); + let mut castling = Vec::with_capacity(n); + let mut ep = Vec::with_capacity(n); + for item in &self.nn_items { + boards.extend_from_slice(&item.tokens); + player.push(item.player); + castling.push(item.castling); + ep.push(item.ep); + } + let boards = PyArray1::from_vec(py, boards) + .reshape([n, 64]) + .expect("reshape"); + ( + boards, + player.into_pyarray(py), + castling.into_pyarray(py), + ep.into_pyarray(py), + ) + } + + /// Consume NN results for the batch returned by the last collect(): + /// expand + back up all pending leaves, then play moves for games whose + /// search budget is complete (recording positions / finishing games). + fn apply( + &mut self, + logits: PyReadonlyArray3, + values: PyReadonlyArray1, + ) -> PyResult<()> { + let logits = logits.as_array(); + let values = values.as_slice()?; + if values.len() != self.nn_items.len() { + return Err(pyo3::exceptions::PyValueError::new_err(format!( + "apply: got {} values for {} pending NN items", + values.len(), + self.nn_items.len() + ))); + } + + if self.tt.len() + self.nn_items.len() > self.cfg.tt_cap { + self.tt_old = std::mem::take(&mut self.tt); + } + for (i, item) in self.nn_items.iter().enumerate() { + let mut scores: Vec = item + .move_fp + .iter() + .map(|&(f, p)| logits[[i, f, p]]) + .collect(); + softmax_priors(&mut scores, self.cfg.prior_temp); + self.tt.insert(item.key, (scores, values[i])); + } + + let pending = std::mem::take(&mut self.pending); + for leaf in pending { + let (priors, value) = self.tt.get(&leaf.key).cloned().expect("just inserted"); + let game = &mut self.games[leaf.game]; + Self::resolve_leaf(game, leaf.node, leaf.moves, &priors, value, &leaf.path); + game.inflight -= 1; + if leaf.node == 0 { + self.maybe_noise_root(leaf.game); + } + } + self.nn_items.clear(); + self.nn_index.clear(); + + for gi in 0..self.games.len() { + if self.games[gi].active + && self.games[gi].inflight == 0 + && self.games[gi].sims_done >= self.games[gi].move_sims + { + self.finish_move(gi); + } + } + Ok(()) + } + + /// Completed games since the last call, as dicts of numpy arrays. + fn drain_finished<'py>(&mut self, py: Python<'py>) -> PyResult>> { + let finished = std::mem::take(&mut self.finished); + let mut out = Vec::with_capacity(finished.len()); + for f in finished { + let p = f.records.len(); + let mut boards = Vec::with_capacity(p * 64); + let (mut player, mut castling, mut ep) = + (Vec::with_capacity(p), Vec::with_capacity(p), Vec::with_capacity(p)); + let mut halfmove = Vec::with_capacity(p); + let (mut root_v, mut z) = (Vec::with_capacity(p), Vec::with_capacity(p)); + let mut full = Vec::with_capacity(p); + let (mut visit_idx, mut visit_cnt) = (Vec::new(), Vec::new()); + let mut visit_ptr = Vec::with_capacity(p + 1); + visit_ptr.push(0i64); + for r in &f.records { + boards.extend_from_slice(&r.tokens); + player.push(r.player); + castling.push(r.castling); + ep.push(r.ep); + halfmove.push(r.halfmove); + root_v.push(r.root_v); + full.push(r.full); + z.push(if r.player == 1 { f.z_white } else { -f.z_white }); + visit_idx.extend_from_slice(&r.visit_idx); + visit_cnt.extend_from_slice(&r.visit_cnt); + visit_ptr.push(visit_idx.len() as i64); + } + let d = PyDict::new(py); + d.set_item("boards", PyArray1::from_vec(py, boards).reshape([p, 64]).expect("reshape"))?; + d.set_item("player", player.into_pyarray(py))?; + d.set_item("castling", castling.into_pyarray(py))?; + d.set_item("ep", ep.into_pyarray(py))?; + d.set_item("halfmove", halfmove.into_pyarray(py))?; + d.set_item("root_v", root_v.into_pyarray(py))?; + d.set_item("full", full.into_pyarray(py))?; + d.set_item("z", z.into_pyarray(py))?; + d.set_item("visit_idx", visit_idx.into_pyarray(py))?; + d.set_item("visit_cnt", visit_cnt.into_pyarray(py))?; + d.set_item("visit_ptr", visit_ptr.into_pyarray(py))?; + d.set_item("moves", f.moves_uci)?; + d.set_item("fen", f.start_fen)?; + d.set_item("z_white", f.z_white)?; + d.set_item("end", f.end)?; + d.set_item("resign_allowed", f.resign_allowed)?; + d.set_item("id", f.id)?; + out.push(d); + } + Ok(out) + } + + fn done(&self) -> bool { + self.completed >= self.target + } + + /// (games started, games completed, positions recorded, TT entries) + fn stats(&self) -> (usize, usize, usize, usize) { + (self.started, self.completed, self.positions_recorded, self.tt.len() + self.tt_old.len()) + } +} + +// ── debug helpers for the Python parity test ──────────────────────────── + +#[pyfunction] +fn debug_encode(fen: &str) -> PyResult<(Vec, u8, u8, u8)> { + let f: Fen = fen + .parse() + .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?; + let pos: Chess = f + .into_position(CastlingMode::Standard) + .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?; + let (tokens, player, castling, ep) = encode_position(&pos); + Ok((tokens.to_vec(), player, castling, ep)) +} + +#[pyfunction] +fn debug_move_planes(fen: &str) -> PyResult> { + let f: Fen = fen + .parse() + .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?; + let pos: Chess = f + .into_position(CastlingMode::Standard) + .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?; + let mut out = Vec::new(); + for m in pos.legal_moves() { + let (from, to, promo) = move_coords(&m); + out.push(( + m.to_uci(CastlingMode::Standard).to_string(), + from as u8, + action_plane(from, to, promo) as u8, + )); + } + Ok(out) +} + +#[pyfunction] +fn debug_zobrist(fen: &str) -> PyResult { + let f: Fen = fen + .parse() + .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?; + let pos: Chess = f + .into_position(CastlingMode::Standard) + .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("{e}")))?; + Ok(zobrist(&pos)) +} + +#[pymodule] +fn selfplay_core(m: &Bound<'_, PyModule>) -> PyResult<()> { + m.add_class::()?; + m.add_class::()?; + m.add_class::()?; + m.add_function(wrap_pyfunction!(debug_encode, m)?)?; + m.add_function(wrap_pyfunction!(debug_move_planes, m)?)?; + m.add_function(wrap_pyfunction!(debug_zobrist, m)?)?; + Ok(()) +} diff --git a/rust/selfplay-core/src/matches.rs b/rust/selfplay-core/src/matches.rs new file mode 100644 index 0000000000000000000000000000000000000000..5aaaddb19cc54ab32f16afcfe9d7c5681824977b --- /dev/null +++ b/rust/selfplay-core/src/matches.rs @@ -0,0 +1,344 @@ +//! Batched matches between two networks, played with the deployed bot's search +//! and move flow (`chess_core::matchplay`: tree reuse, the per-move budget +//! rules and pondering of ct-bot's lichess loop). Every side of every game is +//! a `chess_core::search::Search` driven one wave at a time; this wrapper runs +//! the games in parallel and hands their waves to Python, one forward per +//! network for all games, instead of ct-bot's 16 positions per call. +//! +//! Not modelled: the clock (moves play at the per-speed cap, as 81-100 % of +//! live moves do), the opening temperature (a book start is past ply 2), int8 +//! numerics (the forward runs in Python). + +use std::collections::HashMap; + +use chess_core::matchplay::{MatchGame, MatchRules, SideParams}; +use chess_core::search::EvalOutput; +use numpy::{IntoPyArray, PyArray1, PyArray2, PyArrayMethods, PyReadonlyArray1, PyReadonlyArray2, + PyReadonlyArray3}; +use pyo3::prelude::*; +use pyo3::types::PyDict; +use serde::Deserialize; +use shakmaty::fen::Fen; +use shakmaty::{CastlingMode, Chess}; + +const POLICY: usize = 64 * 73; + +/// Pad index of the legal-move array: one past the last logit, so a GPU gather +/// over logits with one appended column reads a dummy there. +const PAD: i16 = POLICY as i16; + +/// The legal-move index rows of a batch, padded to the longest: (flat, width, lengths). +fn legal_rows<'a>(reqs: impl Iterator) -> (Vec, usize, Vec) { + let reqs: Vec<_> = reqs.collect(); + let width = reqs.iter().map(|r| r.legal.len()).max().unwrap_or(0).max(1); + let mut flat = vec![PAD; reqs.len() * width]; + let mut lens = Vec::with_capacity(reqs.len()); + for (i, r) in reqs.iter().enumerate() { + for (j, &m) in r.legal.iter().enumerate() { + flat[i * width + j] = m as i16; + } + lens.push(r.legal.len() as u16); + } + (flat, width, lens) +} + +#[derive(Deserialize)] +struct MatchConfig { + /// Per-move fresh-sims cap (ct-bot `--max-sims`, 4000 for bullet/blitz). + #[serde(default = "d_sims")] + sims: u32, + /// Ponder budget (ct-bot `--ponder-max-sims`); 0 = no pondering. + #[serde(default = "d_ponder")] + ponder_sims: u32, + /// Total root visits allowed above `sims` (ct-bot PONDER_HEADROOM). + #[serde(default = "d_headroom")] + headroom: u32, + #[serde(default = "d_batch")] + sim_batch: usize, + #[serde(default = "d_cpuct")] + c_puct: f64, + #[serde(default = "d_fpu")] + fpu: f64, + #[serde(default = "d_one")] + prior_temp: f32, + /// TT entries per search. ct-bot's 2M would need tens of GB across hundreds + /// of searches; the TT only caches evaluations, so a smaller one changes the + /// GPU work, not the search. + #[serde(default = "d_tt")] + tt_cap: usize, + #[serde(default = "d_games")] + num_parallel_games: usize, + #[serde(default = "d_max_plies")] + max_plies: u32, + #[serde(default = "d_threads")] + threads: usize, +} +fn d_sims() -> u32 { 4000 } +fn d_ponder() -> u32 { 2000 } +fn d_headroom() -> u32 { chess_core::search::PONDER_HEADROOM } +fn d_batch() -> usize { 16 } +fn d_cpuct() -> f64 { 1.0 } +fn d_fpu() -> f64 { 0.2 } +fn d_one() -> f32 { 1.0 } +fn d_tt() -> usize { 150_000 } +fn d_games() -> usize { 128 } +fn d_max_plies() -> u32 { 200 } +fn d_threads() -> usize { 8 } + +#[pyclass] +pub struct MatchEngine { + cfg: MatchConfig, + rules: MatchRules, + params: SideParams, + fens: Vec, + starts: Vec, + a_white: Vec, + games: Vec, + started: usize, + completed: usize, + finished: Vec, + /// (game slot, side, positions) of the last collect, in batch order. + owners: Vec<(usize, usize, usize)>, + /// Legal-move count per position of the last collect, and the padded width. + legal_lens: Vec, + legal_width: usize, +} + +impl MatchEngine { + fn fill(&mut self) { + while self.games.len() < self.cfg.num_parallel_games && self.started < self.fens.len() { + let i = self.started; + self.started += 1; + self.games.push(MatchGame::new(i, self.starts[i].clone(), self.a_white[i], self.params)); + } + } + + /// Run `f` over the games in `threads` contiguous chunks. + fn par_games(&mut self, f: F) + where + F: Fn(usize, &mut MatchGame) + Sync, + { + let threads = self.cfg.threads.max(1); + let chunk = self.games.len().div_ceil(threads).max(1); + std::thread::scope(|scope| { + for (ci, games) in self.games.chunks_mut(chunk).enumerate() { + let f = &f; + scope.spawn(move || { + for (j, g) in games.iter_mut().enumerate() { + f(ci * chunk + j, g); + } + }); + } + }); + } +} + +#[pymethods] +impl MatchEngine { + /// Game i starts from `fens[i]` with network A white iff `a_white[i]`. + #[new] + fn new(config_json: &str, fens: Vec, a_white: Vec) -> PyResult { + let cfg: MatchConfig = serde_json::from_str(config_json) + .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("config: {e}")))?; + if fens.len() != a_white.len() || fens.is_empty() { + return Err(pyo3::exceptions::PyValueError::new_err( + "need one a_white flag per opening, and at least one game")); + } + let mut starts = Vec::with_capacity(fens.len()); + for fen in &fens { + let f: Fen = fen.parse() + .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("fen {fen}: {e}")))?; + let pos: Chess = f.into_position(CastlingMode::Standard) + .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("fen {fen}: {e}")))?; + starts.push(pos); + } + let rules = MatchRules { + sims: cfg.sims, + ponder_sims: cfg.ponder_sims, + total_cap: cfg.sims + cfg.headroom, + max_plies: cfg.max_plies, + }; + let params = SideParams { + c_puct: cfg.c_puct, + fpu: cfg.fpu, + prior_temp: cfg.prior_temp, + sim_batch: cfg.sim_batch, + tt_cap: cfg.tt_cap, + }; + let mut m = MatchEngine { + cfg, rules, params, fens, starts, a_white, games: Vec::new(), started: 0, + completed: 0, finished: Vec::new(), owners: Vec::new(), legal_lens: Vec::new(), + legal_width: 1, + }; + m.fill(); + Ok(m) + } + + /// Advance every search to its next NN wave; returns the batch (boards, + /// player, castling, ep, net, legal) with net 0 = A, 1 = B and `legal` the + /// legal moves' flat logit indices per position, padded with 4672. + #[allow(clippy::type_complexity)] + fn collect<'py>(&mut self, py: Python<'py>) -> PyResult<( + Bound<'py, PyArray2>, Bound<'py, PyArray1>, Bound<'py, PyArray1>, + Bound<'py, PyArray1>, Bound<'py, PyArray1>, Bound<'py, PyArray2>, + )> { + loop { + let rules = self.rules; + self.par_games(|_, g| g.advance(&rules)); + if let Some(g) = self.games.iter().find(|g| g.stalled()) { + return Err(pyo3::exceptions::PyRuntimeError::new_err(format!( + "match engine stalled in game {}", g.id))); + } + // Retire finished games and refill from the schedule; new games need + // advancing before the batch goes out. + let before = self.games.len(); + let mut i = 0; + while i < self.games.len() { + if self.games[i].end().is_some() { + self.finished.push(self.games.swap_remove(i)); + self.completed += 1; + } else { + i += 1; + } + } + let retired = before != self.games.len(); + self.fill(); + if !retired || self.games.is_empty() { + break; + } + } + + self.owners.clear(); + let (mut boards, mut player, mut castling, mut ep, mut net) = + (Vec::new(), Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for (gi, g) in self.games.iter().enumerate() { + for s in 0..2 { + if let Some(reqs) = g.pending(s) { + for r in reqs { + boards.extend_from_slice(&r.tokens); + player.push(r.player); + castling.push(r.castling); + ep.push(r.ep); + net.push(s as u8); + } + self.owners.push((gi, s, reqs.len())); + } + } + } + let n = player.len(); + let (legal, width, lens) = legal_rows( + self.owners.iter().flat_map(|&(gi, s, _)| self.games[gi].pending(s).unwrap().iter())); + self.legal_lens = lens; + self.legal_width = width; + Ok(( + PyArray1::from_vec(py, boards).reshape([n, 64]).expect("reshape"), + player.into_pyarray(py), + castling.into_pyarray(py), + ep.into_pyarray(py), + net.into_pyarray(py), + PyArray1::from_vec(py, legal).reshape([n, width]).expect("reshape"), + )) + } + + /// Like `apply`, with the legal moves' logits already gathered: row i holds + /// the logits at the indices of the last collect's `legal` row i. + fn apply_legal(&mut self, logits: PyReadonlyArray2, values: PyReadonlyArray1) -> PyResult<()> { + let logits = logits.as_array(); + let values = values.as_slice()?; + let total = self.legal_lens.len(); + let width = self.legal_width; + if values.len() != total || logits.shape() != [total, width] { + return Err(pyo3::exceptions::PyValueError::new_err(format!( + "apply_legal: got {} values / logits {:?} for {} pending positions of width {}", + values.len(), logits.shape(), total, width))); + } + let flat = logits.as_slice().ok_or_else(|| { + pyo3::exceptions::PyValueError::new_err("apply_legal: logits must be C-contiguous") + })?; + let lens = std::mem::take(&mut self.legal_lens); + let lens = &lens; + let mut offsets: HashMap<(usize, usize), (usize, usize)> = HashMap::new(); + let mut at = 0; + for &(gi, s, k) in &self.owners { + offsets.insert((gi, s), (at, k)); + at += k; + } + let offsets = &offsets; + self.par_games(|gi, g| { + for s in 0..2 { + let Some(&(at, k)) = offsets.get(&(gi, s)) else { continue }; + let outputs: Vec = (at..at + k) + .map(|i| EvalOutput { + logits: flat[i * width..i * width + lens[i] as usize].to_vec(), + value: values[i], + }) + .collect(); + g.resolve(s, outputs); + } + }); + self.owners.clear(); + Ok(()) + } + + /// Outputs for the batch of the last collect(), in its order. + fn apply(&mut self, logits: PyReadonlyArray3, values: PyReadonlyArray1) -> PyResult<()> { + let logits = logits.as_array(); + let values = values.as_slice()?; + let total: usize = self.owners.iter().map(|o| o.2).sum(); + if values.len() != total || logits.shape() != [total, 64, 73] { + return Err(pyo3::exceptions::PyValueError::new_err(format!( + "apply: got {} values / logits {:?} for {} pending positions", + values.len(), logits.shape(), total))); + } + let flat = logits.as_slice().ok_or_else(|| { + pyo3::exceptions::PyValueError::new_err("apply: logits must be C-contiguous") + })?; + let mut offsets: HashMap<(usize, usize), (usize, usize)> = HashMap::new(); + let mut at = 0; + for &(gi, s, k) in &self.owners { + offsets.insert((gi, s), (at, k)); + at += k; + } + let offsets = &offsets; + self.par_games(|gi, g| { + for s in 0..2 { + let Some(&(at, k)) = offsets.get(&(gi, s)) else { continue }; + let outputs: Vec = (at..at + k) + .map(|i| EvalOutput { + logits: flat[i * POLICY..(i + 1) * POLICY].to_vec(), + value: values[i], + }) + .collect(); + g.resolve(s, outputs); + } + }); + self.owners.clear(); + Ok(()) + } + + /// Completed games since the last call. + fn drain_finished<'py>(&mut self, py: Python<'py>) -> PyResult>> { + let mut out = Vec::new(); + for g in std::mem::take(&mut self.finished) { + let (z, end) = g.end().expect("finished game has a result"); + let d = PyDict::new(py); + d.set_item("id", g.id)?; + d.set_item("fen", &self.fens[g.id])?; + d.set_item("a_white", g.a_white)?; + d.set_item("moves", g.moves_uci().to_vec())?; + d.set_item("z_white", z)?; + d.set_item("end", end)?; + out.push(d); + } + Ok(out) + } + + fn done(&self) -> bool { + self.completed >= self.fens.len() + } + + /// (games started, games completed) + fn stats(&self) -> (usize, usize) { + (self.started, self.completed) + } +} diff --git a/rust/selfplay-core/src/selfplay_engine.rs b/rust/selfplay-core/src/selfplay_engine.rs new file mode 100644 index 0000000000000000000000000000000000000000..2f05e075ea8bae9f9dfe1939f06148b83e5afdc2 --- /dev/null +++ b/rust/selfplay-core/src/selfplay_engine.rs @@ -0,0 +1,379 @@ +//! Self-play on the deployed bot's search: many `chess_core::selfplay` games in +//! parallel threads, their waves handed to Python as one batch. Same protocol +//! and game records as `Engine`, which keeps its own older search. + +use chess_core::search::EvalOutput; +use chess_core::selfplay::{SelfPlayGame, SelfPlayRules}; +use numpy::{IntoPyArray, PyArray1, PyArray2, PyArrayMethods, PyReadonlyArray1, PyReadonlyArray2, + PyReadonlyArray3}; +use pyo3::prelude::*; +use pyo3::types::PyDict; +use rand::prelude::*; +use rand::rngs::StdRng; +use serde::Deserialize; +use shakmaty::fen::Fen; +use shakmaty::{CastlingMode, Chess}; + +const POLICY: usize = 64 * 73; + +/// Pad index of the legal-move array: one past the last logit, so a GPU gather +/// over logits with one appended column reads a dummy there. +const PAD: i16 = POLICY as i16; + +/// The legal-move index rows of a batch, padded to the longest: (flat, width, lengths). +fn legal_rows<'a>(reqs: impl Iterator) -> (Vec, usize, Vec) { + let reqs: Vec<_> = reqs.collect(); + let width = reqs.iter().map(|r| r.legal.len()).max().unwrap_or(0).max(1); + let mut flat = vec![PAD; reqs.len() * width]; + let mut lens = Vec::with_capacity(reqs.len()); + for (i, r) in reqs.iter().enumerate() { + for (j, &m) in r.legal.iter().enumerate() { + flat[i * width + j] = m as i16; + } + lens.push(r.legal.len() as u16); + } + (flat, width, lens) +} + +#[derive(Deserialize)] +struct Config { + num_sims: u32, + #[serde(default = "d_games")] + num_parallel_games: usize, + #[serde(default = "d_batch")] + sim_batch: usize, + #[serde(default = "d_cpuct")] + c_puct: f64, + #[serde(default = "d_fpu")] + fpu: f64, + #[serde(default = "d_one")] + prior_temp: f32, + #[serde(default = "d_one_f64")] + move_temp: f64, + #[serde(default = "d_temp_plies")] + temp_plies: u32, + #[serde(default = "d_resign")] + resign_threshold: f32, + #[serde(default = "d_resign_plies")] + resign_plies: u32, + #[serde(default = "d_noresign")] + no_resign_frac: f64, + #[serde(default = "d_max_plies")] + max_plies: u32, + /// TT entries per game (it only caches evaluations). + #[serde(default = "d_tt")] + tt_cap: usize, + #[serde(default)] + fast_sims: u32, + #[serde(default = "d_one_f64")] + full_frac: f64, + #[serde(default)] + dirichlet_alpha: f64, + #[serde(default = "d_dir_eps")] + dirichlet_eps: f64, + #[serde(default = "d_threads")] + threads: usize, + /// Count the reused tree's warm visits toward the full / fast budget. + #[serde(default)] + cap_total_full: bool, + #[serde(default)] + cap_total_fast: bool, +} +fn d_games() -> usize { 128 } +fn d_batch() -> usize { 16 } +fn d_cpuct() -> f64 { 1.0 } +fn d_fpu() -> f64 { 0.2 } +fn d_one() -> f32 { 1.0 } +fn d_one_f64() -> f64 { 1.0 } +fn d_temp_plies() -> u32 { 30 } +fn d_resign() -> f32 { 0.93 } +fn d_resign_plies() -> u32 { 6 } +fn d_noresign() -> f64 { 0.1 } +fn d_max_plies() -> u32 { 300 } +fn d_tt() -> usize { 100_000 } +fn d_dir_eps() -> f64 { 0.25 } +fn d_threads() -> usize { 6 } + +#[pyclass] +pub struct SelfPlayEngine { + rules: SelfPlayRules, + num_parallel_games: usize, + threads: usize, + openings: Vec, + opening_fens: Vec, + games: Vec, + finished: Vec, + rng: StdRng, + started: usize, + completed: usize, + target: usize, + positions_recorded: usize, + /// (game slot, positions) of the last collect, in batch order. + owners: Vec<(usize, usize)>, + /// Legal-move count per position of the last collect, and the padded width. + legal_lens: Vec, + legal_width: usize, +} + +impl SelfPlayEngine { + fn fill(&mut self) { + while self.games.len() < self.num_parallel_games && self.started < self.target { + let oi = self.rng.gen_range(0..self.openings.len()); + let seed = self.rng.gen(); + let g = SelfPlayGame::new(self.started, oi, self.openings[oi].clone(), &self.rules, seed); + self.started += 1; + self.games.push(g); + } + } + + fn par_games(&mut self, f: F) + where + F: Fn(usize, &mut SelfPlayGame) + Sync, + { + let chunk = self.games.len().div_ceil(self.threads.max(1)).max(1); + std::thread::scope(|scope| { + for (ci, games) in self.games.chunks_mut(chunk).enumerate() { + let f = &f; + scope.spawn(move || { + for (j, g) in games.iter_mut().enumerate() { + f(ci * chunk + j, g); + } + }); + } + }); + } +} + +#[pymethods] +impl SelfPlayEngine { + #[new] + fn new(config_json: &str, openings: Vec, seed: u64, target: usize) -> PyResult { + let c: Config = serde_json::from_str(config_json) + .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("config: {e}")))?; + let mut parsed = Vec::new(); + for fen in &openings { + let f: Fen = fen.parse() + .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("fen {fen}: {e}")))?; + let pos: Chess = f.into_position(CastlingMode::Standard) + .map_err(|e| pyo3::exceptions::PyValueError::new_err(format!("fen {fen}: {e}")))?; + parsed.push(pos); + } + let rules = SelfPlayRules { + num_sims: c.num_sims, fast_sims: c.fast_sims, full_frac: c.full_frac, + dirichlet_alpha: c.dirichlet_alpha, dirichlet_eps: c.dirichlet_eps, + move_temp: c.move_temp, temp_plies: c.temp_plies, + resign_threshold: c.resign_threshold, resign_plies: c.resign_plies, + no_resign_frac: c.no_resign_frac, max_plies: c.max_plies, sim_batch: c.sim_batch, + c_puct: c.c_puct, fpu: c.fpu, prior_temp: c.prior_temp, tt_cap: c.tt_cap, + cap_total_full: c.cap_total_full, cap_total_fast: c.cap_total_fast, + }; + let mut e = SelfPlayEngine { + rules, + num_parallel_games: c.num_parallel_games.min(target.max(1)), + threads: c.threads, + openings: parsed, + opening_fens: openings, + games: Vec::new(), + finished: Vec::new(), + rng: StdRng::seed_from_u64(seed), + started: 0, + completed: 0, + target, + positions_recorded: 0, + owners: Vec::new(), + legal_lens: Vec::new(), + legal_width: 1, + }; + e.fill(); + Ok(e) + } + + /// Advance every game to its next NN wave; returns (boards, player, + /// castling, ep, legal) of all pending positions, `legal` being the legal + /// moves' flat logit indices per position, padded with 4672. + #[allow(clippy::type_complexity)] + fn collect<'py>(&mut self, py: Python<'py>) -> PyResult<( + Bound<'py, PyArray2>, Bound<'py, PyArray1>, Bound<'py, PyArray1>, + Bound<'py, PyArray1>, Bound<'py, PyArray2>, + )> { + loop { + let rules = self.rules; + self.par_games(|_, g| g.advance(&rules)); + if let Some(g) = self.games.iter().find(|g| g.stalled()) { + return Err(pyo3::exceptions::PyRuntimeError::new_err(format!( + "self-play engine stalled in game {}", g.id))); + } + let before = self.games.len(); + let mut i = 0; + while i < self.games.len() { + if self.games[i].end().is_some() { + let g = self.games.swap_remove(i); + self.positions_recorded += g.records().len(); + self.completed += 1; + self.finished.push(g); + } else { + i += 1; + } + } + let retired = before != self.games.len(); + self.fill(); + if !retired || self.games.is_empty() { + break; + } + } + + self.owners.clear(); + let (mut boards, mut player, mut castling, mut ep) = + (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + for (gi, g) in self.games.iter().enumerate() { + if let Some(reqs) = g.pending() { + for r in reqs { + boards.extend_from_slice(&r.tokens); + player.push(r.player); + castling.push(r.castling); + ep.push(r.ep); + } + self.owners.push((gi, reqs.len())); + } + } + let n = player.len(); + let (legal, width, lens) = legal_rows( + self.owners.iter().flat_map(|&(gi, _)| self.games[gi].pending().unwrap().iter())); + self.legal_lens = lens; + self.legal_width = width; + Ok(( + PyArray1::from_vec(py, boards).reshape([n, 64]).expect("reshape"), + player.into_pyarray(py), + castling.into_pyarray(py), + ep.into_pyarray(py), + PyArray1::from_vec(py, legal).reshape([n, width]).expect("reshape"), + )) + } + + /// Like `apply`, with the legal moves' logits already gathered: row i holds + /// the logits at the indices of the last collect's `legal` row i. + fn apply_legal(&mut self, logits: PyReadonlyArray2, values: PyReadonlyArray1) -> PyResult<()> { + let logits = logits.as_array(); + let values = values.as_slice()?; + let total = self.legal_lens.len(); + let width = self.legal_width; + if values.len() != total || logits.shape() != [total, width] { + return Err(pyo3::exceptions::PyValueError::new_err(format!( + "apply_legal: got {} values / logits {:?} for {} pending positions of width {}", + values.len(), logits.shape(), total, width))); + } + let flat = logits.as_slice().ok_or_else(|| { + pyo3::exceptions::PyValueError::new_err("apply_legal: logits must be C-contiguous") + })?; + let lens = std::mem::take(&mut self.legal_lens); + let lens = &lens; + let mut offset = vec![None; self.games.len()]; + let mut at = 0; + for &(gi, k) in &self.owners { + offset[gi] = Some((at, k)); + at += k; + } + let offset = &offset; + self.par_games(|gi, g| { + let Some((at, k)) = offset[gi] else { return }; + let outputs: Vec = (at..at + k) + .map(|i| EvalOutput { logits: flat[i * width..i * width + lens[i] as usize].to_vec(), + value: values[i] }) + .collect(); + g.resolve(outputs); + }); + self.owners.clear(); + Ok(()) + } + + /// Outputs for the batch of the last collect(), in its order. + fn apply(&mut self, logits: PyReadonlyArray3, values: PyReadonlyArray1) -> PyResult<()> { + let logits = logits.as_array(); + let values = values.as_slice()?; + let total: usize = self.owners.iter().map(|o| o.1).sum(); + if values.len() != total || logits.shape() != [total, 64, 73] { + return Err(pyo3::exceptions::PyValueError::new_err(format!( + "apply: got {} values / logits {:?} for {} pending positions", + values.len(), logits.shape(), total))); + } + let flat = logits.as_slice().ok_or_else(|| { + pyo3::exceptions::PyValueError::new_err("apply: logits must be C-contiguous") + })?; + let mut offset = vec![None; self.games.len()]; + let mut at = 0; + for &(gi, k) in &self.owners { + offset[gi] = Some((at, k)); + at += k; + } + let offset = &offset; + self.par_games(|gi, g| { + let Some((at, k)) = offset[gi] else { return }; + let outputs: Vec = (at..at + k) + .map(|i| EvalOutput { logits: flat[i * POLICY..(i + 1) * POLICY].to_vec(), + value: values[i] }) + .collect(); + g.resolve(outputs); + }); + self.owners.clear(); + Ok(()) + } + + /// Completed games since the last call, as dicts of numpy arrays (the + /// `Engine.drain_finished` layout). + fn drain_finished<'py>(&mut self, py: Python<'py>) -> PyResult>> { + let mut out = Vec::new(); + for g in std::mem::take(&mut self.finished) { + let (z_white, end) = g.end().expect("finished game has a result"); + let recs = g.records(); + let p = recs.len(); + let mut boards = Vec::with_capacity(p * 64); + let (mut player, mut castling, mut ep) = (Vec::new(), Vec::new(), Vec::new()); + let (mut halfmove, mut root_v, mut z, mut full) = (Vec::new(), Vec::new(), Vec::new(), Vec::new()); + let (mut visit_idx, mut visit_cnt) = (Vec::new(), Vec::new()); + let mut visit_ptr = vec![0i64]; + for r in recs { + boards.extend_from_slice(&r.tokens); + player.push(r.player); + castling.push(r.castling); + ep.push(r.ep); + halfmove.push(r.halfmove); + root_v.push(r.root_v); + full.push(r.full); + z.push(if r.player == 1 { z_white } else { -z_white }); + visit_idx.extend_from_slice(&r.visit_idx); + visit_cnt.extend_from_slice(&r.visit_cnt); + visit_ptr.push(visit_idx.len() as i64); + } + let d = PyDict::new(py); + d.set_item("boards", PyArray1::from_vec(py, boards).reshape([p, 64]).expect("reshape"))?; + d.set_item("player", player.into_pyarray(py))?; + d.set_item("castling", castling.into_pyarray(py))?; + d.set_item("ep", ep.into_pyarray(py))?; + d.set_item("halfmove", halfmove.into_pyarray(py))?; + d.set_item("root_v", root_v.into_pyarray(py))?; + d.set_item("full", full.into_pyarray(py))?; + d.set_item("z", z.into_pyarray(py))?; + d.set_item("visit_idx", visit_idx.into_pyarray(py))?; + d.set_item("visit_cnt", visit_cnt.into_pyarray(py))?; + d.set_item("visit_ptr", visit_ptr.into_pyarray(py))?; + d.set_item("moves", g.moves_uci().to_vec())?; + d.set_item("fen", &self.opening_fens[g.opening])?; + d.set_item("z_white", z_white)?; + d.set_item("end", end)?; + d.set_item("resign_allowed", g.resign_allowed())?; + d.set_item("id", g.id)?; + out.push(d); + } + Ok(out) + } + + fn done(&self) -> bool { + self.completed >= self.target + } + + /// (games started, games completed, positions recorded, TT entries) + fn stats(&self) -> (usize, usize, usize, usize) { + let tt = self.games.iter().map(|g| g.tt_len()).sum(); + (self.started, self.completed, self.positions_recorded, tt) + } +}