File size: 14,521 Bytes
7d90172 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 | #!/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()
|