diff --git a/benchmarks/run_snake_controller_benchmark.py b/benchmarks/run_snake_controller_benchmark.py index 83bcc63..9717baa 100644 --- a/benchmarks/run_snake_controller_benchmark.py +++ b/benchmarks/run_snake_controller_benchmark.py @@ -4,6 +4,7 @@ import argparse import json +import time import uuid from datetime import UTC, datetime from pathlib import Path @@ -39,6 +40,160 @@ def _now() -> str: return datetime.now(UTC).isoformat().replace("+00:00", "Z") +def _format_duration(seconds: float | None) -> str: + if seconds is None: + return "--:--:--" + whole = max(0, int(round(seconds))) + hours, remainder = divmod(whole, 3600) + minutes, secs = divmod(remainder, 60) + return f"{hours:02d}:{minutes:02d}:{secs:02d}" + + +class _ProgressReporter: + """Human-readable progress without affecting benchmark evidence or protocol identity.""" + + episode_step_interval = 4 + + def __init__( + self, + *, + config_id: str, + config_index: int, + config_total: int, + matrix_started: float, + ) -> None: + self.config_id = config_id + self.config_index = config_index + self.config_total = config_total + self.matrix_started = matrix_started + self.config_started = time.perf_counter() + self.phase_started = self.config_started + self.episode_started: float | None = None + self.last_food_eaten: int | None = None + + @property + def prefix(self) -> str: + return ( + f"[snake {self.config_index}/{self.config_total} " + f"{self.config_id}]" + ) + + def start_fixed(self, total: int) -> None: + self.phase_started = time.perf_counter() + print( + f"{self.prefix} fixed 0/{total} | elapsed 00:00:00 | ETA --:--:--", + flush=True, + ) + + def start_episodes(self, total: int, max_steps: int) -> None: + self.phase_started = time.perf_counter() + print( + f"{self.prefix} episodes 0/{total} | max_steps={max_steps} " + "| elapsed 00:00:00", + flush=True, + ) + + def __call__(self, event: dict[str, Any]) -> None: + now = time.perf_counter() + phase = event["phase"] + + if phase == "fixed": + completed = int(event["completed"]) + total = int(event["total"]) + elapsed = now - self.phase_started + eta = ( + elapsed / completed * (total - completed) + if completed > 0 + else None + ) + percent = 100.0 * completed / total if total else 100.0 + print( + f"{self.prefix} fixed {completed}/{total} | {percent:5.1f}% " + f"| case={event['case_id']} " + f"| elapsed {_format_duration(elapsed)} " + f"| ETA {_format_duration(eta)}", + flush=True, + ) + return + + if phase == "episode_start": + self.episode_started = now + self.last_food_eaten = 0 + print( + f"{self.prefix} episode {event['seed_index']}/{event['seed_total']} " + f"seed={event['seed']} start | max_steps={event['max_steps']}", + flush=True, + ) + return + + if phase == "episode_step": + step = int(event["step"]) + food_eaten = int(event["food_eaten"]) + stop_reason = event.get("stop_reason") + food_changed = food_eaten != self.last_food_eaten + should_print = ( + step <= 1 + or step % self.episode_step_interval == 0 + or food_changed + or stop_reason is not None + ) + self.last_food_eaten = food_eaten + if not should_print: + return + elapsed = ( + now - self.episode_started + if self.episode_started is not None + else 0.0 + ) + max_steps = int(event["max_steps"]) + eta = ( + elapsed / step * max(0, max_steps - step) + if step > 0 + else None + ) + suffix = f" | stop={stop_reason}" if stop_reason else "" + print( + f"{self.prefix} episode {event['seed_index']}/{event['seed_total']} " + f"seed={event['seed']} step {step}/{max_steps} " + f"| food={food_eaten} " + f"| elapsed {_format_duration(elapsed)} " + f"| ETA<={_format_duration(eta)}{suffix}", + flush=True, + ) + return + + if phase == "episode_complete": + elapsed = ( + now - self.episode_started + if self.episode_started is not None + else 0.0 + ) + print( + f"{self.prefix} episode {event['seed_index']}/{event['seed_total']} " + f"seed={event['seed']} complete " + f"| steps={event['step']} food={event['food_eaten']} " + f"| stop={event['stop_reason']} " + f"| elapsed {_format_duration(elapsed)}", + flush=True, + ) + + def complete(self) -> None: + now = time.perf_counter() + config_elapsed = now - self.config_started + matrix_elapsed = now - self.matrix_started + remaining = self.config_total - self.config_index + overall_eta = ( + matrix_elapsed / self.config_index * remaining + if self.config_index > 0 + else None + ) + print( + f"{self.prefix} complete | elapsed {_format_duration(config_elapsed)} " + f"| overall ETA~{_format_duration(overall_eta)}", + flush=True, + ) + + def _requested_model_identity(args: argparse.Namespace) -> dict[str, Any]: path = args.model.expanduser() exists = path.is_file() @@ -200,15 +355,33 @@ def run(args: argparse.Namespace) -> dict[str, Any]: }, ) - for config_id in args.configs: + matrix_started = time.perf_counter() + for config_index, config_id in enumerate(args.configs, start=1): config = CONFIGS[config_id] config_started = _now() fixed = episodes = runtime = None + progress = _ProgressReporter( + config_id=config_id, + config_index=config_index, + config_total=len(args.configs), + matrix_started=matrix_started, + ) try: backend.clear_repeated_state_cache() backend.reset_runtime_metrics() scorer = build_scorer(config, backend) - fixed = fixed_state_benchmark(cases, scorer, config, planner) + progress.start_fixed(len(cases)) + fixed = fixed_state_benchmark( + cases, + scorer, + config, + planner, + progress_callback=progress, + ) + progress.start_episodes( + len(args.episode_seeds), + args.episode_max_steps, + ) episodes = episode_benchmark( scorer, config, @@ -217,6 +390,7 @@ def run(args: argparse.Namespace) -> dict[str, Any]: height=args.height, max_steps=args.episode_max_steps, stall_steps=args.stall_steps, + progress_callback=progress, ) runtime = runtime_metrics(backend) row = _ledger_record( @@ -243,6 +417,7 @@ def run(args: argparse.Namespace) -> dict[str, Any]: f"median_food={episodes['median_food_eaten']}", flush=True, ) + progress.complete() except Exception as exc: try: runtime = runtime or runtime_metrics(backend) diff --git a/benchmarks/snake-controller-benchmark-v1.md b/benchmarks/snake-controller-benchmark-v1.md index 808e557..6b77771 100644 --- a/benchmarks/snake-controller-benchmark-v1.md +++ b/benchmarks/snake-controller-benchmark-v1.md @@ -129,6 +129,12 @@ uv run python -m benchmarks.run_snake_controller_benchmark \ --threads 2 --threads-batch 2 ``` + +The runner prints live terminal progress without changing the benchmark protocol or evidence payload: +fixed-state progress is reported after every case with elapsed time and ETA; episode progress reports +seed start/completion plus every fourth step, food changes and terminal conditions. Episode ETA is an +upper-bound estimate against `max_steps` because games may finish earlier. + For a cheap smoke, reduce fixed states and episode length without relabelling it representative: ```bash diff --git a/benchmarks/snake_controller_benchmark.py b/benchmarks/snake_controller_benchmark.py index 29ba9fc..2ea5b1f 100644 --- a/benchmarks/snake_controller_benchmark.py +++ b/benchmarks/snake_controller_benchmark.py @@ -11,7 +11,7 @@ from collections import deque from dataclasses import dataclass from pathlib import Path -from typing import Any +from typing import Any, Callable from decisio.baselines import GeneratedJsonScorer from decisio.schema import DecisionResult @@ -24,6 +24,7 @@ SCHEMA_VERSION = 2 DEFAULT_FIXTURE = Path("benchmarks/fixtures/snake-controller-v1.jsonl") DEFAULT_LEDGER = Path(".artifacts/snake-controller/history.jsonl") +ProgressCallback = Callable[[dict[str, Any]], None] @dataclass(frozen=True, slots=True) @@ -273,11 +274,13 @@ def fixed_state_benchmark( scorer: Any, config: ControllerConfig, planner: SnakePlanner, + *, + progress_callback: ProgressCallback | None = None, ) -> dict[str, Any]: records: list[dict[str, Any]] = [] all_latencies: list[float] = [] model_latencies: list[float] = [] - for case in cases: + for case_index, case in enumerate(cases, start=1): plan: PlannerResult = planner.evaluate(game_from_case(case)) choice, latency, mode, decision = controller_decision( game_from_case(case), scorer, config @@ -354,6 +357,15 @@ def fixed_state_benchmark( "planner": plan.to_dict(), } ) + if progress_callback is not None: + progress_callback( + { + "phase": "fixed", + "completed": case_index, + "total": len(cases), + "case_id": str(case["id"]), + } + ) total = len(records) oracle_records = [row for row in records if row["oracle_complete"]] @@ -412,6 +424,7 @@ def run_episode( height: int, max_steps: int, stall_steps: int, + progress_callback: ProgressCallback | None = None, ) -> dict[str, Any]: game = SnakeGame(width=width, height=height, seed=seed) initial_length = len(game.snake) @@ -434,6 +447,17 @@ def run_episode( generated_tokens += int((decision or {}).get("generated_tokens", 0)) if choice is None: reason = "invalid_choice" + if progress_callback is not None: + progress_callback( + { + "phase": "episode_step", + "seed": seed, + "step": game.steps, + "max_steps": max_steps, + "food_eaten": game.score, + "stop_reason": reason, + } + ) break score_before = game.score @@ -452,8 +476,22 @@ def run_episode( if signature in seen_states: reason = "loop_detected" loop_detected = True + else: + seen_states.add(signature) + + if progress_callback is not None: + progress_callback( + { + "phase": "episode_step", + "seed": seed, + "step": game.steps, + "max_steps": max_steps, + "food_eaten": game.score, + "stop_reason": reason if loop_detected or not game.alive else None, + } + ) + if loop_detected: break - seen_states.add(signature) possible_food = width * height - initial_length return { @@ -486,9 +524,32 @@ def episode_benchmark( height: int, max_steps: int, stall_steps: int, + progress_callback: ProgressCallback | None = None, ) -> dict[str, Any]: - rows = [ - run_episode( + rows: list[dict[str, Any]] = [] + for seed_index, seed in enumerate(seeds, start=1): + if progress_callback is not None: + progress_callback( + { + "phase": "episode_start", + "seed": seed, + "seed_index": seed_index, + "seed_total": len(seeds), + "max_steps": max_steps, + } + ) + + def on_step(event: dict[str, Any]) -> None: + if progress_callback is not None: + progress_callback( + { + **event, + "seed_index": seed_index, + "seed_total": len(seeds), + } + ) + + row = run_episode( scorer, config, seed=seed, @@ -496,9 +557,22 @@ def episode_benchmark( height=height, max_steps=max_steps, stall_steps=stall_steps, + progress_callback=on_step, ) - for seed in seeds - ] + rows.append(row) + if progress_callback is not None: + progress_callback( + { + "phase": "episode_complete", + "seed": seed, + "seed_index": seed_index, + "seed_total": len(seeds), + "step": row["steps"], + "max_steps": max_steps, + "food_eaten": row["food_eaten"], + "stop_reason": row["stop_reason"], + } + ) return { "episodes": len(rows), "median_food_eaten": statistics.median(row["food_eaten"] for row in rows), diff --git a/tests/test_snake_controller_benchmark.py b/tests/test_snake_controller_benchmark.py index 627c923..2356b72 100644 --- a/tests/test_snake_controller_benchmark.py +++ b/tests/test_snake_controller_benchmark.py @@ -14,6 +14,7 @@ CONFIGS, SnakePlanner, append_ledger, + episode_benchmark, fixed_state_benchmark, game_from_case, ) @@ -113,6 +114,53 @@ def test_fixed_state_records_raw_decision_evidence(): assert record["decision"]["choice"] == "up" assert record["reverse_decision"]["choice"] == "down" + +def test_fixed_state_progress_callback_reports_completed_cases(): + events = [] + fixed_state_benchmark( + [_case()], + FirstCandidateScorer(), + CONFIGS["direct-stateful-verbose"], + SnakePlanner(max_nodes=10_000), + progress_callback=events.append, + ) + + assert events == [ + { + "phase": "fixed", + "completed": 1, + "total": 1, + "case_id": "easy-up", + } + ] + + +def test_episode_progress_callback_reports_seed_steps_and_completion(): + events = [] + episode_benchmark( + FirstCandidateScorer(), + CONFIGS["direct-stateful-verbose"], + seeds=[7], + width=8, + height=8, + max_steps=2, + stall_steps=2, + progress_callback=events.append, + ) + + assert events[0] == { + "phase": "episode_start", + "seed": 7, + "seed_index": 1, + "seed_total": 1, + "max_steps": 2, + } + assert any(event["phase"] == "episode_step" for event in events) + assert events[-1]["phase"] == "episode_complete" + assert events[-1]["seed"] == 7 + assert events[-1]["seed_index"] == 1 + assert events[-1]["seed_total"] == 1 + def test_ledger_is_append_only_and_preserves_parameters(tmp_path: Path): ledger = tmp_path / "history.jsonl" first = {