#!/usr/bin/env python3 """Build SPAgent training data for three VRBench navigation environments. The resulting prompts and images follow the FrozenLake v3 interaction contract. Beyond-MMEnv is used only to sample official initial states; rollout transitions and reward replay use ``spagent.vrbench_navigation_protocol``. """ from __future__ import annotations import argparse 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" / "vrbench_navigation_v1" ) if str(REPO_ROOT) not in sys.path: sys.path.insert(0, str(REPO_ROOT)) from spagent.vrbench_navigation_protocol import ( # noqa: E402 MAZE_TASK, PATHFINDER_TASK, SUPPORTED_TASKS, TRAPFIELD_SOLVABLE_SEEDS, TRAPFIELD_TASK, build_system_prompt, build_user_prompt, canonical_state, encode_initial_state, render_state, shortest_path, state_text, ) _SAMPLING_ENV: Any = None 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_state(env: Any) -> Dict[str, Any]: base = env.unwrapped return canonical_state( grid=base._grid, start=(base._pr, base._pc), goal=(base._gr, base._gc), ) def sample_state(env: Any, seed: int) -> Dict[str, Any]: env.reset(seed=seed) return extract_state(env) def task_slug(task_id: str) -> str: return { PATHFINDER_TASK: "pathfinder", MAZE_TASK: "maze", TRAPFIELD_TASK: "trapfield", }[task_id] def seed_candidates( task_id: str, *, start_seed: int, max_seed_attempts: int, ) -> Iterable[int]: stop = start_seed + max_seed_attempts if task_id != TRAPFIELD_TASK: yield from range(start_seed, stop) return known = set() for seed in TRAPFIELD_SOLVABLE_SEEDS: if seed not in known: known.add(seed) yield seed for seed in range(start_seed, stop): if seed not in known: yield seed def _init_sampling_worker(beyond_root: str, task_id: str) -> None: global _SAMPLING_ENV gym_v = _import_gym_v(Path(beyond_root)) try: from loguru import logger logger.remove() except (ImportError, ValueError): pass _SAMPLING_ENV = gym_v.make(task_id) def _sample_seed_batch( seed_start: int, seed_stop: int, ) -> tuple[int, int, List[tuple[int, Dict[str, Any], List[str]]], int]: if _SAMPLING_ENV is None: raise RuntimeError("Sampling worker environment was not initialized") solvable: List[tuple[int, Dict[str, Any], List[str]]] = [] errors = 0 for seed in range(seed_start, seed_stop): try: state = sample_state(_SAMPLING_ENV, seed) solution = shortest_path(state) except Exception: errors += 1 continue if solution is not None: solvable.append((seed, state, solution)) return seed_start, seed_stop, solvable, errors def build_record( *, task_id: str, state: Dict[str, Any], solution: List[str], 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) 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, state), }, { "role": "user", "content": build_user_prompt(task_id, state, image_path), }, ], "images": [str(image_path.resolve())], "initial_state": encode_initial_state(state), "state_text": state_text(state, initial=True), "solution": " ".join(solution), "optimal_length": len(solution), "solvable": True, "deterministic": True, "fully_observed": True, } def _build_record_job( task_id: str, state: Dict[str, Any], solution: List[str], seed: int, index: int, output_dir: str, ) -> Dict[str, Any]: return build_record( task_id=task_id, state=state, solution=solution, seed=seed, index=index, output_dir=Path(output_dir), ) def collect_records( *, gym_v: Any, task_id: str, count: int, start_seed: int, max_seed_attempts: int, output_dir: Path, workers: int, beyond_root: Path, ) -> tuple[List[Dict[str, Any]], int]: selected: List[tuple[int, Dict[str, Any], List[str]]] = [] seen = set() scanned = 0 errors = 0 def consume( seed: int, state: Dict[str, Any], solution: List[str], ) -> None: encoded = encode_initial_state(state) if encoded in seen: return seen.add(encoded) selected.append((seed, state, solution)) if len(selected) % 100 == 0 or len(selected) == count: print( f"[{task_id}] selected {len(selected)}/{count} " f"(scanned {scanned} seeds)", flush=True, ) if workers == 1: env = gym_v.make(task_id) try: for seed in seed_candidates( task_id, start_seed=start_seed, max_seed_attempts=max_seed_attempts, ): if len(selected) >= count or scanned >= max_seed_attempts: break scanned += 1 try: state = sample_state(env, seed) solution = shortest_path(state) except Exception as exc: errors += 1 print( f"[skip] {task_id} seed={seed}: " f"{type(exc).__name__}: {exc}", flush=True, ) continue if solution is not None: consume(seed, state, solution) finally: env.close() else: next_seed = start_seed sample_batch_size = 256 with ProcessPoolExecutor( max_workers=workers, initializer=_init_sampling_worker, initargs=(str(beyond_root), task_id), ) as executor: while len(selected) < count and scanned < max_seed_attempts: remaining = max_seed_attempts - scanned window = min(remaining, workers * sample_batch_size * 8) seed_stop = next_seed + window ranges = [ ( batch_start, min(batch_start + sample_batch_size, seed_stop), ) for batch_start in range( next_seed, seed_stop, sample_batch_size, ) ] next_seed = seed_stop batches = executor.map( _sample_seed_batch, *(zip(*ranges)), chunksize=1, ) done = False for batch_start, batch_stop, candidates, batch_errors in batches: scanned += batch_stop - batch_start errors += batch_errors for seed, state, solution in candidates: if len(selected) >= count: done = True break consume(seed, state, solution) if done: break if scanned % 100000 < sample_batch_size: print( f"[{task_id}] scanned {scanned} seeds; " f"selected {len(selected)}/{count}", flush=True, ) if len(selected) != count: raise RuntimeError( f"Selected only {len(selected)}/{count} records for {task_id} " f"after {scanned} seed attempts ({errors} reset errors)" ) jobs = [ ( task_id, state, solution, seed, index, str(output_dir), ) for index, (seed, state, solution) in enumerate(selected) ] if workers == 1: records = [_build_record_job(*job) for job in jobs] else: with ProcessPoolExecutor(max_workers=workers) as executor: records = list(executor.map(_build_record_job, *zip(*jobs))) print( f"[{task_id}] rendered {len(records)}/{count} with {workers} workers", flush=True, ) return records, scanned 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 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 parse_args() -> argparse.Namespace: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "--beyond-root", type=Path, default=DEFAULT_BEYOND_ROOT, ) parser.add_argument( "--output-dir", type=Path, default=DEFAULT_OUTPUT_DIR, ) parser.add_argument( "--task", action="append", choices=SUPPORTED_TASKS, help="Task to build; repeat for multiple tasks. Defaults to all three.", ) parser.add_argument("--count-per-task", type=int, default=2000) 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=1500000) parser.add_argument("--workers", type=int, default=16) 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 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") 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): records, scanned = collect_records( gym_v=gym_v, task_id=task_id, count=args.count_per_task, start_seed=args.start_seed, max_seed_attempts=args.max_seed_attempts, output_dir=output_dir, workers=args.workers, beyond_root=args.beyond_root.resolve(), ) unique_initial_states = len( {str(record["initial_state"]) for record in records} ) 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_attempts": scanned, } random.Random(args.split_seed).shuffle(combined_train) random.Random(args.split_seed + 1).shuffle(combined_test) write_jsonl( output_dir / "vrbench_navigation_train_v1.jsonl", combined_train, ) write_jsonl( output_dir / "vrbench_navigation_test_v1.jsonl", combined_test, ) manifest = { "format": "spagent-vrbench-navigation-v1", "tasks": manifest_tasks, "combined_train": len(combined_train), "combined_test": len(combined_test), "test_ratio": args.test_ratio, "sampling_workers": args.workers, "render_workers": args.workers, "fully_observed": True, "deterministic": True, "interaction_contract": "SPAgent/FrozenLake-v3", } (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()