Download scripts/diagnose_eval_env_step.py from zhicao/openpi: direct link, hf CLI and curl.
- Browser
- Download file 11.1 kB
-
https://huggingface.co/datasets/zhicao/openpi/resolve/main/scripts/diagnose_eval_env_step.py
- Command line
-
hf download hf://datasets/zhicao/openpi/scripts/diagnose_eval_env_step.py
-
curl -L -o diagnose_eval_env_step.py https://huggingface.co/datasets/zhicao/openpi/resolve/main/scripts/diagnose_eval_env_step.py
11.1 kB
| #!/usr/bin/env python3 | |
| """Diagnose why LIBERO env.step is slow (packages vs node vs GPU render contention). | |
| Run: | |
| cd /scratch1/home/zhicao/openpi | |
| .venv/bin/python scripts/diagnose_eval_env_step.py | |
| CUDA_VISIBLE_DEVICES=2 .venv/bin/python scripts/diagnose_eval_env_step.py --with-gpu-policy | |
| """ | |
| from __future__ import annotations | |
| import argparse | |
| import json | |
| import os | |
| import subprocess | |
| import sys | |
| import time | |
| from pathlib import Path | |
| OPENPI_ROOT = Path(__file__).resolve().parents[1] | |
| def _parse_args() -> argparse.Namespace: | |
| p = argparse.ArgumentParser(description="Diagnose env.step slowness for evaluate2") | |
| p.add_argument("--worker", action="store_true", help=argparse.SUPPRESS) | |
| p.add_argument("--suite", default="libero_10_task") | |
| p.add_argument("--task-index", type=int, default=4) | |
| p.add_argument("--steps", type=int, default=25) | |
| p.add_argument("--resolution", type=int, default=256) | |
| p.add_argument("--with-gpu-policy", action="store_true") | |
| p.add_argument("--checkpoint-dir", default=str( | |
| OPENPI_ROOT / "checkpoints/pi05_libero_stage2p5_joint/pi05_final/29999" | |
| )) | |
| p.add_argument("--config-name", default="pi05_libero_stage2p5_joint") | |
| p.add_argument("--mujoco-gl", default="osmesa") | |
| p.add_argument("--mode", default="mesh_fast", choices=["plain", "mesh_legacy", "mesh_fast"]) | |
| p.add_argument("--label", default="") | |
| p.add_argument("--gl-list", default="osmesa,egl", help="Backends to compare in driver mode") | |
| return p.parse_args() | |
| def _run_info() -> dict: | |
| info: dict = {} | |
| info["python"] = sys.executable | |
| try: | |
| info["loadavg"] = os.getloadavg() | |
| except OSError: | |
| pass | |
| if hasattr(os, "sched_getaffinity"): | |
| info["affinity_cpus"] = len(os.sched_getaffinity(0)) | |
| info["cuda_visible"] = os.environ.get("CUDA_VISIBLE_DEVICES", "") | |
| info["mujoco_gl"] = os.environ.get("MUJOCO_GL", "") | |
| for mod in ("mujoco", "numpy", "torch", "robosuite"): | |
| try: | |
| m = __import__(mod) | |
| info[f"{mod}_version"] = getattr(m, "__version__", "?") | |
| except ImportError: | |
| info[f"{mod}_version"] = "missing" | |
| try: | |
| out = subprocess.check_output( | |
| [ | |
| "nvidia-smi", | |
| "--query-gpu=index,name,utilization.gpu,memory.used", | |
| "--format=csv,noheader", | |
| ], | |
| text=True, | |
| timeout=5, | |
| ) | |
| info["nvidia_smi"] = out.strip().splitlines()[:4] | |
| except Exception as e: | |
| info["nvidia_smi"] = str(e) | |
| return info | |
| def _worker_main(args: argparse.Namespace) -> None: | |
| os.environ["MUJOCO_GL"] = args.mujoco_gl | |
| for p in (OPENPI_ROOT / "third_party", OPENPI_ROOT / "third_party" / "libero"): | |
| if str(p) not in sys.path: | |
| sys.path.insert(0, str(p)) | |
| os.environ.setdefault("LIBERO_CONFIG_PATH", str(OPENPI_ROOT / ".libero_local")) | |
| import numpy as np | |
| from libero.libero import benchmark, get_libero_path | |
| from libero.libero.envs import OffScreenRenderEnv | |
| from libero.libero.envs.mesh_vertex_tracker import MeshVertexTracker | |
| from libero.libero.envs.mesh_vertex_wrapper import MeshVertexWrapper | |
| bench = benchmark.get_benchmark_dict()[args.suite]() | |
| task = bench.get_task(args.task_index) | |
| bddl = Path(get_libero_path("bddl_files")) / task.problem_folder / task.bddl_file | |
| act = [0.0] * 6 + [-1.0] | |
| agent_ids = [3001, 3004, 3014, 3067, 3040, 3081, 2898] | |
| wrist_ids = [2955, 3055, 3040, 2981, 2966, 3052, 3022] | |
| def make_env(): | |
| e = OffScreenRenderEnv( | |
| bddl_file_name=bddl, | |
| camera_heights=args.resolution, | |
| camera_widths=args.resolution, | |
| render_gpu_device_id=-1, | |
| ) | |
| e.seed(7) | |
| if args.mode == "plain": | |
| return e | |
| if args.mode == "mesh_legacy": | |
| e = MeshVertexWrapper(e, max_points=10000, include_non_mesh_geoms=True) | |
| if args.mode in ("mesh_legacy", "mesh_fast"): | |
| e = MeshVertexTracker( | |
| e, | |
| agentview_vertex_ids=agent_ids, | |
| eye_in_hand_vertex_ids=wrist_ids, | |
| img_height=args.resolution, | |
| img_width=args.resolution, | |
| ) | |
| return e | |
| policy = None | |
| if args.with_gpu_policy: | |
| import dataclasses | |
| import torch | |
| from openpi.policies import policy_config as _policy_config | |
| from openpi.training import config as training_config | |
| cfg = training_config.get_config(args.config_name) | |
| eval_cfg = dataclasses.replace( | |
| cfg, data=dataclasses.replace(cfg.data, include_track_targets=False) | |
| ) | |
| eval_data_cfg = eval_cfg.data.create(eval_cfg.assets_dirs, eval_cfg.model) | |
| policy = _policy_config.create_trained_policy( | |
| eval_cfg, | |
| args.checkpoint_dir, | |
| repack_transforms=eval_data_cfg.repack_transforms, | |
| ) | |
| if torch.cuda.is_available(): | |
| torch.cuda.synchronize() | |
| env = make_env() | |
| env.reset() | |
| mapping_size = len(getattr(env, "vertex_mapping", {}) or {}) | |
| for _ in range(3): | |
| env.step(act) | |
| infer_s = 0.0 | |
| infer_n = 0 | |
| t0 = time.perf_counter() | |
| for i in range(args.steps): | |
| if policy is not None and i % 5 == 0: | |
| import torch | |
| from openpi_client import image_tools | |
| inner = env | |
| while hasattr(inner, "env") and not hasattr(inner, "sim"): | |
| inner = inner.env | |
| obs = inner._get_observations() if hasattr(inner, "_get_observations") else {} | |
| ag = np.asarray(obs.get("agentview_image", np.zeros((args.resolution, args.resolution, 3)))) | |
| wr = np.asarray(obs.get("robot0_eye_in_hand_image", np.zeros((args.resolution, args.resolution, 3)))) | |
| ag = image_tools.convert_to_uint8(image_tools.resize_with_pad(ag, 224, 224)) | |
| wr = image_tools.convert_to_uint8(image_tools.resize_with_pad(wr, 224, 224)) | |
| grid = np.linspace(0.1, 0.9, 5, dtype=np.float32) | |
| uu, vv = np.meshgrid(grid, grid, indexing="ij") | |
| g25 = np.stack([uu.reshape(-1), vv.reshape(-1)], axis=-1) | |
| raw = { | |
| "image": ag, | |
| "wrist_image": wr, | |
| "state": np.zeros(8, np.float32), | |
| "actions": np.zeros((16, 7), np.float32), | |
| "prompt": "diag", | |
| "agentview_mesh_vertices_2d": np.stack( | |
| [np.linspace(0.35, 0.65, 7), np.full(7, 0.55)], axis=1 | |
| ).astype(np.float32), | |
| "wrist_mesh_vertices_2d": np.stack( | |
| [np.linspace(0.35, 0.65, 7), np.full(7, 0.55)], axis=1 | |
| ).astype(np.float32), | |
| "wrist_tracks": np.concatenate([g25, np.stack( | |
| [np.linspace(0.35, 0.65, 7), np.full(7, 0.55)], axis=1 | |
| )]).astype(np.float32), | |
| "wrist_grid_mesh_32": np.zeros((32, 2), np.float32), | |
| } | |
| t_inf = time.perf_counter() | |
| policy.infer(raw, return_tracks=True) | |
| if torch.cuda.is_available(): | |
| torch.cuda.synchronize() | |
| infer_s += time.perf_counter() - t_inf | |
| infer_n += 1 | |
| env.step(act) | |
| if policy is not None: | |
| import torch | |
| if torch.cuda.is_available(): | |
| torch.cuda.synchronize() | |
| dt = time.perf_counter() - t0 | |
| env.close() | |
| label = args.label or f"{args.mode}_{args.mujoco_gl}" | |
| out = { | |
| "label": label, | |
| "mujoco_gl": args.mujoco_gl, | |
| "mode": args.mode, | |
| "ms_per_step": round(1000.0 * dt / args.steps, 2), | |
| "total_s": round(dt, 3), | |
| "vertex_mapping": mapping_size, | |
| "with_gpu_policy": args.with_gpu_policy, | |
| "infer_s": round(infer_s, 3), | |
| "infer_n": infer_n, | |
| } | |
| print(json.dumps(out), flush=True) | |
| def _spawn_worker(extra: list[str], env: dict[str, str]) -> dict: | |
| cmd = [sys.executable, str(Path(__file__).resolve()), "--worker", *extra] | |
| proc = subprocess.run(cmd, cwd=str(OPENPI_ROOT), env=env, capture_output=True, text=True) | |
| if proc.returncode != 0: | |
| return {"error": proc.stderr[-800:]} | |
| return json.loads(proc.stdout.strip().splitlines()[-1]) | |
| def main() -> None: | |
| args = _parse_args() | |
| if args.worker: | |
| _worker_main(args) | |
| return | |
| print("=== Runtime / package info ===") | |
| for k, v in _run_info().items(): | |
| print(f" {k}: {v}") | |
| gl_list = [g.strip() for g in args.gl_list.split(",") if g.strip()] | |
| modes = ["plain", "mesh_legacy", "mesh_fast"] | |
| rows: list[dict] = [] | |
| print("\n=== env.step benchmarks (subprocess per cell, clean GL context) ===") | |
| for gl in gl_list: | |
| for mode in modes: | |
| label = f"{mode}_{gl}" | |
| print(f" {label} ...", flush=True) | |
| extra = [ | |
| "--suite", args.suite, | |
| "--task-index", str(args.task_index), | |
| "--steps", str(args.steps), | |
| "--resolution", str(args.resolution), | |
| "--mujoco-gl", gl, | |
| "--mode", mode, | |
| "--label", label, | |
| "--config-name", args.config_name, | |
| "--checkpoint-dir", args.checkpoint_dir, | |
| ] | |
| if args.with_gpu_policy: | |
| extra.append("--with-gpu-policy") | |
| row = _spawn_worker(extra, {**os.environ, "MUJOCO_GL": gl}) | |
| rows.append(row) | |
| if "ms_per_step" in row: | |
| print(f" {row['ms_per_step']} ms/step") | |
| else: | |
| print(f" ERROR: {row.get('error', '?')[:200]}") | |
| print("\n=== Summary ===") | |
| print(f"{'label':28} {'ms/step':>10} {'vertices':>8}") | |
| print("-" * 50) | |
| for r in rows: | |
| if "ms_per_step" not in r: | |
| print(f"{r.get('label', '?'):28} {'FAIL':>10}") | |
| continue | |
| print(f"{r['label']:28} {r['ms_per_step']:10.2f} {r.get('vertex_mapping', 0):8}") | |
| legacy_osmesa = next((r for r in rows if r.get("label") == "mesh_legacy_osmesa"), {}) | |
| fast_osmesa = next((r for r in rows if r.get("label") == "mesh_fast_osmesa"), {}) | |
| if legacy_osmesa.get("ms_per_step") and fast_osmesa.get("ms_per_step"): | |
| sp = legacy_osmesa["ms_per_step"] / fast_osmesa["ms_per_step"] | |
| print(f"\n mesh_fast vs mesh_legacy (osmesa): {sp:.2f}x faster") | |
| egl = next((r for r in rows if r.get("label") == "mesh_fast_egl"), {}) | |
| osm = next((r for r in rows if r.get("label") == "mesh_fast_osmesa"), {}) | |
| if egl.get("ms_per_step") and osm.get("ms_per_step"): | |
| print(f" mesh_fast egl/osmesa: {egl['ms_per_step'] / osm['ms_per_step']:.2f}x") | |
| print("\n=== Verdict guide ===") | |
| print(" Package OK if: mujoco 2.3.x from .venv, ms/step tens not thousands (idle node).") | |
| print(" Node issue if: loadavg ~ affinity_cpus and all modes slow.") | |
| print(" GPU contention if: mesh_fast_egl >> mesh_fast_osmesa, worse with --with-gpu-policy.") | |
| print(" evaluate.py: use --policy-gpu N --render-gpu M to split policy vs MuJoCo EGL.") | |
| if __name__ == "__main__": | |
| main() | |