benchmarks-viz / outputs /_scripts /scene_demo.py
ckwolfe's picture
Upload folder using huggingface_hub
73a3036 verified
"""End-to-end Genesis/dexmachina scene demo.
Runs inside the `benchmarking/dexmachina:latest` container. Patches the
installed `dexmachina` package with the missing `envs/hand_cfgs/` submodule
(copied to `outputs/_runtime_patches` on the host, volume-mounted at
`/workspace/outputs/_runtime_patches`), verifies imports, builds a small
Genesis scene (ground plane + xhand URDF), renders 60 frames and muxes them
into an mp4 via `shared.bench.VideoRecorder`.
All output artefacts are written under `/workspace/outputs/`.
"""
from __future__ import annotations
import json
import os
import shutil
import sys
import time
import traceback
from pathlib import Path
OUT_ROOT = Path("/workspace/outputs")
LOG_PATH = OUT_ROOT / "logs" / "dexmachina_scene_demo.log"
MP4_PATH = OUT_ROOT / "videos" / "dexmachina_xhand_demo.mp4"
LOG_PATH.parent.mkdir(parents=True, exist_ok=True)
MP4_PATH.parent.mkdir(parents=True, exist_ok=True)
log_buf = []
def log(msg: str) -> None:
print(msg, flush=True)
log_buf.append(str(msg))
def flush_log() -> None:
LOG_PATH.write_text("\n".join(log_buf) + "\n")
# ---- 1. runtime-patch dexmachina.envs.hand_cfgs (missing in installed wheel)
def patch_hand_cfgs() -> None:
import dexmachina
dst = Path(dexmachina.__file__).parent / "envs" / "hand_cfgs"
src = Path("/workspace/outputs/_runtime_patches/dexmachina/envs/hand_cfgs")
if not dst.exists():
if not src.exists():
raise RuntimeError(f"hand_cfgs staged source missing: {src}")
shutil.copytree(src, dst)
log(f"patched: copied {src} -> {dst}")
else:
log(f"hand_cfgs already present at {dst}")
# ---- 2. import graph
def do_imports() -> dict:
import importlib.metadata as im
import torch, genesis, rl_games, dexmachina # noqa: F401
from dexmachina.envs.hand_cfgs.xhand import XHAND_CFGs
from dexmachina.envs import base_env
info = {
"torch": torch.__version__,
"genesis": getattr(genesis, "__version__", "ok"),
"rl_games": im.version("rl_games"),
"dexmachina": im.version("dexmachina"),
"cuda_available": bool(torch.cuda.is_available()),
"BaseEnv": base_env.BaseEnv.__name__,
"XHAND_CFGs_keys": list(XHAND_CFGs.keys()),
}
return info
# ---- 3. scene demo
def run_scene_demo() -> dict:
import numpy as np
import torch
import genesis as gs
sys.path.insert(0, "/workspace/shared")
from bench.video_recorder import VideoRecorder
backend = gs.cuda if torch.cuda.is_available() else gs.cpu
log(f"genesis.init backend={backend}")
gs.init(backend=backend, logging_level="warning")
scene = gs.Scene(show_viewer=False)
# ground plane
scene.add_entity(gs.morphs.Plane())
# xhand URDF (right hand is the standard variant)
# Preference order: staging-backed /workspace/assets symlinks (but in this
# image those aren't mounted, so the symlink target is missing), then the
# dexmachina-shipped URDF. We try both so future mount changes "just work".
candidates = [
"/workspace/assets/urdf/xhand/xhand_urdf/xhand_right/urdf/xhand_right.urdf",
"/usr/local/lib/python3.10/dist-packages/dexmachina/assets/xhand/xhand_right.urdf",
]
urdf_path = next((p for p in candidates if Path(p).exists()), None)
assert urdf_path is not None, f"no xhand urdf found among {candidates}"
log(f"urdf_path={urdf_path}")
hand = scene.add_entity(
gs.morphs.URDF(
file=urdf_path,
pos=(0.0, 0.0, 0.25),
fixed=True,
)
)
W, H = 640, 480
camera = scene.add_camera(
res=(W, H),
pos=(0.6, 0.6, 0.45),
lookat=(0.0, 0.0, 0.2),
fov=45,
GUI=False,
)
scene.build()
log(f"scene built; hand entity: {hand}")
rec = VideoRecorder(MP4_PATH, fps=30, size=(W, H))
n_frames = 60
t0 = time.time()
for i in range(n_frames):
scene.step()
out = camera.render()
# Genesis camera.render returns a tuple (rgb, depth, seg, normal)
rgb = out[0] if isinstance(out, tuple) else out
if hasattr(rgb, "cpu"):
rgb = rgb.cpu().numpy()
if rgb.dtype != np.uint8:
rgb = rgb.astype(np.uint8)
if rgb.shape[-1] == 4:
rgb = rgb[..., :3]
rec.log_frame(np.ascontiguousarray(rgb))
rec.close()
dt = time.time() - t0
size_bytes = MP4_PATH.stat().st_size
log(f"rendered {n_frames} frames {W}x{H} in {dt:.2f}s; mp4={MP4_PATH} ({size_bytes} bytes)")
return {
"mp4_path": str(MP4_PATH),
"frames": n_frames,
"resolution": [W, H],
"mp4_size_bytes": size_bytes,
"backend": str(backend),
"elapsed_s": round(dt, 3),
}
def main() -> int:
result = {"ok": True, "steps": {}}
try:
patch_hand_cfgs()
imports = do_imports()
result["steps"]["imports"] = imports
log("IMPORTS: " + json.dumps(imports))
except Exception as e:
result["ok"] = False
result["steps"]["imports_error"] = repr(e)
log("IMPORT ERROR: " + repr(e))
log(traceback.format_exc())
flush_log()
(OUT_ROOT / "logs" / "dexmachina_scene_demo.json").write_text(json.dumps(result, indent=2))
return 2
try:
scene_info = run_scene_demo()
result["steps"]["scene"] = scene_info
log("SCENE: " + json.dumps(scene_info))
except Exception as e:
result["ok"] = False
result["steps"]["scene_error"] = repr(e)
log("SCENE ERROR: " + repr(e))
log(traceback.format_exc())
flush_log()
(OUT_ROOT / "logs" / "dexmachina_scene_demo.json").write_text(json.dumps(result, indent=2))
return 3
flush_log()
(OUT_ROOT / "logs" / "dexmachina_scene_demo.json").write_text(json.dumps(result, indent=2))
log("DONE")
return 0
if __name__ == "__main__":
sys.exit(main())