#!/usr/bin/env python3 """Build SPAgent GRPO datasets for Sokoban and FifteenPuzzle. Initial states are sampled from the registered Beyond-MMEnv environments. Images and transitions use ``spagent.grid_puzzle_protocol`` so the initial frame, rollout frames, direct-answer replay, and reward logic cannot drift. Example smoke build: /path/to/mmenv-pool/.venv/bin/python \ train/build_grid_puzzle_training_data.py \ --count-per-task 10 \ --output-dir outputs/grpo_converted/grid_puzzles_v1_smoke The FifteenPuzzle upstream generator shuffles without a parity check. This builder rejects unsolvable boards and records only verified-solvable states. """ from __future__ import annotations import argparse import copy import json import random import sys from concurrent.futures import ProcessPoolExecutor from pathlib import Path from typing import Any, Dict, Iterable, List, Sequence REPO_ROOT = Path(__file__).resolve().parents[1] THINK_WITH_IMAGES_ROOT = REPO_ROOT.parents[1] DEFAULT_BEYOND_ROOT = THINK_WITH_IMAGES_ROOT / "Beyond-MMEnv-Scaling" DEFAULT_OUTPUT_DIR = REPO_ROOT / "outputs" / "grpo_converted" / "grid_puzzles_v1" if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT)) from spagent.grid_puzzle_protocol import ( # noqa: E402 FIFTEEN_TASK, SOKOBAN_TASK, SUPPORTED_TASKS, build_system_prompt, build_user_prompt, canonical_fifteen_state, canonical_sokoban_state, encode_initial_state, render_state, state_text, ) _WORKER_ENV: Any = None def is_fifteen_solvable(board: Sequence[int], *, size: int = 4) -> bool: """Return the standard even-width sliding-puzzle parity test.""" values = [int(value) for value in board] nonzero = [value for value in values if value != 0] inversions = sum( 1 for i, left in enumerate(nonzero) for right in nonzero[i + 1:] if left > right ) blank_row_from_bottom = size - (values.index(0) // size) if size % 2 == 1: return inversions % 2 == 0 return (blank_row_from_bottom % 2 == 0) != (inversions % 2 == 0) def _import_gym_v(beyond_root: Path) -> Any: pool_root = beyond_root / "mmenv-pool" if not pool_root.is_dir(): raise FileNotFoundError(f"Beyond-MMEnv mmenv-pool not found: {pool_root}") if str(pool_root) not in sys.path: sys.path.insert(0, str(pool_root)) try: import gym_v import gym_v.envs # noqa: F401 except ImportError as exc: raise RuntimeError( "Could not import gym_v. Run this builder with the mmenv-pool " "virtualenv, for example:\n" f" {pool_root}/.venv/bin/python {Path(__file__).resolve()}" ) from exc return gym_v def _extract_sokoban_state(base: Any) -> Dict[str, Any]: room_state = base._ta_env.room_state room_fixed = base._ta_env.room_fixed rows, cols = room_state.shape walls = [] goals = [] boxes = [] players = [] for r in range(rows): for c in range(cols): fixed = int(room_fixed[r, c]) current = int(room_state[r, c]) if fixed == 0: walls.append((r, c)) if fixed == 2: goals.append((r, c)) if current in (3, 4): boxes.append((r, c)) if current in (5, 6): players.append((r, c)) if len(players) != 1: raise RuntimeError(f"Expected exactly one Sokoban player, found {players}") return canonical_sokoban_state( rows=rows, cols=cols, walls=walls, goals=goals, boxes=boxes, player=players[0], ) def _extract_fifteen_state(base: Any) -> Dict[str, Any]: board = [ 0 if value is None else int(value) for row in base._ta_env.board for value in row ] return canonical_fifteen_state(board) def sample_state(env: Any, task_id: str, seed: int) -> Dict[str, Any]: env.reset(seed=seed) base = env.unwrapped if task_id == SOKOBAN_TASK: return _extract_sokoban_state(base) if task_id == FIFTEEN_TASK: return _extract_fifteen_state(base) raise ValueError(f"Unsupported task_id: {task_id}") def _init_sampling_worker(beyond_root: str, task_id: str) -> None: """Create one reusable environment per sampling worker.""" global _WORKER_ENV gym_v = _import_gym_v(Path(beyond_root)) try: from loguru import logger logger.remove() except (ImportError, ValueError): pass _WORKER_ENV = gym_v.make(task_id) def _sample_seed_batch( task_id: str, seed_start: int, seed_stop: int, ) -> List[tuple[int, Dict[str, Any] | None, str | None]]: if _WORKER_ENV is None: raise RuntimeError("Sampling worker environment was not initialized") results: List[tuple[int, Dict[str, Any] | None, str | None]] = [] for seed in range(seed_start, seed_stop): try: state = sample_state(_WORKER_ENV, task_id, seed) except Exception as exc: results.append( (seed, None, f"{type(exc).__name__}: {exc}") ) else: results.append((seed, state, None)) return results def _task_slug(task_id: str) -> str: return "sokoban" if task_id == SOKOBAN_TASK else "fifteen_puzzle" def build_record( *, task_id: str, state: Dict[str, Any], seed: int, index: int, output_dir: Path, ) -> Dict[str, Any]: slug = _task_slug(task_id) image_path = output_dir / "images" / slug / f"{slug}_{index:06d}.png" render_state(task_id, state, image_path) encoded = encode_initial_state(state) return { "id": f"{slug}_{index:06d}", "task_id": task_id, "source_env": task_id, "source_seed": seed, "messages": [ {"role": "system", "content": build_system_prompt(task_id)}, { "role": "user", "content": build_user_prompt(task_id, state, image_path), }, ], "images": [str(image_path.resolve())], "initial_state": encoded, "state_text": state_text(task_id, state), "solvable": True, "deterministic": True, "fully_observed": True, } def collect_records( *, gym_v: Any, task_id: str, count: int, start_seed: int, output_dir: Path, max_seed_attempts: int, beyond_root: Path, workers: int, sample_batch_size: int, ) -> List[Dict[str, Any]]: records: List[Dict[str, Any]] = [] seen = set() attempts = 0 def consume( seed: int, state: Dict[str, Any] | None, error: str | None, ) -> None: nonlocal attempts attempts += 1 if error is not None or state is None: print( f"[skip] {task_id} seed={seed}: " f"{error or 'missing state'}", flush=True, ) return encoded = encode_initial_state(state) if encoded in seen: return if ( task_id == FIFTEEN_TASK and not is_fifteen_solvable(state["board"]) ): return seen.add(encoded) records.append( build_record( task_id=task_id, state=state, seed=seed, index=len(records), output_dir=output_dir, ) ) if len(records) % 100 == 0 or len(records) == count: print( f"[{task_id}] built {len(records)}/{count} " f"(scanned {attempts} seeds)", flush=True, ) if workers == 1: seed = start_seed env = gym_v.make(task_id) try: while len(records) < count and attempts < max_seed_attempts: try: state = sample_state(env, task_id, seed) except Exception as exc: consume( seed, None, f"{type(exc).__name__}: {exc}", ) else: consume(seed, state, None) seed += 1 finally: env.close() else: next_seed = start_seed with ProcessPoolExecutor( max_workers=workers, initializer=_init_sampling_worker, initargs=(str(beyond_root), task_id), ) as executor: while len(records) < count and attempts < max_seed_attempts: remaining = max_seed_attempts - attempts window = min( remaining, workers * sample_batch_size * 4, ) ranges = [] seed_stop = next_seed + window for batch_start in range( next_seed, seed_stop, sample_batch_size ): ranges.append( ( task_id, batch_start, min(batch_start + sample_batch_size, seed_stop), ) ) next_seed = seed_stop batches = executor.map( _sample_seed_batch, *(zip(*ranges)), chunksize=1, ) done = False for batch in batches: for seed, state, error in batch: if ( len(records) >= count or attempts >= max_seed_attempts ): done = True break consume(seed, state, error) if done: break if len(records) != count: raise RuntimeError( f"Built only {len(records)}/{count} records for {task_id} after " f"{attempts} seed attempts" ) return records def _write_jsonl(path: Path, records: Iterable[Dict[str, Any]]) -> None: path.parent.mkdir(parents=True, exist_ok=True) with path.open("w", encoding="utf-8") as handle: for record in records: handle.write(json.dumps(record, ensure_ascii=False) + "\n") def split_records( records: Sequence[Dict[str, Any]], *, test_ratio: float, split_seed: int, ) -> tuple[List[Dict[str, Any]], List[Dict[str, Any]]]: shuffled = list(records) random.Random(split_seed).shuffle(shuffled) if not shuffled: return [], [] test_count = int(len(shuffled) * test_ratio) if test_ratio > 0 and len(shuffled) > 1: test_count = max(1, test_count) test_count = min(test_count, max(0, len(shuffled) - 1)) return shuffled[test_count:], shuffled[:test_count] def pad_records( records: Sequence[Dict[str, Any]], *, count: int, seed: int, ) -> List[Dict[str, Any]]: """Deterministically repeat records when the source has fewer unique states.""" padded = list(records) if len(padded) >= count: return padded[:count] if not padded: raise ValueError("Cannot pad an empty record collection") pool = list(records) random.Random(seed).shuffle(pool) while len(padded) < count: source = pool[(len(padded) - len(records)) % len(pool)] repeated = copy.deepcopy(source) slug = _task_slug(str(source["task_id"])) repeated["id"] = f"{slug}_{len(padded):06d}" repeated["duplicate_of"] = source["id"] padded.append(repeated) return padded def parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--beyond-root", type=Path, default=DEFAULT_BEYOND_ROOT, help=f"Beyond-MMEnv-Scaling root (default: {DEFAULT_BEYOND_ROOT})", ) parser.add_argument( "--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR, help=f"Dataset output directory (default: {DEFAULT_OUTPUT_DIR})", ) parser.add_argument( "--task", action="append", choices=SUPPORTED_TASKS, help="Task to build; repeat for multiple tasks. Defaults to both.", ) parser.add_argument("--count-per-task", type=int, default=2000) parser.add_argument( "--sokoban-count", type=int, default=None, help="Override --count-per-task for Games/Sokoban-v0.", ) parser.add_argument( "--fifteen-count", type=int, default=None, help="Override --count-per-task for Games/FifteenPuzzle-v0.", ) parser.add_argument( "--sokoban-unique-count", type=int, default=1600, help=( "Unique Sokoban states to collect before deterministic padding. " "The official fixed 6x6 generator has fewer than 2000 practical " "unique states." ), ) parser.add_argument("--test-ratio", type=float, default=0.0) parser.add_argument("--start-seed", type=int, default=0) parser.add_argument("--split-seed", type=int, default=0) parser.add_argument("--max-seed-attempts", type=int, default=100000) parser.add_argument( "--workers", type=int, default=16, help="Parallel sampling workers; use 1 for serial generation.", ) parser.add_argument( "--sample-batch-size", type=int, default=16, help="Consecutive seeds sampled per worker job.", ) return parser.parse_args() def main() -> None: args = parse_args() if args.count_per_task <= 0: raise SystemExit("--count-per-task must be positive") if args.sokoban_count is not None and args.sokoban_count <= 0: raise SystemExit("--sokoban-count must be positive") if args.fifteen_count is not None and args.fifteen_count <= 0: raise SystemExit("--fifteen-count must be positive") if args.sokoban_unique_count <= 0: raise SystemExit("--sokoban-unique-count must be positive") if not 0 <= args.test_ratio < 1: raise SystemExit("--test-ratio must be in [0, 1)") if args.workers <= 0: raise SystemExit("--workers must be positive") if args.sample_batch_size <= 0: raise SystemExit("--sample-batch-size must be positive") tasks = args.task or list(SUPPORTED_TASKS) output_dir = args.output_dir.resolve() output_dir.mkdir(parents=True, exist_ok=True) gym_v = _import_gym_v(args.beyond_root.resolve()) combined_train: List[Dict[str, Any]] = [] combined_test: List[Dict[str, Any]] = [] manifest_tasks: Dict[str, Any] = {} for task_offset, task_id in enumerate(tasks): if task_id == SOKOBAN_TASK: task_count = args.sokoban_count or args.count_per_task collection_count = min(task_count, args.sokoban_unique_count) else: task_count = args.fifteen_count or args.count_per_task collection_count = task_count records = collect_records( gym_v=gym_v, task_id=task_id, count=collection_count, start_seed=args.start_seed, output_dir=output_dir, max_seed_attempts=args.max_seed_attempts, beyond_root=args.beyond_root.resolve(), workers=args.workers, sample_batch_size=args.sample_batch_size, ) unique_initial_states = len( {str(record["initial_state"]) for record in records} ) records = pad_records( records, count=task_count, seed=args.split_seed + task_offset, ) train, test = split_records( records, test_ratio=args.test_ratio, split_seed=args.split_seed + task_offset, ) slug = _task_slug(task_id) _write_jsonl(output_dir / f"{slug}_all_v1.jsonl", records) _write_jsonl(output_dir / f"{slug}_train_v1.jsonl", train) _write_jsonl(output_dir / f"{slug}_test_v1.jsonl", test) combined_train.extend(train) combined_test.extend(test) manifest_tasks[task_id] = { "records": len(records), "train": len(train), "test": len(test), "unique_initial_states": unique_initial_states, "repeated_records": len(records) - unique_initial_states, "seed_range_scanned_from": args.start_seed, } random.Random(args.split_seed).shuffle(combined_train) random.Random(args.split_seed + 1).shuffle(combined_test) _write_jsonl(output_dir / "grid_puzzles_train_v1.jsonl", combined_train) _write_jsonl(output_dir / "grid_puzzles_test_v1.jsonl", combined_test) manifest = { "format": "spagent-grid-puzzles-v1", "tasks": manifest_tasks, "combined_train": len(combined_train), "combined_test": len(combined_test), "test_ratio": args.test_ratio, "sampling_workers": args.workers, "fully_observed": True, "deterministic": True, "fifteen_filter": "standard sliding-puzzle parity", } (output_dir / "manifest.json").write_text( json.dumps(manifest, indent=2, ensure_ascii=False) + "\n", encoding="utf-8", ) print(f"DONE: {output_dir}") print(json.dumps(manifest, indent=2, ensure_ascii=False)) if __name__ == "__main__": main()