GWAM_Data / scripts /verify_rgb_graph_alignment.py
ChangChrisLiu's picture
Add reusable RGB graph alignment verifier
f5d3e89 verified
Raw
History Blame Contribute Delete
7.03 kB
#!/usr/bin/env python3
"""Verify online GWAM graph / multi-view RGB / mask alignment on a live RoboCasa env.
This is an integration smoke for the team-facing contract:
snapshot = extractor.extract_final_graph(...)
snapshot['gnn_graph'] is the fused graph from the current state
snapshot['rgb_frames'][v] is the current RGB image for view id v
snapshot['rle_masks'][*]['v'] and visual_features_sparse['v'] use the same v
The default backend is fake so this can run without SAM2/CLIP while still
checking state/RGB/mask/feature plumbing. Use scripts/verify_realtime_final_graph.py
for the real SAM2/CLIP backend gate.
"""
from __future__ import annotations
import argparse
import gzip
import hashlib
import json
import sys
import tempfile
from pathlib import Path
import numpy as np
PACKAGE_ROOT = Path(__file__).resolve().parents[1]
if str(PACKAGE_ROOT) not in sys.path:
sys.path.insert(0, str(PACKAGE_ROOT))
from examples.realtime_env_graph_eval_loop import FakeVisualBackend, make_env, zero_action # noqa: E402
from realtime.gwam_realtime_env_graph import ( # noqa: E402
RealtimeGWAMGraphExtractor,
build_online_visual_features,
render_rgb_frames,
render_visibility_and_masks,
save_realtime_graph_snapshot,
)
def state_digest(sim) -> str:
h = hashlib.sha256()
h.update(np.asarray(sim.data.qpos, dtype=np.float64).tobytes())
h.update(np.asarray(sim.data.qvel, dtype=np.float64).tobytes())
h.update(np.asarray([sim.data.time], dtype=np.float64).tobytes())
return h.hexdigest()
def rle_key(row: dict) -> tuple[int, int, str]:
return int(row["n"]), int(row["v"]), json.dumps(row["rle"], separators=(",", ":"))
def main() -> int:
ap = argparse.ArgumentParser()
ap.add_argument("--task", default="OpenDrawer")
ap.add_argument("--robots", default="PandaOmron")
args = ap.parse_args()
env = make_env(args.task, args.robots)
try:
env.reset()
extractor = RealtimeGWAMGraphExtractor(env)
backend = FakeVisualBackend()
before = state_digest(extractor.sim)
snapshot = extractor.extract_final_graph(visual_backend=backend, include_masks=True)
after = state_digest(extractor.sim)
assert before == after, "extract_final_graph advanced or mutated sim state"
graph = snapshot["gnn_graph"]
assert graph["x"].shape[1] == 342, graph["x"].shape
assert graph["edge_attr"].shape[1] == 8, graph["edge_attr"].shape
assert snapshot["rgb_frame_cameras"] == ["robot0_agentview_right", "robot0_agentview_left", "robot0_eye_in_hand"]
assert len(snapshot["rgb_frames"]) == 3
for v, frame in snapshot["rgb_frames"].items():
assert int(v) in (0, 1, 2)
assert frame.shape == (256, 256, 3), frame.shape
assert frame.dtype == np.uint8, frame.dtype
# Re-render from the still-current state; RGB and segmentation/masks must match.
rgb2 = render_rgb_frames(extractor.sim, cameras=extractor.cameras)
for v in snapshot["rgb_frames"]:
assert np.array_equal(snapshot["rgb_frames"][v], rgb2[v]), f"RGB view {v} changed without env.step"
visible2, centroid2, area2, bbox2, rle2 = render_visibility_and_masks(
extractor.sim, extractor.g2n, len(extractor.specs), cameras=extractor.cameras, include_rle=True
)
assert np.array_equal(snapshot["view_visible"], visible2)
assert np.allclose(snapshot["view_centroid"], centroid2, equal_nan=True)
assert np.allclose(snapshot["view_area"], area2, equal_nan=True)
assert np.allclose(snapshot["view_bbox"], bbox2, equal_nan=True)
assert sorted(map(rle_key, snapshot["rle_masks"])) == sorted(map(rle_key, rle2))
# Sparse feature provenance: recomputing with returned RGB/masks matches.
recomputed = build_online_visual_features(
rgb_frames=snapshot["rgb_frames"],
rle_rows=snapshot["rle_masks"],
nodes=snapshot["graph_static"]["nodes"],
visual_backend=backend,
t=0,
)
visual = snapshot["visual_features_sparse"]
for key in ["t", "n", "v", "feat", "type_clip32", "visual_computed", "invalid_t", "invalid_n", "invalid_v"]:
assert np.array_equal(visual[key], recomputed[key]), key
assert len(visual["n"]) + len(visual["invalid_n"]) == len(snapshot["rle_masks"])
# Node-state visibility flags match the view_visible matrix for active nodes.
active = snapshot["node_state"][:, 0] == 1
assert np.array_equal(snapshot["node_state"][active, 19:22].astype(bool), snapshot["view_visible"][active])
assert not any(e.get("rel") == "visibility_change" for e in snapshot["dynamic_edges"]), "first call should not have visibility_change edges"
# Persistence contract: saved RGB, masks, node_state, cameras round-trip.
with tempfile.TemporaryDirectory(prefix="gwam-rgb-align-") as td:
out = Path(td)
save_realtime_graph_snapshot(snapshot, out)
manifest = json.loads((out / "rgb_manifest.json").read_text())
assert [v["camera"] for v in manifest["views"]] == snapshot["rgb_frame_cameras"]
for rec in manifest["views"]:
arr = np.load(out / rec["path"])
assert np.array_equal(arr, snapshot["rgb_frames"][int(rec["view_id"])])
ve = np.load(out / "graph/view_evidence.npz")
assert list(ve["cameras"]) == snapshot["rgb_frame_cameras"]
assert np.array_equal(ve["view_visible"][0], snapshot["view_visible"])
ns = np.load(out / "graph/node_state.npz")
assert np.array_equal(ns["node_state"][0], snapshot["node_state"])
with gzip.open(out / "graph/visible_masks_rle.jsonl.gz", "rt") as f:
saved_masks = json.loads(f.readline())["masks"]
assert sorted(map(rle_key, saved_masks)) == sorted(map(rle_key, snapshot["rle_masks"]))
# Currency after one env step: t increments. RGB often changes even for zero action,
# but we only require the extractor not to reuse stale t/cache.
env.step(zero_action(env))
snapshot2 = extractor.extract_final_graph(visual_backend=backend, include_masks=True)
assert snapshot2["t"] == snapshot["t"] + 1
assert len(snapshot2["rgb_frames"]) == 3
result = {
"ok": True,
"N_real": int(graph["metadata"]["N_real"]),
"D_node": int(graph["x"].shape[1]),
"D_edge": int(graph["edge_attr"].shape[1]),
"n_visible_pairs": int(len(snapshot["rle_masks"])),
"n_feat_rows": int(len(visual["n"])),
"rgb_cameras": snapshot["rgb_frame_cameras"],
}
print("verify_rgb_graph_alignment_ok", json.dumps(result, sort_keys=True))
return 0
finally:
try:
env.close()
except Exception:
pass
if __name__ == "__main__":
raise SystemExit(main())