File size: 7,829 Bytes
8a66870 fb2f41e 8a66870 fb2f41e e371d65 8a66870 fb2f41e 8a66870 fb2f41e 8a66870 fb2f41e 8a66870 d5fb6b2 fb2f41e d5fb6b2 fb2f41e e371d65 fb2f41e e371d65 fb2f41e 8a66870 fb2f41e d5fb6b2 fb2f41e 8a66870 fb2f41e 8a66870 d5fb6b2 8a66870 fb2f41e 8a66870 fb2f41e 8a66870 fb2f41e 8a66870 | 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 | #!/usr/bin/env python3
"""Example: build the full online GWAM final graph during evaluation.
This is a template, not a benchmark script. It requires a working local RoboCasa
installation and simulator assets. For the full final graph it also requires the
same Phase-2 visual stack used locally: SAM2.1 Hiera-B+ checkpoint and CLIP.
The HF dataset does not redistribute RoboCasa/MuJoCo assets; SAM2/CLIP checkpoints are bundled under models/ with upstream licenses.
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import sys
import numpy as np
# Allow running this file directly from the HF package checkout:
# python examples/realtime_env_graph_eval_loop.py ...
PACKAGE_ROOT = Path(__file__).resolve().parents[1]
if str(PACKAGE_ROOT) not in sys.path:
sys.path.insert(0, str(PACKAGE_ROOT))
from realtime.gwam_realtime_env_graph import ( # noqa: E402
RealtimeGWAMGraphExtractor,
Sam2ClipRealtimeFeatureBackend,
save_realtime_graph_snapshot,
)
class FakeVisualBackend:
"""Small deterministic backend for CI/docs smoke only; not for real metrics."""
def image_embedding(self, rgb_frame):
return np.asarray(rgb_frame, dtype=np.float32)
def pool_mask(self, image_embedding, mask):
if not mask.any():
return None
seed = float(image_embedding[mask].mean()) if image_embedding.ndim == 3 else float(mask.mean())
vec = np.linspace(0.0, 1.0, 256, dtype=np.float32) + seed / 255.0
vec /= np.linalg.norm(vec).clip(min=1e-6)
return vec.astype(np.float16)
def type_clip32(self, nodes):
arr = np.zeros((256, 32), dtype=np.float32)
for i in range(min(len(nodes), 256)):
arr[i, i % 32] = 1.0
return arr, {"model": "fake-docs-ci-only", "projection_seed": 20260702}
def make_env(task: str, robots: str):
import robocasa # noqa: F401 registers RoboCasa environments
import robosuite
return robosuite.make(
task,
robots=robots,
has_renderer=False,
has_offscreen_renderer=True,
use_object_obs=True,
use_camera_obs=True,
camera_names=["robot0_agentview_right", "robot0_agentview_left", "robot0_eye_in_hand"],
camera_heights=256,
camera_widths=256,
camera_depths=False,
reward_shaping=False,
ignore_done=True,
)
def zero_action(env) -> np.ndarray:
if hasattr(env, "action_spec"):
spec = env.action_spec
if isinstance(spec, tuple) and len(spec) == 2:
low, _high = spec
return np.zeros_like(low, dtype=np.float32)
if hasattr(env, "action_dim"):
return np.zeros(int(env.action_dim), dtype=np.float32)
raise RuntimeError("cannot infer action dimension; replace zero_action() with your policy action")
def make_visual_backend(name: str, device: str | None, sam2_root: Path | None, sam2_checkpoint: Path | None, clip_checkpoint: Path | None):
if name == "sam2":
return Sam2ClipRealtimeFeatureBackend(
device=device,
sam2_root=sam2_root,
sam2_checkpoint=sam2_checkpoint,
clip_checkpoint=clip_checkpoint,
)
if name == "fake":
return FakeVisualBackend()
raise ValueError(f"unknown visual backend: {name}")
def summarize_graph(t: int, snapshot: dict) -> dict:
graph = snapshot["gnn_graph"]
visual = snapshot.get("visual_features_sparse") or {}
rgb_frames = snapshot.get("rgb_frames") or {}
rgb_cameras = list(snapshot.get("rgb_frame_cameras") or [])
rgb_shapes = {str(k): list(np.asarray(v).shape) for k, v in sorted(rgb_frames.items())}
return {
"t": t,
"N_real": int(graph["metadata"]["N_real"]),
"D_node": int(graph["x"].shape[1]),
"E": int(graph["edge_index"].shape[1]),
"D_edge": int(graph["edge_attr"].shape[1]) if graph["edge_attr"].ndim == 2 else 0,
"first_slots": graph["slot_ids"][:8].astype(int).tolist(),
"final_graph": bool(graph["metadata"].get("include_visual")),
"visual_features_written": int((visual.get("summary") or {}).get("features_written", 0)),
"invalid_visible_pairs": int((visual.get("summary") or {}).get("invalid_visible_pairs", 0)),
"rgb_view_count": len(rgb_frames),
"rgb_cameras": rgb_cameras,
"rgb_shapes": rgb_shapes,
"rgb_aligned_with_view_ids": bool(len(rgb_frames) == len(rgb_cameras) == 3),
}
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--task", default="OpenDrawer", help="RoboCasa/robosuite environment name")
ap.add_argument("--robots", default="PandaOmron", help="RoboCasa robot name; source GWAM_Data episodes use PandaOmron")
ap.add_argument("--steps", type=int, default=3)
ap.add_argument("--visual-backend", choices=["sam2", "fake"], default="sam2", help="Use sam2 for real final graphs; fake is CI/docs smoke only")
ap.add_argument("--device", default=None, help="Torch device for SAM2/CLIP, e.g. cuda or cpu")
ap.add_argument("--sam2-root", type=Path, default=None, help="Optional local sam2 repo path. Needed when SAM2 is editable-installed from source; package weights are used by default when present.")
ap.add_argument("--sam2-checkpoint", type=Path, default=None, help="Optional SAM2 checkpoint path; defaults to package models/sam2/checkpoints/sam2.1_hiera_base_plus.pt when present")
ap.add_argument("--clip-checkpoint", type=Path, default=None, help="Optional CLIP ViT-B/32 checkpoint path; defaults to package models/clip/ViT-B-32.pt when present")
ap.add_argument("--phase1-only-debug", action="store_true", help="Debug only: skip SAM2/CLIP and return 33-D Phase-1 graph instead of final 342-D graph")
ap.add_argument("--save-dir", type=Path, default=None, help="Optional directory for debug graph snapshots")
ap.add_argument("--json-output", type=Path, default=None, help="Optional clean JSON summary path; useful because some simulators print warnings to stdout")
args = ap.parse_args()
env = make_env(args.task, args.robots)
try:
env.reset()
extractor = RealtimeGWAMGraphExtractor(env)
visual_backend = None if args.phase1_only_debug else make_visual_backend(
args.visual_backend,
args.device,
args.sam2_root,
args.sam2_checkpoint,
args.clip_checkpoint,
)
summaries = []
for t in range(args.steps):
if args.phase1_only_debug:
snapshot = extractor.extract_current_graph(include_masks=args.save_dir is not None)
else:
snapshot = extractor.extract_final_graph(visual_backend=visual_backend, include_masks=args.save_dir is not None)
summaries.append(summarize_graph(t, snapshot))
if args.save_dir is not None:
save_realtime_graph_snapshot(snapshot, args.save_dir / f"step_{t:06d}")
action = zero_action(env)
_obs, _reward, done, _info = env.step(action)
if done:
break
result = {
"task": args.task,
"robots": args.robots,
"steps": len(summaries),
"phase1_only_debug": bool(args.phase1_only_debug),
"visual_backend": args.visual_backend if not args.phase1_only_debug else None,
"summaries": summaries,
}
text = json.dumps(result, indent=2)
if args.json_output is not None:
args.json_output.parent.mkdir(parents=True, exist_ok=True)
args.json_output.write_text(text + "\n")
print(text)
finally:
try:
env.close()
except Exception:
pass
return 0
if __name__ == "__main__":
raise SystemExit(main())
|