Download misc/code_recovered/ViewAgent/cem_vlm_test_extension.py from kobemanba-shared/vsnext-migration: direct link, hf CLI and curl.
- Browser
- Download file 40.1 kB
-
https://huggingface.co/datasets/kobemanba-shared/vsnext-migration/resolve/main/misc/code_recovered/ViewAgent/cem_vlm_test_extension.py
- Command line
-
hf download hf://datasets/kobemanba-shared/vsnext-migration/misc/code_recovered/ViewAgent/cem_vlm_test_extension.py
-
curl -L -o cem_vlm_test_extension.py https://huggingface.co/datasets/kobemanba-shared/vsnext-migration/resolve/main/misc/code_recovered/ViewAgent/cem_vlm_test_extension.py
40.1 kB
| """CEM-primary IVP planner with a paper-checkpoint VLM soft action prior. | |
| The VLM never receives a grid of candidate lookahead images and never directly | |
| overrides the controller. At each real state it sees the standard official IVP | |
| conversation, proposes ordinary camera actions, and its proposal only biases | |
| CEM's initial sampling distribution. Renderer scores and elite refitting remain | |
| authoritative. Exactly one CEM-selected action is executed, then the official | |
| environment returns a new real observation. | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import asyncio | |
| import base64 | |
| from collections import Counter | |
| import hashlib | |
| import importlib.metadata | |
| import io | |
| import json | |
| import os | |
| from pathlib import Path | |
| import time | |
| import numpy as np | |
| from openai import AsyncOpenAI | |
| from PIL import Image | |
| from scipy.spatial.transform import Rotation | |
| from cem_official_harness import ( | |
| CEM, | |
| KEYS, | |
| NAMES, | |
| NA, | |
| Scorer, | |
| atomic_json, | |
| pose_error, | |
| roll, | |
| rotation_error_deg, | |
| ) | |
| from merge_cem_official_submit import CALIBRATION_SCENES, VALIDATION_SCENES | |
| from view_suite.envs.scannet_proxy_task.interactive_view_planning import ( | |
| InteractiveViewPlanning, | |
| ) | |
| ROOT = Path(__file__).resolve().parent | |
| DATA = ROOT / "data" / "viewsuite_15k" | |
| ACTION_TO_ID = {NAMES[key]: index for index, key in enumerate(KEYS)} | |
| SCENE_SPLIT_SHA256 = "bb238c2164e727bfbd5b19d3c3c12323e8d870938d053333c9b9010a40c2ac1d" | |
| CAMERA_ACTIONS = frozenset(ACTION_TO_ID) | |
| DINOV2_REVISION = "f9e44c814b77203eaa57a6bdbbd535f21ede1415" | |
| DINOV2_FILES = { | |
| "model.safetensors": "d73036b56966966d07975d696bde331762f37297e2f095de8cea0040c3aa0841", | |
| "config.json": "f7ff4cfa73d2f70647dbf6950541ad25d73082d54c2e7e9bded160c7656b2a70", | |
| "preprocessor_config.json": "14e780d86fa1861f8751f868d7f45425b5feb55c38ca26f152ca5097ab30f828", | |
| } | |
| FROZEN_RENDERER_CEM_SHA256 = ( | |
| "ed5764a0113bcccc8535866e9fd90461fe5f52b5780da7f956ee76ef795effce" | |
| ) | |
| def test_env_config(dataset_path: Path, max_turns: int) -> dict: | |
| """Official submit-mode environment bound to the independent test JSONL.""" | |
| return { | |
| "jsonl_path": str(dataset_path), | |
| "max_turns": max_turns, | |
| "render_backend": "client", | |
| "client_url_file_path": os.environ.get( | |
| "CEM_URL_FILE", str(ROOT / "client_url_cem.txt") | |
| ), | |
| "image_size": [512, 512], | |
| "format": "eval_mode", | |
| "use_example_in_sys_prompt": False, | |
| "action_only_mode": True, | |
| "no_submit": False, | |
| } | |
| def file_sha256(path: Path) -> str: | |
| digest = hashlib.sha256() | |
| with path.open("rb") as handle: | |
| for block in iter(lambda: handle.read(1024 * 1024), b""): | |
| digest.update(block) | |
| return digest.hexdigest() | |
| def package_versions() -> dict[str, str]: | |
| versions = {} | |
| for distribution in ("numpy", "openai", "Pillow", "scipy", "sglang", "torch", "transformers"): | |
| try: | |
| versions[distribution] = importlib.metadata.version(distribution) | |
| except importlib.metadata.PackageNotFoundError: | |
| versions[distribution] = "not-installed-in-client-environment" | |
| return versions | |
| def checkpoint_provenance(model_path: Path) -> dict: | |
| """Fingerprint the exact checkpoint using the precomputed full-file manifest. | |
| Hashing the 33 GB checkpoint independently in every calibration shard would | |
| create avoidable shared-filesystem load. The manifest itself contains a | |
| SHA256 for every weight/config/tokenizer file and is generated and verified | |
| once before any GPU run; here we additionally verify every recorded size. | |
| """ | |
| manifest_path = ROOT / "viewagent_ivp_checkpoint_manifest_2026-08-02.json" | |
| if not manifest_path.is_file(): | |
| raise FileNotFoundError(f"checkpoint manifest not found: {manifest_path}") | |
| manifest = json.loads(manifest_path.read_text()) | |
| if Path(manifest.get("model_path", "")) != model_path: | |
| raise RuntimeError("checkpoint manifest model_path does not match --model") | |
| entries = manifest.get("files") | |
| if not isinstance(entries, list) or not entries: | |
| raise RuntimeError("checkpoint manifest has no files") | |
| verified_entries = [] | |
| for entry in entries: | |
| path = model_path / entry["name"] | |
| if not path.is_file(): | |
| raise FileNotFoundError(f"checkpoint file missing: {path}") | |
| stat = path.stat() | |
| if stat.st_size != int(entry["size_bytes"]): | |
| raise RuntimeError(f"checkpoint file size changed: {path}") | |
| if stat.st_size <= 64 * 1024 * 1024 and file_sha256(path) != entry["sha256"]: | |
| raise RuntimeError(f"checkpoint file SHA changed: {path}") | |
| verified_entries.append({**entry, "mtime_ns": stat.st_mtime_ns}) | |
| return { | |
| "path": str(model_path), | |
| "manifest_path": str(manifest_path), | |
| "manifest_sha256": file_sha256(manifest_path), | |
| "files": verified_entries, | |
| } | |
| def dinov2_provenance() -> dict: | |
| hf_home = Path(os.environ.get("HF_HOME", str(Path.home() / ".cache" / "huggingface"))) | |
| repository = hf_home / "hub" / "models--facebook--dinov2-base" | |
| snapshot = repository / "snapshots" / DINOV2_REVISION | |
| # ``Scorer`` loads by model id. In offline mode Transformers resolves that | |
| # id through refs/main, so merely verifying that the intended snapshot also | |
| # exists in the cache is insufficient: a different cached main ref could be | |
| # loaded while the provenance below claimed DINOV2_REVISION. Fail closed | |
| # unless the ref used by from_pretrained() resolves to the frozen revision. | |
| main_ref = repository / "refs" / "main" | |
| if not main_ref.is_file(): | |
| raise FileNotFoundError(f"DINOv2 main ref missing: {main_ref}") | |
| resolved_revision = main_ref.read_text().strip() | |
| if resolved_revision != DINOV2_REVISION: | |
| raise RuntimeError( | |
| "DINOv2 refs/main mismatch: " | |
| f"expected={DINOV2_REVISION} actual={resolved_revision}" | |
| ) | |
| files = [] | |
| for name, expected_sha in DINOV2_FILES.items(): | |
| path = snapshot / name | |
| if not path.is_file(): | |
| raise FileNotFoundError(f"DINOv2 snapshot file missing: {path}") | |
| actual_sha = file_sha256(path) | |
| if actual_sha != expected_sha: | |
| raise RuntimeError(f"DINOv2 SHA mismatch: {path}") | |
| stat = path.stat() | |
| files.append({ | |
| "name": name, | |
| "size_bytes": stat.st_size, | |
| "sha256": actual_sha, | |
| "mtime_ns": stat.st_mtime_ns, | |
| }) | |
| return { | |
| "model_id": "facebook/dinov2-base", | |
| "revision": DINOV2_REVISION, | |
| "main_ref_path": str(main_ref), | |
| "main_ref_sha256": file_sha256(main_ref), | |
| "files": files, | |
| } | |
| def frozen_calibration_provenance(path: Path, prior_weight: float) -> dict: | |
| """Validate and fingerprint the calibration-only frozen lambda selection.""" | |
| if not path.is_file(): | |
| raise FileNotFoundError(f"calibration selection not found: {path}") | |
| payload = json.loads(path.read_text()) | |
| if not payload.get("passed_integrity_audit"): | |
| raise RuntimeError("calibration selection did not pass its integrity audit") | |
| if payload.get("selection_status") != "selected": | |
| raise RuntimeError("calibration did not select a hybrid lambda") | |
| if payload.get("scene_partition") != "calibration-only": | |
| raise RuntimeError("lambda selection was not calibration-only") | |
| if int(payload.get("n_calibration", -1)) != 218: | |
| raise RuntimeError("lambda selection does not cover 218 calibration episodes") | |
| selected = float(payload.get("selected_prior_weight")) | |
| if not np.isclose(selected, prior_weight, rtol=0.0, atol=1e-12): | |
| raise RuntimeError( | |
| f"validation lambda {prior_weight} differs from frozen lambda {selected}" | |
| ) | |
| renderer = payload.get("renderer_cem") or {} | |
| if renderer.get("sha256") != FROZEN_RENDERER_CEM_SHA256: | |
| raise RuntimeError("calibration selection used an unexpected renderer-CEM baseline") | |
| return { | |
| "path": str(path), | |
| "sha256": file_sha256(path), | |
| "selected_prior_weight": selected, | |
| "selection_status": payload["selection_status"], | |
| "n_calibration": int(payload["n_calibration"]), | |
| "renderer_cem_sha256": renderer["sha256"], | |
| } | |
| def images_from_observation(observation: dict) -> list[Image.Image]: | |
| return list((observation.get("multi_modal_input") or {}).get("<image>", [])) | |
| def image_data_url(image: Image.Image) -> str: | |
| buffer = io.BytesIO() | |
| image.save(buffer, format="PNG") | |
| encoded = base64.b64encode(buffer.getvalue()).decode("ascii") | |
| return f"data:image/png;base64,{encoded}" | |
| def format_message(role: str, text: str, images: list[Image.Image]) -> dict: | |
| """Match VAGEN's OpenAIAdapter placeholder/image interleaving.""" | |
| parts = text.split("<image>") | |
| content = [] | |
| for index, part in enumerate(parts): | |
| if part.strip(): | |
| content.append({"type": "text", "text": part}) | |
| if index < len(parts) - 1 and index < len(images): | |
| content.append({ | |
| "type": "image_url", | |
| "image_url": {"url": image_data_url(images[index])}, | |
| }) | |
| for image in images[max(0, len(parts) - 1):]: | |
| content.append({ | |
| "type": "image_url", | |
| "image_url": {"url": image_data_url(image)}, | |
| }) | |
| return {"role": role, "content": content} | |
| def format_executed_action(action_name: str) -> dict: | |
| """Put the real CEM action in history using the checkpoint's native format.""" | |
| text = f"<action>{action_name}</action>" | |
| return {"role": "assistant", "content": [{"type": "text", "text": text}]} | |
| def parse_vlm_advice(env: InteractiveViewPlanning, reply: str) -> dict: | |
| """Classify a reply with the official parser; camera advice alone biases CEM.""" | |
| valid, parsed = env._parse_action_str(reply, format=env.format) | |
| if not valid: | |
| return { | |
| "parse_valid": False, | |
| "parsed_action_names": [], | |
| "camera_actions": [], | |
| "effective_camera_actions": [], | |
| "answer_advice": False, | |
| "unknown_actions": [], | |
| } | |
| parsed_names = [action.name for action in parsed] | |
| camera_actions = [name for name in parsed_names if name in CAMERA_ACTIONS] | |
| answer_advice = any(name == "answer" for name in parsed_names) | |
| return { | |
| "parse_valid": True, | |
| "parsed_action_names": parsed_names, | |
| "camera_actions": camera_actions, | |
| # The preregistration defines legal answer(...) advice as advisor | |
| # abstention. Even an unusual mixed camera+answer reply must therefore | |
| # fall back to uniform CEM; retain camera_actions above for diagnosis. | |
| "effective_camera_actions": [] if answer_advice else camera_actions, | |
| "answer_advice": answer_advice, | |
| "unknown_actions": [ | |
| name for name in parsed_names if name not in CAMERA_ACTIONS and name != "answer" | |
| ], | |
| } | |
| def action_prior(actions: list[str], horizon: int, weight: float) -> np.ndarray: | |
| """Mixture of uniform CEM sampling and per-horizon VLM one-hot advice.""" | |
| probabilities = np.full((horizon, NA), 1.0 / NA, dtype=np.float64) | |
| for step, action_name in enumerate(actions[:horizon]): | |
| one_hot = np.zeros(NA, dtype=np.float64) | |
| one_hot[ACTION_TO_ID[action_name]] = 1.0 | |
| probabilities[step] = (1.0 - weight) / NA + weight * one_hot | |
| return probabilities | |
| class PriorCEM(CEM): | |
| def __init__(self, *args, **kwargs) -> None: | |
| super().__init__(*args, **kwargs) | |
| self.candidate_render_batches_requested = 0 | |
| self.candidate_views_requested = 0 | |
| self.candidate_views_returned = 0 | |
| async def render(self, scene_id, poses, intrinsics) -> list[Image.Image]: | |
| self.candidate_render_batches_requested += 1 | |
| self.candidate_views_requested += len(poses) | |
| images = await super().render(scene_id, poses, intrinsics) | |
| self.candidate_views_returned += len(images) | |
| if len(images) != len(poses): | |
| raise RuntimeError( | |
| f"renderer returned {len(images)} images for {len(poses)} requested poses" | |
| ) | |
| return images | |
| async def plan( | |
| self, scene_id, pose, intrinsics, target_cls, vm_kwargs, | |
| initial_probabilities: np.ndarray, | |
| ): | |
| if initial_probabilities.shape != (self.H, NA): | |
| raise ValueError("invalid CEM prior shape") | |
| if not np.allclose(initial_probabilities.sum(axis=1), 1.0, atol=1e-10): | |
| raise ValueError("CEM prior rows do not sum to one") | |
| logits = np.log(np.maximum(initial_probabilities, 1e-12)) | |
| best_score, best_first, best_pose = -1e9, 0, pose | |
| score_batches, first_action_batches = [], [] | |
| for _ in range(self.opt): | |
| probabilities = np.exp(logits - logits.max(1, keepdims=True)) | |
| probabilities /= probabilities.sum(1, keepdims=True) | |
| sequences = np.stack([ | |
| [self.rng.choice(NA, p=probabilities[h]) for h in range(self.H)] | |
| for _ in range(self.N) | |
| ]) | |
| final_poses = [roll(pose, sequence, vm_kwargs) for sequence in sequences] | |
| images = await self.render(scene_id, final_poses, intrinsics) | |
| scores = self.scorer.cls(images) @ target_cls | |
| scores = np.asarray(scores, dtype=np.float64) | |
| if scores.shape != (self.N,): | |
| raise RuntimeError(f"invalid scorer output shape: {scores.shape}") | |
| if not np.isfinite(scores).all(): | |
| raise RuntimeError("scorer returned non-finite candidate scores") | |
| score_batches.append(np.asarray(scores, dtype=np.float64)) | |
| first_action_batches.append(np.asarray(sequences[:, 0], dtype=np.int64)) | |
| best_index = int(np.argmax(scores)) | |
| if scores[best_index] > best_score: | |
| best_score = float(scores[best_index]) | |
| best_first = int(sequences[best_index][0]) | |
| best_pose = final_poses[best_index] | |
| elites = sequences[np.argsort(-scores)[: self.K]] | |
| logits = np.zeros((self.H, NA), dtype=np.float64) | |
| for horizon_step in range(self.H): | |
| counts = np.bincount(elites[:, horizon_step], minlength=NA).astype(float) | |
| logits[horizon_step] = np.log(counts + 1e-3) | |
| all_scores = np.concatenate(score_batches) | |
| all_first = np.concatenate(first_action_batches) | |
| ordered = np.sort(all_scores) | |
| refit_probability = np.exp(logits[0] - logits[0].max()) | |
| refit_probability /= refit_probability.sum() | |
| per_action_max, per_action_mean = [], [] | |
| for action_id in range(NA): | |
| selected = all_scores[all_first == action_id] | |
| per_action_max.append(float(selected.max()) if len(selected) else None) | |
| per_action_mean.append(float(selected.mean()) if len(selected) else None) | |
| diagnostics = { | |
| "best_score": float(best_score), | |
| "score_mean": float(all_scores.mean()), | |
| "score_std": float(all_scores.std()), | |
| "score_range": float(all_scores.max() - all_scores.min()), | |
| "top2_margin": float(ordered[-1] - ordered[-2]), | |
| "first_action_count": np.bincount(all_first, minlength=NA).astype(int).tolist(), | |
| "first_action_max": per_action_max, | |
| "first_action_mean": per_action_mean, | |
| "input_first_action_probability": initial_probabilities[0].tolist(), | |
| "refit_first_action_probability": refit_probability.tolist(), | |
| "refit_first_action_entropy": float( | |
| -(refit_probability * np.log(np.maximum(refit_probability, 1e-12))).sum() | |
| ), | |
| } | |
| return NAMES[KEYS[best_first]], best_pose, best_score, diagnostics | |
| async def get_vlm_advice( | |
| client: AsyncOpenAI, model: str, messages: list[dict], max_tokens: int | |
| ) -> tuple[str, dict]: | |
| started = time.perf_counter() | |
| last_error = None | |
| for attempt in range(6): | |
| try: | |
| response = await client.chat.completions.create( | |
| model=model, | |
| messages=messages, | |
| temperature=0.0, | |
| top_p=0.95, | |
| max_tokens=max_tokens, | |
| ) | |
| return response.choices[0].message.content or "", { | |
| "attempts": attempt + 1, | |
| "latency_seconds": float(time.perf_counter() - started), | |
| } | |
| except Exception as error: # provider-specific hierarchy varies by version | |
| last_error = error | |
| status_code = getattr(error, "status_code", None) | |
| retryable = ( | |
| type(error).__name__ in { | |
| "APIConnectionError", "APITimeoutError", "RateLimitError", | |
| "InternalServerError", | |
| } | |
| or status_code in {408, 409, 429} | |
| or (isinstance(status_code, int) and status_code >= 500) | |
| ) | |
| if attempt == 5 or not retryable: | |
| break | |
| await asyncio.sleep(min(0.5 * (2 ** attempt), 8.0)) | |
| raise RuntimeError(f"VLM advice failed after {attempt + 1} attempt(s): {last_error!r}") | |
| def selected_scenes(partition: str) -> set[str] | None: | |
| if partition == "calibration": | |
| return CALIBRATION_SCENES | |
| if partition == "validation": | |
| return VALIDATION_SCENES | |
| return None | |
| async def main() -> None: | |
| parser = argparse.ArgumentParser() | |
| parser.add_argument("--renderer_url", required=True) | |
| parser.add_argument("--vlm_url", required=True, help="OpenAI-compatible /v1 base URL") | |
| parser.add_argument("--model", required=True) | |
| parser.add_argument("--prior_weight", type=float, required=True) | |
| parser.add_argument("--partition", choices=("test",), default="test") | |
| parser.add_argument("--H", type=int, default=5) | |
| parser.add_argument("--N", type=int, default=100) | |
| parser.add_argument("--K", type=int, default=10) | |
| parser.add_argument("--opt", type=int, default=3) | |
| parser.add_argument("--max_turns", type=int, default=10) | |
| parser.add_argument("--render_size", type=int, default=512) | |
| parser.add_argument("--seed", type=int, default=20260730) | |
| parser.add_argument("--start", type=int, default=1) | |
| parser.add_argument("--end", type=int, default=531) # exclusive; seeds are 1..530 | |
| parser.add_argument("--dataset", required=True) | |
| parser.add_argument("--max_tokens", type=int, default=2048) | |
| parser.add_argument("--scorer_device", default="cuda:0") | |
| parser.add_argument("--sglang_tp", type=int, required=True) | |
| parser.add_argument("--sglang_mem_fraction", type=float, required=True) | |
| parser.add_argument("--sglang_random_seed", type=int, required=True) | |
| parser.add_argument( | |
| "--calibration_selection", | |
| help="frozen calibration analysis; required and enforced for validation", | |
| ) | |
| parser.add_argument("--output", required=True) | |
| args = parser.parse_args() | |
| if not (0.0 < args.prior_weight <= 0.5): | |
| raise ValueError("prior_weight must lie in (0, 0.5] for the CEM-primary arm") | |
| if args.H <= 0 or args.N < 2 or not (1 <= args.K <= args.N) or args.opt <= 0: | |
| raise ValueError("require H>0, N>=2, 1<=K<=N, and opt>0") | |
| if args.max_turns < 2 or args.render_size <= 0 or args.max_tokens <= 0: | |
| raise ValueError("require max_turns>=2, render_size>0, and max_tokens>0") | |
| if args.start >= args.end: | |
| raise ValueError("--start must be smaller than --end") | |
| if args.sglang_tp <= 0 or not (0.0 < args.sglang_mem_fraction < 1.0): | |
| raise ValueError("invalid SGLang resource settings") | |
| if args.sglang_random_seed < 0: | |
| raise ValueError("SGLang random seed must be non-negative") | |
| if args.calibration_selection: | |
| raise ValueError("test extension does not accept calibration selection") | |
| dataset_path = Path(args.dataset).resolve() | |
| if not dataset_path.is_file(): | |
| raise FileNotFoundError(dataset_path) | |
| dataset_rows = [json.loads(line) for line in dataset_path.read_text().splitlines() if line] | |
| if not dataset_rows: | |
| raise RuntimeError("test dataset is empty") | |
| scene_filter = None | |
| expected_rows = { | |
| seed: dataset_rows[seed % len(dataset_rows)] | |
| for seed in range(args.start, args.end) | |
| if scene_filter is None | |
| or dataset_rows[seed % len(dataset_rows)]["scene_id"] in scene_filter | |
| } | |
| expected_seeds = set(expected_rows) | |
| model_path = Path(args.model).resolve() | |
| model_provenance = checkpoint_provenance(model_path) | |
| scorer_provenance = dinov2_provenance() | |
| calibration_selection = None | |
| partition_scenes = sorted({row["scene_id"] for row in dataset_rows}) | |
| run_config = { | |
| "protocol": "official_submit_cem_primary_vlm_soft_prior_v2", | |
| "split": "test", | |
| "partition": args.partition, | |
| "start": args.start, | |
| "end_exclusive": args.end, | |
| "expected_n_episodes": len(expected_seeds), | |
| "prior_weight": args.prior_weight, | |
| "history_policy": ( | |
| "official concatenated observations plus synthetic action-only history " | |
| "containing exactly the action CEM actually executed" | |
| ), | |
| "executed_action_template": "<action>{cem_action}</action>", | |
| "vlm_input": ( | |
| "official system prompt and full real-observation history; " | |
| "no candidate lookahead images" | |
| ), | |
| "advice_parse_policy": ( | |
| "official eval_mode parser; legal camera subsequence biases matching horizons; " | |
| "any answer/empty/invalid advice falls back to uniform" | |
| ), | |
| "generation": { | |
| "temperature": 0.0, | |
| "top_p": 0.95, | |
| "max_tokens": args.max_tokens, | |
| }, | |
| "model": model_provenance, | |
| "scorer_model": scorer_provenance, | |
| "dataset": { | |
| "path": str(dataset_path), | |
| "sha256": file_sha256(dataset_path), | |
| "n_rows": len(dataset_rows), | |
| }, | |
| "scene_split_sha256": file_sha256(dataset_path), | |
| "calibration_selection": calibration_selection, | |
| "partition_scenes": partition_scenes, | |
| "calibration_scenes": [], | |
| "validation_scenes": [], | |
| "split_source_sha256": file_sha256(Path(__file__)), | |
| "planner": { | |
| "H": args.H, "N": args.N, "K": args.K, "opt_steps": args.opt, | |
| "render_size": args.render_size, "cost": "dinov2_cls_cosine", | |
| "action_names": [NAMES[key] for key in KEYS], | |
| "scorer_device": args.scorer_device, | |
| "query_unit": "candidate terminal-view instances requested from the renderer", | |
| }, | |
| "server": { | |
| "sglang_tp": args.sglang_tp, | |
| "sglang_mem_fraction_static": args.sglang_mem_fraction, | |
| "random_seed": args.sglang_random_seed, | |
| "attention_backend": "triton", | |
| "mm_attention_backend": "triton_attn", | |
| }, | |
| "package_versions": package_versions(), | |
| "seed": args.seed, | |
| "max_turns": args.max_turns, | |
| "implementation_sha256": file_sha256(Path(__file__)), | |
| "base_cem_sha256": file_sha256(ROOT / "cem_official_harness.py"), | |
| } | |
| output_path = Path(args.output) | |
| output_path.parent.mkdir(parents=True, exist_ok=True) | |
| completed: dict[int, dict] = {} | |
| failures: list[dict] = [] | |
| if output_path.exists(): | |
| previous = json.loads(output_path.read_text()) | |
| if previous.get("run_config") != run_config: | |
| raise RuntimeError("refusing to resume hybrid output with a different run_config") | |
| previous_episodes = previous.get("episodes", []) | |
| previous_seeds = [int(episode["seed"]) for episode in previous_episodes] | |
| if len(previous_seeds) != len(set(previous_seeds)): | |
| raise RuntimeError("resume output contains duplicate seeds") | |
| for episode in previous_episodes: | |
| seed = int(episode["seed"]) | |
| if seed not in expected_rows: | |
| raise RuntimeError(f"resume output contains unexpected seed {seed}") | |
| expected = expected_rows[seed] | |
| static = (episode.get("scene_id"), episode.get("sample_id"), episode.get("gt_len")) | |
| expected_static = ( | |
| expected["scene_id"], expected["sample_id"], len(expected["gt_action_seq"]) | |
| ) | |
| if static != expected_static: | |
| raise RuntimeError(f"resume metadata mismatch for seed {seed}") | |
| completed[seed] = episode | |
| failures = list(previous.get("failure_history", [])) | |
| episodes = sorted(completed.values(), key=lambda episode: int(episode["seed"])) | |
| def write_partial() -> None: | |
| atomic_json(output_path, { | |
| "partial": True, | |
| "run_config": run_config, | |
| "expected_seeds": sorted(expected_seeds), | |
| "failure_history": failures, | |
| "episodes": episodes, | |
| }) | |
| vlm_client = AsyncOpenAI(api_key="EMPTY", base_url=args.vlm_url, timeout=300.0) | |
| renderer_client = __import__( | |
| "view_suite.service_http.async_client", fromlist=["AsyncUnifiedClient"] | |
| ).AsyncUnifiedClient(args.renderer_url) | |
| try: | |
| scorer = Scorer(device=args.scorer_device) | |
| for seed in sorted(expected_seeds): | |
| if seed in completed: | |
| continue | |
| env = InteractiveViewPlanning(test_env_config(dataset_path, args.max_turns)) | |
| episode_record = None | |
| try: | |
| observation, reset_info = await env.reset(seed) | |
| row = env.current_item | |
| if row is None: | |
| raise RuntimeError("official environment did not expose current_item") | |
| expected = expected_rows[seed] | |
| actual_static = (row["scene_id"], row["sample_id"], len(row["gt_action_seq"])) | |
| expected_static = ( | |
| expected["scene_id"], expected["sample_id"], len(expected["gt_action_seq"]) | |
| ) | |
| if actual_static != expected_static: | |
| raise RuntimeError(f"official seed mapping mismatch for seed {seed}") | |
| reset_images = images_from_observation(observation) | |
| if len(reset_images) != 3: | |
| raise RuntimeError( | |
| f"official reset must contain target/init/topdown images, got {len(reset_images)}" | |
| ) | |
| if env.camera_intrinsics is None: | |
| raise RuntimeError("official environment has no active camera intrinsics") | |
| if env.target_view is None: | |
| raise RuntimeError("official environment has no target_view") | |
| system_observation = await env.system_prompt() | |
| messages = [ | |
| format_message( | |
| "system", system_observation.get("obs_str", ""), | |
| images_from_observation(system_observation), | |
| ), | |
| format_message("user", observation.get("obs_str", ""), reset_images), | |
| ] | |
| target_cls = scorer.cls([reset_images[0].convert("RGB")])[0] | |
| if target_cls.ndim != 1 or not np.isfinite(target_cls).all(): | |
| raise RuntimeError("invalid target DINO feature") | |
| intrinsics = np.asarray(env.camera_intrinsics, np.float32).tolist() | |
| target_pose = np.asarray(env.target_view["c2w_extrinsic"], dtype=np.float64) | |
| sample_dir = (dataset_path.parent / row["image_detail"]["init_view"]["path"]).parent | |
| metadata = json.loads((sample_dir / "meta.json").read_text()) | |
| cem = PriorCEM( | |
| renderer_client, scorer, args.H, args.N, args.K, args.opt, | |
| args.render_size, args.seed + seed, | |
| ) | |
| position_threshold = float(reset_info["pos_threshold_m"]) | |
| angle_threshold = float(reset_info["ang_threshold_deg"]) | |
| initial_pose = np.asarray( | |
| env.view_engine.get_pose(mode="c2w"), dtype=np.float64 | |
| ) | |
| def errors(pose: np.ndarray) -> dict: | |
| position = pose_error(pose, target_pose) | |
| angle = rotation_error_deg(pose, target_pose) | |
| return { | |
| "pos_err_m": position, | |
| "ang_err_deg": angle, | |
| "normalized_max_error": max( | |
| position / max(position_threshold, 1e-12), | |
| angle / max(angle_threshold, 1e-12), | |
| ), | |
| } | |
| initial_errors = errors(initial_pose) | |
| best_visited_errors = dict(initial_errors) | |
| best_pose, best_score = None, -1e9 | |
| action_trace, turn_records = [], [] | |
| for turn in range(1, args.max_turns): | |
| reply, request_diagnostics = await get_vlm_advice( | |
| vlm_client, args.model, messages, args.max_tokens | |
| ) | |
| advice = parse_vlm_advice(env, reply) | |
| prior = action_prior( | |
| advice["effective_camera_actions"], args.H, args.prior_weight | |
| ) | |
| current_pose = np.asarray( | |
| env.view_engine.get_pose(mode="c2w"), dtype=np.float64 | |
| ) | |
| action_name, candidate_pose, candidate_score, cem_diagnostics = ( | |
| await cem.plan( | |
| row["scene_id"], current_pose, intrinsics, target_cls, | |
| metadata["vm_kwargs"], prior, | |
| ) | |
| ) | |
| if candidate_score > best_score: | |
| best_score, best_pose = candidate_score, candidate_pose | |
| next_observation, reward, done, step_info = await env.step( | |
| f"<action>{action_name}</action>" | |
| ) | |
| step_info = dict(step_info or {}) | |
| if step_info.get("error"): | |
| raise RuntimeError( | |
| f"official env rejected CEM action {action_name}: {step_info['error']}" | |
| ) | |
| if done: | |
| raise RuntimeError("official submit-mode env terminated before answer turn") | |
| actual_pose = np.asarray( | |
| env.view_engine.get_pose(mode="c2w"), dtype=np.float64 | |
| ) | |
| expected_pose = roll( | |
| current_pose, [ACTION_TO_ID[action_name]], metadata["vm_kwargs"] | |
| ) | |
| pose_consistency_max_abs = float(np.max(np.abs(actual_pose - expected_pose))) | |
| if pose_consistency_max_abs > 1e-6: | |
| raise RuntimeError( | |
| "executed pose disagrees with audited ViewManipulator rollout: " | |
| f"max_abs={pose_consistency_max_abs}" | |
| ) | |
| visited_errors = errors(actual_pose) | |
| if ( | |
| visited_errors["normalized_max_error"] | |
| < best_visited_errors["normalized_max_error"] | |
| ): | |
| best_visited_errors = dict(visited_errors) | |
| action_trace.append(action_name) | |
| turn_records.append({ | |
| "turn": turn, | |
| "vlm_reply": reply, | |
| "vlm_request": request_diagnostics, | |
| "vlm_advice": advice, | |
| "cem_action": action_name, | |
| "cem_action_id": ACTION_TO_ID[action_name], | |
| "current_pose_c2w": current_pose.tolist(), | |
| "candidate_best_pose_c2w": np.asarray(candidate_pose).tolist(), | |
| "actual_pose_c2w": actual_pose.tolist(), | |
| "pose_consistency_max_abs": pose_consistency_max_abs, | |
| "visited_errors": visited_errors, | |
| "reward": float(reward), | |
| "done": bool(done), | |
| "step_info": step_info, | |
| "cem": cem_diagnostics, | |
| }) | |
| messages.append(format_executed_action(action_name)) | |
| messages.append(format_message( | |
| "user", next_observation.get("obs_str", ""), | |
| images_from_observation(next_observation), | |
| )) | |
| if best_pose is None or not np.isfinite(best_score): | |
| raise RuntimeError("CEM produced no finite pose to submit") | |
| translation = best_pose[:3, 3] | |
| euler = Rotation.from_matrix(best_pose[:3, :3]).as_euler( | |
| "xyz", degrees=True | |
| ) | |
| submitted = [float(value) for value in (*translation, *euler)] | |
| answer = "answer({:.6f},{:.6f},{:.6f},{:.6f},{:.6f},{:.6f})".format( | |
| *submitted | |
| ) | |
| _, submit_reward, submit_done, submit_info = await env.step( | |
| f"<action>{answer}</action>" | |
| ) | |
| submit_info = dict(submit_info or {}) | |
| required_submit_metrics = { | |
| "pos_err_m", "ang_err_deg", "pos_threshold_m", "ang_threshold_deg" | |
| } | |
| if submit_info.get("error") or not submit_done: | |
| raise RuntimeError( | |
| f"official answer protocol failed: done={submit_done} info={submit_info}" | |
| ) | |
| if not required_submit_metrics <= set(submit_info): | |
| raise RuntimeError("official answer omitted required pose metrics") | |
| success = bool(submit_info.get("success")) | |
| submitted_metrics = { | |
| key: float(submit_info[key]) for key in sorted(required_submit_metrics) | |
| } | |
| expected_batches = (args.max_turns - 1) * args.opt | |
| expected_candidate_views = expected_batches * args.N | |
| if cem.candidate_render_batches_requested != expected_batches: | |
| raise RuntimeError("unexpected number of logical CEM render batches") | |
| if cem.candidate_views_requested != expected_candidate_views: | |
| raise RuntimeError("unexpected number of CEM candidate views requested") | |
| if cem.candidate_views_returned != expected_candidate_views: | |
| raise RuntimeError("renderer did not return every requested candidate view") | |
| renderer_usage = { | |
| "cem_logical_render_batches": cem.candidate_render_batches_requested, | |
| "cem_candidate_view_instances_requested": cem.candidate_views_requested, | |
| "cem_candidate_view_instances_returned": cem.candidate_views_returned, | |
| "official_executed_action_render_views": len(action_trace), | |
| "total_logical_renderer_requests": ( | |
| cem.candidate_render_batches_requested + len(action_trace) | |
| ), | |
| "total_rendered_view_instances": ( | |
| cem.candidate_views_returned + len(action_trace) | |
| ), | |
| } | |
| episode_record = { | |
| "seed": seed, | |
| "scene_id": row["scene_id"], | |
| "sample_id": row["sample_id"], | |
| "gt_len": len(row["gt_action_seq"]), | |
| "success": success, | |
| "turns": args.max_turns, | |
| "actions": action_trace, | |
| "vlm_parse_invalid_turns": int(sum( | |
| not record["vlm_advice"]["parse_valid"] for record in turn_records | |
| )), | |
| "vlm_answer_advice_turns": int(sum( | |
| record["vlm_advice"]["answer_advice"] for record in turn_records | |
| )), | |
| "vlm_no_camera_advice_turns": int(sum( | |
| not record["vlm_advice"]["camera_actions"] for record in turn_records | |
| )), | |
| "vlm_uniform_prior_turns": int(sum( | |
| not record["vlm_advice"]["effective_camera_actions"] | |
| for record in turn_records | |
| )), | |
| "vlm_request_attempts": int(sum( | |
| record["vlm_request"]["attempts"] for record in turn_records | |
| )), | |
| "initial_errors": initial_errors, | |
| "best_visited_errors": best_visited_errors, | |
| "thresholds": { | |
| "pos_m": position_threshold, | |
| "angle_deg": angle_threshold, | |
| }, | |
| "best_imagined_score": float(best_score), | |
| "submitted": submitted, | |
| "submitted_metrics": submitted_metrics, | |
| "submit_reward": float(submit_reward), | |
| "renderer_usage": renderer_usage, | |
| "turn_records": turn_records, | |
| } | |
| except Exception as error: | |
| failures.append({ | |
| "seed": seed, | |
| "error_type": type(error).__name__, | |
| "error": repr(error), | |
| }) | |
| write_partial() | |
| raise | |
| finally: | |
| await env.close() | |
| if episode_record is None: | |
| raise RuntimeError(f"episode {seed} did not produce a record") | |
| episodes.append(episode_record) | |
| episodes.sort(key=lambda episode: int(episode["seed"])) | |
| completed[seed] = episode_record | |
| write_partial() | |
| rate = float(np.mean([episode["success"] for episode in episodes])) | |
| print( | |
| f"{len(episodes)}/{len(expected_seeds)} episodes " | |
| f"latest_seed={seed} success_rate={rate:.4f}", | |
| flush=True, | |
| ) | |
| finally: | |
| try: | |
| await renderer_client.aclose() | |
| finally: | |
| await vlm_client.close() | |
| actual_seeds = {int(episode["seed"]) for episode in episodes} | |
| if actual_seeds != expected_seeds: | |
| missing = sorted(expected_seeds - actual_seeds) | |
| extra = sorted(actual_seeds - expected_seeds) | |
| raise RuntimeError(f"final coverage mismatch: missing={missing}, extra={extra}") | |
| rate = float(np.mean([episode["success"] for episode in episodes])) if episodes else 0.0 | |
| action_counts = Counter(action for episode in episodes for action in episode["actions"]) | |
| renderer_totals = { | |
| key: int(sum(episode["renderer_usage"][key] for episode in episodes)) | |
| for key in ( | |
| "cem_logical_render_batches", "cem_candidate_view_instances_requested", | |
| "cem_candidate_view_instances_returned", "official_executed_action_render_views", | |
| "total_logical_renderer_requests", "total_rendered_view_instances", | |
| ) | |
| } | |
| atomic_json(output_path, { | |
| "partial": False, | |
| "passed_coverage_audit": True, | |
| "run_config": run_config, | |
| "expected_seeds": sorted(expected_seeds), | |
| "n_episodes": len(episodes), | |
| "success_rate": rate, | |
| "action_count": dict(sorted(action_counts.items())), | |
| "renderer_totals": renderer_totals, | |
| "failure_history": failures, | |
| "episodes": episodes, | |
| }) | |
| print(f"CEM_VLM_HYBRID_DONE n={len(episodes)} success_rate={rate:.4f}") | |
| if __name__ == "__main__": | |
| asyncio.run(main()) | |