| |
| """Command-line wrapper for tutorials/5.run_evaluation.ipynb.""" |
|
|
| from __future__ import annotations |
|
|
| import argparse |
| import json |
| import os |
| import sys |
| from importlib import import_module |
| from pathlib import Path |
|
|
|
|
| def _resolve_path(path_like: str) -> str: |
| return str(Path(path_like).expanduser().resolve()) |
|
|
|
|
| def _resolve_episode_config_path( |
| path_like: str, project_root: Path, vlabench_root: Path |
| ) -> str: |
| """Resolve custom episode-config arguments. |
| |
| New downstream tasks may ship configs outside of this repo structure. |
| To keep the CLI flexible, we attempt a few reasonable fallbacks: |
| 1) interpret the argument relative to the current working directory; |
| 2) interpret it relative to the declared project root; |
| 3) interpret it relative to ``VLABENCH_ROOT``; |
| 4) if it looks like a track name (e.g. ``chem01``), look under |
| ``<VLABENCH_ROOT>/configs/evaluation/tracks`` (with and without |
| a ``.json`` suffix). |
| """ |
|
|
| project_root = project_root.expanduser().resolve() |
| vlabench_root = vlabench_root.expanduser().resolve() |
| provided = Path(path_like).expanduser() |
|
|
| candidates: list[Path] = [] |
|
|
| def _register(path: Path) -> None: |
| if path in candidates: |
| return |
| candidates.append(path) |
|
|
| if provided.is_absolute(): |
| _register(provided) |
| else: |
| _register(Path.cwd() / provided) |
| _register(project_root / provided) |
| _register(vlabench_root / provided) |
|
|
| track_dir = vlabench_root / "configs" / "evaluation" / "tracks" |
| track_names: list[str] = [] |
| base_name = provided.name |
| if provided.suffix: |
| track_names.append(base_name) |
| else: |
| track_names.extend([base_name, f"{base_name}.json"]) |
| for name in track_names: |
| _register(track_dir / name) |
|
|
| for candidate in candidates: |
| if candidate.exists(): |
| return str(candidate.resolve()) |
|
|
| searched = "\n - ".join(str(path) for path in candidates) |
| raise FileNotFoundError( |
| f"Could not find episode config '{path_like}'. Tried:\n - {searched}" |
| ) |
|
|
|
|
| def _prepare_environment(project_root: str, vlabench_root: str | None, mujoco_gl: str | None) -> None: |
| project_root_path = Path(project_root).expanduser().resolve() |
| vlabench_root_path = ( |
| project_root_path / "VLABench" |
| if vlabench_root is None |
| else Path(vlabench_root).expanduser().resolve() |
| ) |
|
|
| if not project_root_path.exists(): |
| raise FileNotFoundError(f"project_root does not exist: {project_root_path}") |
| if not vlabench_root_path.exists(): |
| raise FileNotFoundError(f"VLABENCH_ROOT does not exist: {vlabench_root_path}") |
|
|
| if str(project_root_path) not in sys.path: |
| sys.path.append(str(project_root_path)) |
|
|
| src_root = project_root_path / "src" |
| if src_root.exists(): |
| for path in [src_root, *src_root.iterdir()]: |
| if path.is_dir(): |
| path_str = str(path) |
| if path_str not in sys.path: |
| sys.path.append(path_str) |
|
|
| os.environ.setdefault("VLABENCH_ROOT", str(vlabench_root_path)) |
| if mujoco_gl: |
| os.environ["MUJOCO_GL"] = mujoco_gl |
|
|
|
|
| def _load_json_arg(value: str | None) -> dict: |
| if not value: |
| return {} |
| candidate = Path(value) |
| payload = candidate.read_text() if candidate.exists() else value |
| return json.loads(payload) |
|
|
|
|
| def _normalize_task_names(task_args: list[str]) -> list[str]: |
| normalized = [] |
| for name in task_args: |
| normalized.append(name.split("/")[-1]) |
| return normalized |
|
|
|
|
| def _run_policy_eval(args: argparse.Namespace) -> None: |
| from VLABench.evaluation.evaluator import Evaluator |
| from VLABench.evaluation.model.policy.base import RandomPolicy |
|
|
| project_root = Path(args.project_root).expanduser().resolve() |
| env_vlabench_root = os.environ.get("VLABENCH_ROOT") |
| vlabench_root = ( |
| Path(env_vlabench_root).expanduser().resolve() |
| if env_vlabench_root |
| else project_root / "VLABench" |
| ) |
|
|
| tasks = _normalize_task_names(args.tasks) |
| save_dir = _resolve_path(args.save_dir) |
| episode_config = ( |
| _resolve_episode_config_path(args.episode_config, project_root, vlabench_root) |
| if args.episode_config |
| else None |
| ) |
|
|
| policy_name = args.policy.lower() |
| if policy_name == "random": |
| policy = RandomPolicy(model=None) |
| elif policy_name == "openvla": |
| from VLABench.evaluation.model.policy.openvla import OpenVLA |
|
|
| if not args.model_ckpt: |
| raise ValueError("--model-ckpt is required for OpenVLA evaluation") |
| if not args.lora_ckpt: |
| raise ValueError("--lora-ckpt is required for OpenVLA evaluation") |
| norm_config = args.norm_config or os.path.join( |
| os.environ["VLABENCH_ROOT"], "configs", "model", "openvla_config.json" |
| ) |
| policy = OpenVLA( |
| model_ckpt=_resolve_path(args.model_ckpt), |
| lora_ckpt=_resolve_path(args.lora_ckpt), |
| norm_config_file=_resolve_path(norm_config), |
| device=args.device, |
| debug_actions=args.debug_actions, |
| ) |
| elif policy_name == "nora": |
| from VLABench.evaluation.model.policy.nora import NoraPolicy |
|
|
| if not args.model_ckpt: |
| raise ValueError("--model-ckpt is required for Nora evaluation") |
| policy = NoraPolicy( |
| model_ckpt=_resolve_path(args.model_ckpt), |
| device=args.device, |
| time_horizon=max(1, args.nora_time_horizon), |
| debug_tokens=getattr(args, "debug_tokens", False), |
| camera_index=args.nora_camera_index, |
| action_mode=args.nora_action_mode, |
| normalize_gripper=not args.nora_skip_gripper_normalize, |
| binarize_gripper=not args.nora_no_gripper_binarize, |
| invert_gripper=args.nora_invert_gripper, |
| gripper_threshold=args.nora_gripper_threshold, |
| lerobot_dataset=args.nora_lerobot_dataset, |
| ) |
| else: |
| raise ValueError(f"Unsupported policy: {args.policy}") |
|
|
| evaluator = Evaluator( |
| tasks=tasks, |
| n_episodes=args.n_episodes, |
| episode_config=episode_config, |
| max_substeps=args.max_substeps, |
| save_dir=save_dir, |
| visulization=args.visualize, |
| eval_unseen=args.eval_unseen, |
| unnorm_key=args.unnorm_key, |
| intention_score_threshold=args.intention_threshold, |
| ) |
|
|
| metrics = evaluator.evaluate(policy) |
| print(json.dumps(metrics, indent=2, ensure_ascii=False)) |
|
|
|
|
| def _run_vlm_eval(args: argparse.Namespace) -> None: |
| from VLABench.evaluation.evaluator import VLMEvaluator |
|
|
| vlm_module = import_module("VLABench.evaluation.model.vlm") |
| vlm_cls = getattr(vlm_module, args.vlm_name, None) |
| if vlm_cls is None: |
| raise ValueError( |
| f"Unknown VLM '{args.vlm_name}'. Check VLABench.evaluation.model.vlm for valid class names." |
| ) |
|
|
| init_kwargs = _load_json_arg(args.vlm_init) |
| vlm = vlm_cls(**init_kwargs) |
|
|
| evaluator = VLMEvaluator( |
| tasks=args.vlm_tasks, |
| n_episodes=args.n_episodes, |
| data_path=_resolve_path(args.data_path), |
| save_path=_resolve_path(args.save_path), |
| language=args.language, |
| ) |
|
|
| evaluator.evaluate( |
| vlm, |
| task_list=args.vlm_tasks, |
| few_shot_num=args.few_shot_num, |
| with_CoT=args.with_cot, |
| eval_dim=args.eval_dim, |
| ) |
| scores = evaluator.get_final_score_dict( |
| vlm_name=vlm.name, |
| few_shot_num=args.few_shot_num, |
| with_CoT=args.with_cot, |
| ) |
| if scores is not None: |
| print(json.dumps(scores, indent=2, ensure_ascii=False)) |
|
|
|
|
| def build_parser() -> argparse.ArgumentParser: |
| parser = argparse.ArgumentParser(description="Run VLABench policy or VLM evaluations from CLI") |
| parser.add_argument( |
| "--project-root", |
| default=str(Path(__file__).resolve().parents[1]), |
| help="Repository root (default: %(default)s)", |
| ) |
| parser.add_argument( |
| "--vlabench-root", |
| default=None, |
| help="Path to importable VLABench package (default: <project-root>/VLABench)", |
| ) |
| parser.add_argument( |
| "--mujoco-gl", |
| default=None, |
| help="Override MUJOCO_GL (set egl for headless)", |
| ) |
|
|
| subparsers = parser.add_subparsers(dest="command", required=True) |
|
|
| policy_parser = subparsers.add_parser("policy", help="Evaluate action policies (VLA)") |
| policy_parser.add_argument("--tasks", nargs="+", required=True, help="Task names or task_series/task_name") |
| policy_parser.add_argument("--n-episodes", type=int, default=2, help="Episodes per task") |
| policy_parser.add_argument("--max-substeps", type=int, default=10, help="Env substeps per action") |
| policy_parser.add_argument( |
| "--save-dir", |
| default=str(Path("./logs/policy_eval")), |
| help="Directory for evaluator outputs", |
| ) |
| policy_parser.add_argument( |
| "--policy", |
| default="random", |
| choices=["random", "openvla", "nora"], |
| help="Policy backend", |
| ) |
| policy_parser.add_argument("--model-ckpt", default=None, help="OpenVLA base checkpoint path") |
| policy_parser.add_argument("--lora-ckpt", default=None, help="OpenVLA LoRA checkpoint path") |
| policy_parser.add_argument("--norm-config", default=None, help="Optional OpenVLA normalization config") |
| policy_parser.add_argument("--device", default="cuda", help="Device for OpenVLA") |
| policy_parser.add_argument( |
| "--debug-actions", |
| action="store_true", |
| help="Enable verbose OpenVLA action debug logs (norm stats + per-step deltas)", |
| ) |
| policy_parser.add_argument("--episode-config", default=None, help="Episode config JSON path") |
| policy_parser.add_argument("--visualize", action="store_true", help="Store rollout videos") |
| policy_parser.add_argument("--eval-unseen", action="store_true", help="Use unseen-category flag") |
| policy_parser.add_argument("--unnorm-key", default="primitive", help="Normalization key for policies") |
| policy_parser.add_argument( |
| "--intention-threshold", |
| type=float, |
| default=0.1, |
| help="Intention score threshold", |
| ) |
| policy_parser.add_argument( |
| "--nora-time-horizon", |
| type=int, |
| default=1, |
| help="Nora action horizon / replan steps", |
| ) |
| policy_parser.add_argument( |
| "--nora-camera-index", |
| type=int, |
| default=2, |
| help="Camera index fed to Nora (default front view)", |
| ) |
| policy_parser.add_argument( |
| "--nora-action-mode", |
| choices=["delta", "absolute"], |
| default="delta", |
| help="Interpret Nora outputs as delta or absolute poses", |
| ) |
| policy_parser.add_argument( |
| "--nora-skip-gripper-normalize", |
| action="store_true", |
| help="Skip [0,1]->[-1,1] gripper normalization", |
| ) |
| policy_parser.add_argument( |
| "--nora-no-gripper-binarize", |
| action="store_true", |
| help="Keep Nora gripper logits continuous", |
| ) |
| policy_parser.add_argument( |
| "--nora-invert-gripper", |
| action="store_true", |
| help="Flip Nora gripper sign after normalization", |
| ) |
| policy_parser.add_argument( |
| "--nora-gripper-threshold", |
| type=float, |
| default=0.1, |
| help="Threshold to decide open/close state", |
| ) |
| policy_parser.add_argument( |
| "--nora-lerobot-dataset", |
| default=None, |
| help="Optional Lerobot dataset name for Unnormalize", |
| ) |
| policy_parser.add_argument( |
| "--debug-tokens", |
| action="store_true", |
| help="(Nora) Print decoded action tokens for debugging", |
| ) |
|
|
| repo_root = Path(__file__).resolve().parents[1] |
| vlm_parser = subparsers.add_parser("vlm", help="Evaluate vision-language models") |
| vlm_parser.add_argument( |
| "--vlm-name", |
| required=True, |
| help="Class exported by VLABench.evaluation.model.vlm (e.g. GPT_4v, Qwen2_VL)", |
| ) |
| vlm_parser.add_argument( |
| "--vlm-init", |
| default=None, |
| help="JSON string or file providing constructor kwargs (API keys, etc.)", |
| ) |
| vlm_parser.add_argument( |
| "--vlm-tasks", |
| nargs="+", |
| required=True, |
| help="Tasks in <task_series>/<task_name> format", |
| ) |
| vlm_parser.add_argument("--few-shot-num", type=int, default=0, help="Few-shot example count") |
| vlm_parser.add_argument("--with-cot", action="store_true", help="Enable chain-of-thought prompting") |
| vlm_parser.add_argument("--n-episodes", type=int, default=2, help="Episodes per task") |
| vlm_parser.add_argument( |
| "--data-path", |
| default=str(repo_root / "dataset" / "vlm"), |
| help="Directory containing rendered VLM data", |
| ) |
| vlm_parser.add_argument( |
| "--save-path", |
| default=str(repo_root / "logs" / "vlm"), |
| help="Directory to store VLM outputs", |
| ) |
| vlm_parser.add_argument("--language", choices=["en", "zh"], default="en", help="Prompt language") |
| vlm_parser.add_argument("--eval-dim", default="default", help="Evaluation dimension key") |
|
|
| return parser |
|
|
|
|
| def main(argv: list[str] | None = None) -> None: |
| parser = build_parser() |
| args = parser.parse_args(argv) |
|
|
| _prepare_environment(args.project_root, args.vlabench_root, args.mujoco_gl) |
|
|
| if args.command == "policy": |
| _run_policy_eval(args) |
| elif args.command == "vlm": |
| _run_vlm_eval(args) |
| else: |
| parser.error("Unknown command; use 'policy' or 'vlm'.") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|