| --- |
| license: cc-by-4.0 |
| task_categories: [robotics, image-segmentation, graph-ml] |
| language: [en] |
| tags: [robotics, manipulation, disassembly, tower-of-hanoi, constraint-graph, gnn, world-model, sam2, segmentation, ur5e] |
| size_categories: [1K<n<10K] |
| pretty_name: GNN Constraint-Aware World Model Dataset (v3) |
| --- |
| |
| # GNN Constraint-Aware World Model Dataset (v3) |
|
|
| Real robot episodes with per-frame constraint graphs, SAM2 segmentation masks + 256-D feature embeddings, full 3D depth bundles, and synchronized robot states across two manipulation domains. Both domains share the v3 on-disk layout (same JSON/NPZ schemas, same delta-encoded `frame_states`, same fully-connected PyG expansion at load time) and now share a unified **270-D node feature format** β the PyG loader reads a fixed 10-D type encoding from a YAML config so both domains produce identical node dimensionality. |
|
|
| - **Project:** CoRL 2026 β GNN world model for constraint-aware video generation |
| - **Author:** Chang Liu (Texas A&M University) |
| - **Hardware:** UR5e + Robotiq 2F-85 gripper, OAK-D Pro (static side view) |
| - **Format version:** v3.0 (updated 2026-04-16) |
|
|
| ### What's in this repo β at a glance |
|
|
| | Where | Contains | Use for | |
| |---|---|---| |
| | `session_*` (Desktop) and `hanoi/session_hanoi_*` | Raw episodes + per-frame `annotations/` (masks, embeddings, depth bundles, `side_graph.json`) | **Training data for the world model** | |
| | `config/type_encoding_*.yaml` | Fixed 10-D per-type encoding YAMLs | Loader inputs (pick one per run) | |
| | `tools/hanoi_pipeline/` | SAM2 FT checkpoint + all Python code to regenerate / extend / run the Hanoi pipeline end-to-end (auto-labeler, single-frame inferer, per-frame materializer) | **Reproducing or re-running the pipeline** on new Hanoi sessions; inference-time RGBβgraph | |
| | **Not in this repo** (source repo only): `scripts/hanoi/orchestrator.py` (robot data collection), `scripts/run_annotator.sh` (browser verification UI), `scripts/sam2_finetune/` (FT training harness) | Hardware-facing and web-UI code | Clone [the source repo](https://github.com/ChangChrisLiu/gnn-world-model) if you want to collect new data, verify labels in a browser, or retrain the SAM2 FT checkpoint | |
|
|
| ## Domains at a glance |
|
|
| | Domain | Graph variants offered | Node vocab size | Node feature dim | Edge feature dim | Data root | |
| |---|---|---|---|---|---| |
| | Desktop disassembly | products-only, with-robot-node, with-robot-state, with-robot-action | 9 (8 products + `robot`) | **270** | 3 | `session_<date>_<time>/episode_XX/` | |
| | Tower of Hanoi | products-only, with-robot-state, with-robot-action | 4 (`ring_1..ring_4`) | **270** | 3 | `hanoi/session_hanoi_<date>_<time>/episode_XX/` | |
|
|
| Node feature dim = `256 (SAM2 emb) + 3 (3D pos) + 10 (fixed type encoding) + 1 (visibility) = 270`. The 10-D type encoding is a **fixed, deterministic** per-type vector (NOT trained) read from `config/type_encoding_random.yaml` or `config/type_encoding_clip.yaml` at load time β so both domains, and any future component vocabulary up to 13 types, share the same node dimension. |
|
|
| **Four loader variants** (all return `torch_geometric.data.Data`): |
|
|
| - `load_pyg_frame_products_only` β V1 bare graph: products/rings only, no robot info. |
| - `load_pyg_frame_with_robot` β V2 ablation: robot attached as a graph NODE (Desktop only; Hanoi has no robot mask in v1, so this falls back to products-only). |
| - `load_pyg_frame_with_robot_state` β **V3 recommended**: products-only graph + `robot_state=[13]` side-tensor. Works for both domains because `robot_states.npy` is present everywhere. |
| - `load_pyg_frame_with_robot_action` β V3 action-conditioned: same as above + `robot_action=[13]` delta for the next frame. |
|
|
| The three paper options map cleanly: Option 1 (direct graph encoding) β `products_only`; Option 2 (encoder β latent β world model with robot context) β `with_robot_state`; Option 3 (action-conditioned GNN) β `with_robot_action`. |
|
|
| ## File layout (same for both domains) |
|
|
| ``` |
| episode_XX/ |
| βββ metadata.json # episode metadata (domain-specific extras) |
| βββ robot_states.npy # (T, 13) float32 β joints + TCP + gripper |
| βββ robot_actions.npy # (T-1, 13) float32 β frame deltas |
| βββ timestamps.npy # (T, 3) float64 |
| βββ side/ |
| β βββ rgb/frame_XXXXXX.png # 1280Γ720 RGB |
| β βββ depth/frame_XXXXXX.npy # 1280Γ720 uint16 (mm) |
| βββ wrist/ # raw wrist camera (not used in v3) |
| βββ annotations/ |
| βββ side_graph.json # components, static edges, frame_states |
| βββ side_masks/ # {component_id: (H,W) uint8} per frame |
| βββ side_embeddings/ # {component_id: (256,) float32} per frame |
| βββ side_depth_info/ # flat-keyed depth bundle per frame |
| βββ side_robot/ # robot bundle per frame (visible flag) |
| βββ dataset_card.json # format description |
| ``` |
|
|
| **Alignment guarantee:** every labeled frame index has files in all four of `side_masks/`, `side_embeddings/`, `side_depth_info/`, `side_robot/`. Files are keyed by the same integer frame index, so a loader can key off the mask directory and trust the rest to be present. |
|
|
| ## Pipeline β four stages from raw video to training-ready graphs |
|
|
| ``` |
| βββββββββββββββ βββββββββββββββββ βββββββββββββββββββββ ββββββββββββββββββββ |
| β Collection β β β Auto-labeling β β β Verification / UI β β β PyG loader @ β |
| β (30 Hz RGBD β β (SAM2-FT) β β (optional edit) β β training time β |
| β + robot) β β β β β β β |
| βββββββββββββββ βββββββββββββββββ βββββββββββββββββββββ ββββββββββββββββββββ |
| episode_XX/ annotations/ annotations/ torch_geometric |
| masks, emb, (corrected) .data.Data |
| depth, robot, x=[N,270], edge=[E,3] |
| side_graph.json |
| ``` |
|
|
| ### Stage 1 β Collection |
| 30 Hz synchronous capture of side RGB + depth + robot state into `episode_XX/`. No image processing or graph work happens here. |
| - **Desktop:** human teleop via a game controller; the operator decides what to disassemble in what order. |
| - **Hanoi:** autonomous β `scripts/hanoi/orchestrator.py` pre-plans N missions upfront from the captured initial state, samples each as `classical`/`single_ring`/`rearrange` at 40/40/20 weights, writes `metadata.json` with `goal_prompt`, `initial_state`, `target_state`, and the deterministic `solver_moves` (reference action sequence from a classical Hanoi BFS solver). The UR5e executes each mission with blended waypoints and per-ring grasp offsets. |
|
|
| ### Stage 2 β Auto-labeling (SAM2 detection β graph) |
| Separate offline step that produces the entire `annotations/` tree. **Hanoi is fully automatic in v3; Desktop currently uses manual + SAM2-assisted labeling.** The Hanoi auto-labeler ships inside this dataset under `tools/hanoi_pipeline/` (so users cloning the dataset can reproduce or extend it): |
|
|
| ```bash |
| python tools/hanoi_pipeline/scripts/hanoi/auto_label.py <session_dir> |
| ``` |
|
|
| Per-frame algorithm (Hanoi): |
| 1. **Ring detection.** HSV range + color-specific mask β largest connected blob β bbox per ring. |
| 2. **SAM2 segmentation.** Run SAM2 with (bbox + centroid point) prompt on each ring. The Hanoi-fine-tuned checkpoint is auto-loaded if present (`checkpoints/sam2_hanoi_ft.pt`); otherwise falls back to vanilla `sam2.1_hiera_base_plus`. |
| 3. **256-D embedding.** Masked average-pool of SAM2's vision_features spatial grid over each ring mask. |
| 4. **Depth backprojection.** Masked pixels β (u, v) + depth β 3D point cloud in camera frame; centroid used as the node position. |
| |
| Per-episode algorithm: |
| 5. **Grasp-interval detection.** Read `robot_states.npy[:, 12]` (Robotiq 2F-85 gripper position, 0-255). Find the lowest stable plateau above the fully-open cutoff (baseline β pre-grasp width), threshold at baseline+10, morphologically close to bridge single-frame glitches, yielding `[(start, end, ring_id)]` intervals β one per move. |
| 6. **Symbolic state unroll.** Starting from `initial_state`, apply `solver_moves[i]` after each interval closes, marking the moved ring as `held=True` during the interval and recording the resulting per-frame `constraints` / `visibility` / `held` dicts as deltas in `frame_states`. **No per-frame ring re-identification is needed**; the move plan is ground truth. |
|
|
| ### Stage 3 β Verification / correction (optional) |
| Browser UI over labeled episodes β live in the **source repo** ([GitHub](https://github.com/ChangChrisLiu/gnn-world-model)), not bundled with the dataset because it's a full React app not just a Python module: |
|
|
| ```bash |
| # from the source repo: |
| bash scripts/run_annotator.sh --hanoi # or --desktop |
| # β open http://localhost:8000 |
| ``` |
|
|
| Per-frame bbox / point / brush / eraser / polygon editing. Save writes back to the same `annotations/side_masks/*.npz`; format is identical pre- and post-verification, so downstream loaders are unaffected. The only module from the annotator that's bundled here is `tools/hanoi_pipeline/src/annotator/labeling_server.py` (the SAM2 backend β reused by `infer_graph_from_frame.py` at inference time). |
|
|
| ### Stage 4 β SAM2 FT retraining (closes the loop) |
| After enough verified frames accumulate, retrain the SAM2 decoder+prompt_encoder on them. The training harness itself lives in the **source repo** ([GitHub](https://github.com/ChangChrisLiu/gnn-world-model)): |
| |
| ```bash |
| # from the source repo: |
| python scripts/sam2_finetune/collect_hanoi_samples.py # pull (RGB, mask, bbox) triples |
| python scripts/sam2_finetune/train.py # fine-tune, save sam2_<domain>_ft.pt |
| ``` |
| |
| The resulting `sam2_hanoi_ft.pt` goes at `tools/hanoi_pipeline/checkpoints/sam2_hanoi_ft.pt` (alongside the one already published here). `auto_label.py` and `HanoiGraphInferer()` both auto-select the checkpoint via that path on their next run. |
| |
| ## SAM2 models used in this dataset |
| |
| Two checkpoints are in play, both distributed by this repo under `tools/hanoi_pipeline/checkpoints/` (also available from the SAM2 repo): |
|
|
| | File | Size | What it contains | When it's used | |
| |---|---|---|---| |
| | `sam2.1_hiera_base_plus.pt` (Meta AI) | ~320 MB | Full SAM2 model β image encoder + prompt encoder + mask decoder | Loaded as the base. Frozen during fine-tuning and inference | |
| | `sam2_hanoi_ft.pt` (this dataset) | ~16 MB | **Decoder + prompt_encoder only** β fine-tuned weights | Auto-loaded when present; overrides the base decoder/prompt_encoder | |
| |
| The 16 MB FT checkpoint is small because the **image encoder stays frozen at the base SAM2 weights**. Training data: ~800 (image, bbox, ground-truth-mask) triples pulled from manually-corrected Hanoi episodes. Per-ring validation IoU (cross-episode held-out solve): |
| |
| | Ring | Vanilla SAM2 base | Hanoi-FT | Ξ | |
| |---|---|---|---| |
| | ring_1 (red) | 0.786 | 0.851 | +6.5 pp | |
| | ring_2 (yellow) | 0.803 | 0.842 | +3.9 pp | |
| | ring_3 (green) | 0.814 | 0.854 | +4.0 pp | |
| | ring_4 (blue) | 0.794 | 0.846 | +5.2 pp | |
| | **macro mean** | **0.799** | **0.848** | **+4.9 pp** | |
|
|
| Biggest gains are on partially-gripper-occluded rings where vanilla SAM2 tended to oversegment onto the gripper finger. |
|
|
| **Usage in the world-model prediction loop.** At inference time you don't need to run the full `auto_label.py` pipeline. Use the provided single-frame inferer: |
|
|
| ```python |
| from tools.hanoi_pipeline.infer_graph_from_frame import HanoiGraphInferer |
| |
| inferer = HanoiGraphInferer() # loads base + FT once |
| result = inferer(rgb_image, depth=depth_image) |
| |
| graph = result["graph"] # side_graph.json schema |
| masks = result["masks"] # {ring_1..ring_4: (H, W) uint8} |
| embeddings = result["embeddings"] # {ring_1..ring_4: (256,) float32} |
| depth_info = result["depth_info"] # flat-keyed 3D bundle (empty if depth=None) |
| states = result["ring_states"] # {ring_id: RingState(peg, stack_index)} |
| ``` |
|
|
| This returns the **same schema** as the offline pipeline's per-frame output, so the PyG loaders work identically on both sources. Override the checkpoint via `SAM2_FINETUNE_CKPT=<path>`; set to empty string to force vanilla SAM2. |
|
|
| ## Desktop Disassembly Domain |
|
|
| ### Components (9 types) |
|
|
| Eight product types + one robot agent. Multiple instances (e.g. `ram_1`, `ram_2`) share the same 10-D type encoding and are disambiguated by SAM2 embedding + 3D position. |
|
|
| | Index | Type | Color | Notes | |
| |---|---|---|---| |
| | 0 | `cpu_fan` | #FF6B6B | Always visible at start | |
| | 1 | `cpu_bracket` | #4ECDC4 | Hidden at start (under fan) | |
| | 2 | `cpu` | #45B7D1 | Hidden at start | |
| | 3 | `ram_clip` | #96CEB4 | Multi-instance | |
| | 4 | `ram` | #FFEAA7 | Multi-instance | |
| | 5 | `connector` | #DDA0DD | Multi-instance | |
| | 6 | `graphic_card` | #FF8C42 | Always visible | |
| | 7 | `motherboard` | #8B5CF6 | Always visible (base) | |
| | 8 | `robot` | #F5F5F5 | Agent node (stored separately in `side_robot/`) | |
|
|
| ### Sparse constraint edges |
|
|
| Directed prerequisite relations β `A -> B` means "A must be removed before B can be removed": |
|
|
| ``` |
| cpu_fan -> cpu_bracket (fan covers bracket) |
| cpu_fan -> motherboard |
| cpu_bracket -> cpu |
| cpu_bracket -> motherboard |
| cpu -> motherboard |
| ram_N -> motherboard |
| ram_clip_N -> motherboard |
| ram_clip_N -> ram_M (user pairs manually) |
| connector_N -> motherboard |
| graphic_card -> motherboard |
| ``` |
|
|
| Typical episode has 10-15 product nodes and 10-14 stored directed edges. |
|
|
| ### Node feature layout (270-D) |
|
|
| ``` |
| [0 : 256] SAM2 embedding (256) β masked avg pool over vision_features |
| [256 : 259] 3D position (3) β centroid in camera frame (meters) |
| [259 : 269] type encoding (10) β fixed 10-D vector from |
| config/type_encoding_<method>.yaml |
| (shared across domains) |
| [269] visibility (1) β 1 if visible this frame, else 0 |
| ``` |
|
|
| Total: **270-D**. The 10-D type slot is a deterministic encoding (NOT trained) β see "Fixed 10-D type encoding β how it's made" below. |
|
|
| ### Available Desktop episodes |
|
|
| | Session / Episode | Labeled frames | Goal | |
| |---|---|---| |
| | `session_0408_162129/episode_00` | 346 | `cpu_fan` | |
| | `session_0410_125013/episode_00` | 473 | `cpu_fan` | |
| | `session_0410_125013/episode_01` | 525 | `graphic_card` | |
|
|
| Total: **1344 frames**. |
|
|
| ## Tower of Hanoi Domain |
|
|
| ### Components (4 types) β rings only, no robot node in v1 |
|
|
| Hanoi episodes use native ring IDs (`ring_1` .. `ring_4`) in `components` and as npz keys β **no desktop-proxy remapping, and no robot node in v1**. `type_vocab` is `["ring_1", "ring_2", "ring_3", "ring_4"]` (length 4). Robot segmentation is deferred; `side_robot/*.npz` is zero-filled per frame for format uniformity but never becomes a graph node. |
|
|
| **Note on V2 vs V3 for Hanoi.** V2 (`with_robot` β robot as graph node) requires a labeled robot mask/embedding and is therefore **Desktop-only in v1**. V3 (`with_robot_state` / `with_robot_action`) uses the 13-D `robot_states.npy` trace, which IS recorded for Hanoi too β so V3 loaders work for both domains. |
|
|
| | ID | Color | Disk size | Role | |
| |---|---|---|---| |
| | `ring_1` | red (#E63946) | 32 mm | Smallest | |
| | `ring_2` | yellow (#F1C40F) | 42 mm | β | |
| | `ring_3` | green (#2ECC71) | 52 mm | β | |
| | `ring_4` | blue (#2E86DE) | 62 mm | Largest | |
|
|
| Mask `.npz` files carry the literal keys `ring_1`, `ring_2`, `ring_3`, `ring_4`. No robot in `type_vocab`, no robot edges, no robot node appended at load time. |
|
|
| ### Mission kinds (40 / 40 / 20 sampling) |
|
|
| | Kind | Weight | Prompt template | Target | |
| |---|---|---|---| |
| | `classical` | 0.40 | `"Solve the puzzle: stack all rings on peg X"` | All 4 rings stacked in size order on one peg | |
| | `single_ring` | 0.40 | `"Move the <color> ring to peg X"` | One designated ring moved; others untouched | |
| | `rearrange` | 0.20 | `"Rearrange: red on peg A, green on peg B, ..."` | Uniformly sampled valid (larger-under-smaller) configuration | |
|
|
| Every Hanoi `metadata.json` records `mission_kind`, `goal_prompt`, `initial_state`, `target_state`, and `solver_moves` (the reference action sequence from the classical-Hanoi solver, one entry per pickup/release pair). |
|
|
| ### Structural edges (static, always 6) |
|
|
| The 6 smaller β larger directed pairs are stored verbatim in `side_graph.json`: |
|
|
| ``` |
| ring_1 -> ring_2 ring_1 -> ring_3 ring_1 -> ring_4 |
| ring_2 -> ring_3 ring_2 -> ring_4 |
| ring_3 -> ring_4 |
| ``` |
|
|
| At PyG load time the loader expands to **4 Γ 3 = 12** fully-connected directed edges. The reverse (larger β smaller) direction carries the same `has_constraint` / `is_locked` but flipped `src_blocks_dst`. |
|
|
| ### Per-frame `is_locked` semantics |
| |
| `is_locked = 1` on edge `(A, B)` **iff A is currently the immediately-stacked ring on top of B on the same peg** (adjacent in the peg-stack with A above B). Every other pair β non-adjacent on the same peg, on different pegs, or with either ring in transit β gets `is_locked = 0`. This is strictly "physical stacking right now," not "A must move before B." |
| |
| ### Held-ring rule (captures "constraint broken during transit") |
| |
| When the robot holds a ring (gripper closed between grasp and release of that move), the ring is in transit and no longer touches any other ring. The auto-labeler flags `held = 1` for that ring on every held frame, and **every edge touching it gets `is_locked = 0`** β the constraint is physically broken mid-move. On release, the new adjacency emerges and that edge flips back to `is_locked = 1`. |
|
|
| Implementation: `auto_label.py` reads `robot_states.npy[:, 12]` (gripper position, Robotiq 2F-85, 0-255) and detects grasp intervals via baseline-mode thresholding (estimate "resting open" mode, threshold at baseline + margin, binary-close morphologically to bridge single-frame glitches). It then zips the resulting intervals with `solver_moves` **in order** β the k-th grasp interval is assigned to the k-th move. Validated on ep_00 (1 move, 1 interval), ep_01 (15 moves, 15 intervals), ep_02 (1 move, 1 interval). Per-frame held deltas are recorded as `frame_states[f].held = {ring_id: True|False}`. |
| |
| ### Rule 2 β "larger must never sit on smaller" |
| |
| Encoded **without a new feature** via the edge's existing `src_blocks_dst` bit: |
| |
| | Edge direction | `src_blocks_dst` | Meaning | |
| |---|---|---| |
| | smaller β larger (e.g. `ring_1 -> ring_3`) | 1 | **Legal** β smaller may rest on larger | |
| | larger β smaller (e.g. `ring_3 -> ring_1`) | 0 | **Illegal** β larger may not rest on smaller | |
| |
| Three dimension-preserving ways the world model can respect Rule 2: |
| |
| | Method | Where | One-liner | Guarantee | |
| |---|---|---|---| |
| | Training loss | objective | `Ξ» * (pred_is_locked * (1 - src_blocks_dst)).sum()` | Soft (shapes distribution) | |
| | Rollout mask | inference | Reject any predicted `is_locked = 1` where `src_blocks_dst = 0` | Hard (eliminates illegal) | |
| | Dataset invariant | this spec | `is_locked` is never 1 on a largerβsmaller edge in any training frame | Hard (on training distribution) | |
|
|
| ### Node feature layout (270-D) |
|
|
| ``` |
| [0 : 256] SAM2 embedding (256) |
| [256 : 259] 3D position (3) |
| [259 : 269] type encoding (10) β fixed 10-D vector from |
| config/type_encoding_<method>.yaml |
| (shared with Desktop) |
| [269] visibility (1) |
| ``` |
|
|
| Total: **270-D** β identical to Desktop. The 10-D encoding is domain-independent; unknown/unlisted types encode to a zero vector. |
|
|
| ### Mission metadata saved per episode |
|
|
| Every Hanoi `side_graph.json` carries `goal_prompt`, `mission_kind`, and `target_state` in addition to the fields shared with Desktop. Per-frame transitions (grasps, releases, re-stacks) are recorded as deltas in `frame_states[f]` with `constraints`, `visibility`, **and** `held` sub-dicts. |
|
|
| ### Hanoi episodes available |
|
|
| | Session | Episodes | Frames | Collection mode | Notes | |
| |---|---|---|---|---| |
| | `hanoi/session_hanoi_0415_190808` | 3 | 7,479 | manual + teleop | Initial Hanoi pilot: 1 Γ classical 15-move solve + 2 Γ single-ring moves | |
| | `hanoi/session_hanoi_0417_133613` | 7 | 10,968 | autonomous orchestrator | Initial 4-stack on peg B, 40/40/20 mission mix, 1-10 moves per episode | |
| | `hanoi/session_hanoi_0417_144403` | 20 | 30,942 | autonomous orchestrator | Initial 4-stack on peg A, 40/40/20 mission mix, 1-10 moves per episode | |
| | `hanoi/session_hanoi_0417_164816` | 20 | 64,185 | autonomous orchestrator | Initial 4-stack on peg C, minimum 3 moves per episode (no upper cap). `episode_18.zip` and `episode_19.zip` are stored as **zip archives** (see note below). | |
|
|
| Total across all Hanoi sessions: **50 episodes, 113,574 frames**. Each `episode_XX/metadata.json` records the exact `mission_kind`, `goal_prompt`, `initial_state`, `target_state`, and `solver_moves` for that episode. All autonomous sessions are produced by `scripts/hanoi/orchestrator.py`, which pre-plans all N missions upfront from the captured initial state, resamples any mission exceeding the per-episode move cap, and records a deterministic solver reference trajectory for each accepted mission. |
|
|
| **Zipped episodes.** The last two episodes of `session_hanoi_0417_164816` (`episode_18.zip`, `episode_19.zip`) are stored as uncompressed (`zip -0`) archives rather than expanded directory trees. HuggingFace datasets have a hard cap of 1 million files per repository, and expanding these two episodes would have exceeded it. Extract before use: |
|
|
| ```bash |
| cd hanoi/session_hanoi_0417_164816 |
| unzip episode_18.zip # β episode_18/ |
| unzip episode_19.zip # β episode_19/ |
| ``` |
|
|
| Once unzipped, the on-disk layout is identical to every other `episode_XX/` directory in this dataset (same `metadata.json`, `robot_states.npy`, `side/`, `wrist/`, `annotations/` tree, loadable by the exact same PyG loaders below). All other episodes in the dataset are stored as expanded directories and require no pre-processing. |
|
|
| ### Graph generation for Hanoi (reference) |
|
|
| The full pipeline that produced every `annotations/` tree above is checked in under `tools/hanoi_pipeline/` in this repo. For the pipeline overview, algorithm details, and SAM2 checkpoint stats see the **Pipeline** and **SAM2 models** sections above. For the single-frame runtime inferer (use it inside a world-model prediction loop to turn a predicted RGB back into a graph), see `tools/hanoi_pipeline/infer_graph_from_frame.py` and `tools/hanoi_pipeline/README.md`. |
|
|
| ### Per-frame graph retrieval β how it works (important) |
|
|
| **Every frame in every episode has its own distinct graph.** The dataset stores them as a (structural skeleton + per-frame deltas) decomposition rather than N JSON files per episode, because the skeleton is the same every frame and the deltas are small. This cuts ~6000Γ disk-space per episode while losing zero information β the loader reconstructs each frame's full graph on demand. |
|
|
| Where each piece of a per-frame graph lives: |
|
|
| | Component of the frame-T graph | File | |
| |---|---| |
| | Node list (which rings exist) + structural edges (smallerβlarger pairs) | `annotations/side_graph.json` β `components`, `edges` (shared across all frames) | |
| | `is_locked` / `visibility` / `held` **as of frame T** | `annotations/side_graph.json` β `frame_states` (delta-encoded up to T) | |
| | SAM2 mask of each ring at frame T | `annotations/side_masks/frame_TTTTTT.npz` | |
| | 256-D SAM2 embedding at frame T | `annotations/side_embeddings/frame_TTTTTT.npz` | |
| | 3D position (centroid) + bbox + depth-valid flag at frame T | `annotations/side_depth_info/frame_TTTTTT.npz` | |
| | Robot state at frame T | `robot_states.npy[T]` (13-D) | |
|
|
| The PyG loader combines these into a `torch_geometric.data.Data` object for exactly that frame β node features differ per frame (new embeddings + new 3D positions + new visibility flags), and edge features differ per frame (`is_locked` bits flip as rings are stacked / unstacked / held mid-transit). |
|
|
| **To get a distinct graph for every labeled frame in an episode:** use the `list_all_frame_graphs` helper below, or run `scripts/materialize_per_frame_graphs.py` to materialize them as individual `.pt` (and optional `.json`) files on disk. |
|
|
| #### Where edge-feature transitions live |
|
|
| The 3-D `edge_attr` vector is `[has_constraint, is_locked, src_blocks_dst]`. Of these, **only `is_locked` changes over time** β it flips when a ring lifts off / lands on another ring (or enters/exits the held state mid-transit). `has_constraint` and `src_blocks_dst` are static per edge. |
| |
| Every transition of `is_locked` (and every transition of `held`) is recorded as a **delta** in `side_graph.json` under `frame_states`. The key is the frame index at which the transition happens; the value lists exactly which entries changed. Example from a real Hanoi single-move episode: |
| |
| ```jsonc |
| "frame_states": { |
| "0": {"constraints": {"ring_1->ring_2": true, "ring_2->ring_3": true, |
| "ring_3->ring_4": true}}, // initial stack |
| "134": {"constraints": {"ring_1->ring_2": false}, // ring_1 lifted OFF ring_2 |
| "held": {"ring_1": true}}, // ring_1 now in transit |
| "278": {"constraints": {"ring_1->ring_3": true}, // ring_1 placed on ring_3 |
| "held": {"ring_1": false}} |
| } |
| ``` |
| |
| The loader's `resolve_frame_state(graph_json, T)` walks `frame_states` in ascending key order up to `T`, applies every listed constraint/held delta, and returns the **resolved state at frame T**. That resolved state then populates `edge_attr[:, 1]` (the `is_locked` column) and the `held` flags that zero out edges touching rings in transit. So for frame 200 in the example above, `ring_1->ring_2` is unlocked *and* every other edge touching `ring_1` is also unlocked (held-ring rule), whereas `ring_3->ring_4` is still locked (never changed). |
| |
| Bottom line: there's no separate edge-feature file per frame β the transitions are packed into one delta dict in `side_graph.json`, and the loader replays them to give you the exact `edge_attr` for whichever frame you ask for. |
| |
| ## Shared: PyG edge feature semantics (3-D, both domains) |
| |
| `edge_attr[k] = [has_constraint, is_locked, src_blocks_dst]` |
| |
| | `has_constraint` | `is_locked` | `src_blocks_dst` | Meaning | |
| |---|---|---|---| |
| | 0 | 0 | 0 | No physical constraint β message passing only. Used for: robot β anything; Hanoi larger β smaller (non-edge at the pair level) | |
| | 1 | 1 | 1 | Constraint active, src is the blocker (physical Desktop) / src rests on top (physical Hanoi) | |
| | 1 | 1 | 0 | Same pair, reverse direction β src is the blocked / src is underneath | |
| | 1 | 0 | 1 | Constraint released, src was the blocker / legal rest direction with no contact right now | |
| | 1 | 0 | 0 | Same released pair, reverse direction | |
| |
| **Symmetry invariants:** `has_constraint` and `is_locked` are symmetric per unordered pair (same value for `(i, j)` and `(j, i)`). `src_blocks_dst` flips between the two directions. Robot β anything edges are always `[0, 0, 0]`. |
| |
| ## Shared: Fixed 10-D type encoding β how it's made |
| |
| Across both domains the component-type universe is **13 types** (the two vocabularies unioned): |
| |
| ``` |
| cpu_fan, cpu_bracket, cpu, ram_clip, ram, connector, graphic_card, motherboard, |
| ring_1, ring_2, ring_3, ring_4, robot |
| ``` |
| |
| Each type is assigned a **fixed 10-D vector**. The encoding is **NOT trained** β it is a deterministic lookup read from a YAML at load time, so any consumer of the dataset gets the exact same node features bit-for-bit. Two methods are provided; both YAMLs live at the dataset repo root alongside the session directories: |
| |
| | Method | YAML file | How vectors are built | Semantic structure | |
| |---|---|---|---| |
| | `random` | `config/type_encoding_random.yaml` | `numpy.random.default_rng(42)` unit-norm 10-vectors, one per type | None β vectors are orthogonal-ish noise | |
| | `clip` | `config/type_encoding_clip.yaml` | CLIP ViT-B/32 text embedding of a humanised prompt (e.g. `"a CPU fan"`, `"a small red ring"`) β PCA to 10 β unit-normalise | Related types cluster (the four rings are close; the fan/bracket/cpu cluster is tight) | |
| |
| **Unknown type β 10-D zero vector.** If a component's `type` is not in the YAML, the loader returns `np.zeros(10, dtype=np.float32)` for that slot. This keeps node dim at 270 regardless of vocabulary drift. |
|
|
| **To reproduce or extend:** download whichever YAML you want from the dataset repo root, load it with `yaml.safe_load`, and look up each component's type. The loader code below shows the full pattern. |
|
|
| ## Shared: PyG loader β self-contained Python |
|
|
| ### Prerequisites |
|
|
| ```bash |
| pip install torch numpy torch_geometric pillow pyyaml |
| ``` |
|
|
| ### Save as `gnn_world_model_loader.py` |
| |
| The key design property: `node_dim = 256 + 3 + 10 + 1 = 270` for both domains. The 10-D type slot comes from the fixed YAML encoding (loaded once), so there's no domain branching β Desktop, Hanoi, and any future vocabulary all produce 270-D nodes. |
|
|
| ```python |
| import json |
| from dataclasses import dataclass |
| from functools import lru_cache |
| from pathlib import Path |
| from typing import Dict, List, Optional |
| import numpy as np |
| import torch |
| import yaml |
| from torch_geometric.data import Data |
| |
| # ---------- constants ---------- |
| TYPE_ENCODING_DIM = 10 # fixed, domain-independent |
| SAM2_EMB_DIM = 256 |
| POS_DIM = 3 |
| VIS_DIM = 1 |
| NODE_DIM = SAM2_EMB_DIM + POS_DIM + TYPE_ENCODING_DIM + VIS_DIM # = 270 |
| ROBOT_STATE_DIM = 13 # [j0..j5, tcp_x, tcp_y, tcp_z, tcp_rx, tcp_ry, tcp_rz, gripper_pos] |
| |
| |
| # ---------- fixed type encoding ---------- |
| # Download once from the dataset repo root: |
| # config/type_encoding_random.yaml (seeded numpy unit vectors, seed=42) |
| # config/type_encoding_clip.yaml (CLIP ViT-B/32 text β PCA(10) β unit-norm) |
| # Point TYPE_ENCODING_ROOT at wherever you saved them. |
| TYPE_ENCODING_ROOT = Path("./config") |
| |
| |
| @lru_cache(maxsize=4) |
| def load_type_encoding(encoding_method: str = "random") -> Dict[str, np.ndarray]: |
| """Load the fixed 10-D per-type encoding from YAML. Cached across calls.""" |
| path = TYPE_ENCODING_ROOT / f"type_encoding_{encoding_method}.yaml" |
| with open(path) as f: |
| raw = yaml.safe_load(f) |
| return {k: np.asarray(v, dtype=np.float32) for k, v in raw.items()} |
| |
| |
| def type_encode(comp_type: str, encoding_method: str = "random") -> np.ndarray: |
| """Return 10-D vector for `comp_type`; zeros for unknown types.""" |
| table = load_type_encoding(encoding_method) |
| vec = table.get(comp_type) |
| if vec is None: |
| return np.zeros(TYPE_ENCODING_DIM, dtype=np.float32) |
| return vec.astype(np.float32) |
| |
| |
| # ---------- file helpers ---------- |
| def list_labeled_frames(episode_dir: Path) -> List[int]: |
| mask_dir = episode_dir / "annotations" / "side_masks" |
| if not mask_dir.exists(): |
| return [] |
| frames = [] |
| for p in mask_dir.glob("frame_*.npz"): |
| try: |
| frames.append(int(p.stem.split("_")[1])) |
| except (ValueError, IndexError): |
| continue |
| return sorted(frames) |
| |
| |
| def resolve_frame_state(graph_json: dict, frame_idx: int): |
| constraints, visibility = {}, {} |
| for c in graph_json["components"]: |
| visibility[c["id"]] = True |
| for e in graph_json["edges"]: |
| constraints[f"{e['src']}->{e['dst']}"] = True |
| fs_dict = graph_json.get("frame_states", {}) |
| for f in sorted([int(k) for k in fs_dict]): |
| if f > frame_idx: |
| break |
| fs = fs_dict[str(f)] |
| for k, v in fs.get("constraints", {}).items(): |
| constraints[k] = v |
| for k, v in fs.get("visibility", {}).items(): |
| visibility[k] = v |
| return constraints, visibility |
| |
| |
| @dataclass |
| class FrameData: |
| graph: dict |
| masks: dict |
| embeddings: dict |
| depth_info: dict |
| robot: Optional[dict] |
| constraints: dict |
| visibility: dict |
| |
| |
| def load_frame_data(episode_dir, frame_idx): |
| anno = Path(episode_dir) / "annotations" |
| with open(anno / "side_graph.json") as f: |
| graph = json.load(f) |
| def _npz(p): |
| if not p.exists(): return {} |
| d = np.load(p) |
| return {k: d[k] for k in d.files} |
| masks = _npz(anno / "side_masks" / f"frame_{frame_idx:06d}.npz") |
| embeddings = _npz(anno / "side_embeddings" / f"frame_{frame_idx:06d}.npz") |
| depth_info = _npz(anno / "side_depth_info" / f"frame_{frame_idx:06d}.npz") |
| robot = None |
| rp = anno / "side_robot" / f"frame_{frame_idx:06d}.npz" |
| if rp.exists(): |
| r = np.load(rp) |
| if r["visible"][0] == 1: |
| robot = {k: r[k] for k in r.files} |
| constraints, visibility = resolve_frame_state(graph, frame_idx) |
| return FrameData(graph, masks, embeddings, depth_info, robot, constraints, visibility) |
| |
| |
| def _build_product_node_features(nodes, fd, encoding_method): |
| feats = [] |
| for node in nodes: |
| cid = node["id"] |
| emb = fd.embeddings.get(cid, np.zeros(SAM2_EMB_DIM, dtype=np.float32)) |
| dvk = f"{cid}_depth_valid"; ck = f"{cid}_centroid" |
| if dvk in fd.depth_info and int(fd.depth_info[dvk][0]) == 1: |
| pos = fd.depth_info[ck].astype(np.float32) |
| else: |
| pos = np.zeros(POS_DIM, dtype=np.float32) |
| vis = 1.0 if fd.visibility.get(cid, True) else 0.0 |
| if vis == 0.0: |
| emb = np.zeros(SAM2_EMB_DIM, dtype=np.float32) |
| pos = np.zeros(POS_DIM, dtype=np.float32) |
| feats.append(np.concatenate([ |
| emb.astype(np.float32), |
| pos, |
| type_encode(node["type"], encoding_method), |
| np.array([vis], dtype=np.float32), |
| ])) |
| if not feats: |
| return torch.empty((0, NODE_DIM), dtype=torch.float32) |
| return torch.tensor(np.stack(feats), dtype=torch.float32) |
| |
| |
| def _build_product_edges(nodes, graph, fd): |
| N = len(nodes) |
| constraint_set = {(e["src"], e["dst"]) for e in graph["edges"]} |
| pair_forward = {frozenset([s, d]): (s, d) for s, d in constraint_set} |
| src_idx, dst_idx, edge_attr = [], [], [] |
| for i in range(N): |
| for j in range(N): |
| if i == j: continue |
| src_id, dst_id = nodes[i]["id"], nodes[j]["id"] |
| src_idx.append(i); dst_idx.append(j) |
| key = frozenset([src_id, dst_id]) |
| if key in pair_forward: |
| fwd = pair_forward[key] |
| is_locked = fd.constraints.get(f"{fwd[0]}->{fwd[1]}", True) |
| sb = 1.0 if src_id == fwd[0] else 0.0 |
| edge_attr.append([1.0, 1.0 if is_locked else 0.0, sb]) |
| else: |
| edge_attr.append([0.0, 0.0, 0.0]) |
| return src_idx, dst_idx, edge_attr |
| |
| |
| # ---------- 1) products-only (Option 1: direct graph encoding) ---------- |
| def load_pyg_frame_products_only(episode_dir, frame_idx, encoding_method: str = "random"): |
| fd = load_frame_data(episode_dir, frame_idx) |
| nodes = fd.graph["components"] |
| x = _build_product_node_features(nodes, fd, encoding_method) |
| src, dst, ea = _build_product_edges(nodes, fd.graph, fd) |
| return Data( |
| x=x, |
| edge_index=torch.tensor([src, dst], dtype=torch.long), |
| edge_attr=torch.tensor(ea, dtype=torch.float32), |
| y=torch.tensor([frame_idx], dtype=torch.long), |
| num_nodes=len(nodes), |
| ) |
| |
| |
| # ---------- 2) V2 ablation: robot as graph NODE (Desktop only) ---------- |
| def load_pyg_frame_with_robot(episode_dir, frame_idx, encoding_method: str = "random"): |
| fd = load_frame_data(episode_dir, frame_idx) |
| # Hanoi has no robot mask/embedding in v1 β fall back to products-only. |
| if fd.robot is None: |
| return load_pyg_frame_products_only(episode_dir, frame_idx, encoding_method) |
| |
| products = fd.graph["components"] |
| N_prod = len(products); N = N_prod + 1 |
| |
| x_prod = _build_product_node_features(products, fd, encoding_method) |
| robot_emb = fd.robot["embedding"].astype(np.float32) |
| robot_pos = (fd.robot["centroid"].astype(np.float32) |
| if int(fd.robot["depth_valid"][0]) == 1 |
| else np.zeros(POS_DIM, dtype=np.float32)) |
| robot_feat = np.concatenate([ |
| robot_emb, robot_pos, |
| type_encode("robot", encoding_method), |
| np.array([1.0], dtype=np.float32), |
| ]) |
| x = torch.cat([x_prod, torch.tensor(robot_feat, dtype=torch.float32).unsqueeze(0)], dim=0) |
| |
| src, dst, ea = _build_product_edges(products, fd.graph, fd) |
| robot_idx = N_prod |
| for i in range(N_prod): |
| src.append(robot_idx); dst.append(i); ea.append([0.0, 0.0, 0.0]) |
| src.append(i); dst.append(robot_idx); ea.append([0.0, 0.0, 0.0]) |
| |
| data = Data( |
| x=x, |
| edge_index=torch.tensor([src, dst], dtype=torch.long), |
| edge_attr=torch.tensor(ea, dtype=torch.float32), |
| y=torch.tensor([frame_idx], dtype=torch.long), |
| num_nodes=N, |
| ) |
| data.robot_point_cloud = torch.tensor(fd.robot["point_cloud"], dtype=torch.float32) |
| data.robot_pixel_coords = torch.tensor(fd.robot["pixel_coords"], dtype=torch.int32) |
| data.robot_mask = torch.tensor(fd.robot["mask"], dtype=torch.uint8) |
| return data |
| |
| |
| # ---------- 3) V3 recommended: products graph + robot_state side-tensor ---------- |
| def load_pyg_frame_with_robot_state(episode_dir, frame_idx, encoding_method: str = "random"): |
| data = load_pyg_frame_products_only(episode_dir, frame_idx, encoding_method) |
| robot_states = np.load(Path(episode_dir) / "robot_states.npy") # (T, 13) float32 |
| rs = robot_states[frame_idx].astype(np.float32) # 13-D |
| data.robot_state = torch.tensor(rs, dtype=torch.float32) |
| return data |
| |
| |
| # ---------- 4) V3 action-conditioned: + robot_action delta ---------- |
| def load_pyg_frame_with_robot_action(episode_dir, frame_idx, encoding_method: str = "random"): |
| data = load_pyg_frame_with_robot_state(episode_dir, frame_idx, encoding_method) |
| robot_states = np.load(Path(episode_dir) / "robot_states.npy") # (T, 13) |
| T = robot_states.shape[0] |
| if frame_idx + 1 < T: |
| action = robot_states[frame_idx + 1] - robot_states[frame_idx] |
| else: |
| action = np.zeros(ROBOT_STATE_DIM, dtype=np.float32) |
| data.robot_action = torch.tensor(action.astype(np.float32), dtype=torch.float32) |
| return data |
| |
| |
| # ---------- 5) Generator: one distinct graph per labeled frame ---------- |
| _VARIANTS = { |
| "products_only": load_pyg_frame_products_only, |
| "with_robot": load_pyg_frame_with_robot, |
| "with_robot_state": load_pyg_frame_with_robot_state, |
| "with_robot_action": load_pyg_frame_with_robot_action, |
| } |
| |
| |
| def list_all_frame_graphs( |
| episode_dir, |
| variant: str = "with_robot_state", |
| encoding_method: str = "random", |
| ): |
| """Yield (frame_idx, Data) for every labeled frame in an episode. |
| |
| Each `Data` object is the full per-frame graph (node features, edges, |
| edge features, and any requested side tensors). Feature values and |
| `is_locked` bits differ per frame as rings move / stack / get held. |
| """ |
| if variant not in _VARIANTS: |
| raise ValueError(f"variant must be one of {list(_VARIANTS)}, got {variant!r}") |
| loader = _VARIANTS[variant] |
| for f in list_labeled_frames(Path(episode_dir)): |
| yield f, loader(episode_dir, f, encoding_method=encoding_method) |
| ``` |
|
|
| ### Usage examples |
|
|
| All four loaders share the signature `(episode_dir, frame_idx, encoding_method="random")`. Swap `"random"` for `"clip"` to use the CLIP-derived encoding instead. |
|
|
| **Desktop V1** β 15 product nodes, 270-D features, fully-connected edges (15Γ14 = 210): |
|
|
| ```python |
| from pathlib import Path |
| from gnn_world_model_loader import load_pyg_frame_products_only |
| |
| episode = Path("session_0408_162129/episode_00") |
| data = load_pyg_frame_products_only(episode, frame_idx=42) |
| print(data) |
| # β Data(x=[15, 270], edge_index=[2, 210], edge_attr=[210, 3]) |
| ``` |
|
|
| **Desktop V3 (recommended)** β same graph + 13-D robot_state side-tensor: |
| |
| ```python |
| from gnn_world_model_loader import load_pyg_frame_with_robot_state |
| |
| data = load_pyg_frame_with_robot_state(episode, frame_idx=42) |
| print(data) |
| # β Data(x=[15, 270], edge_index=[2, 210], edge_attr=[210, 3], robot_state=[13]) |
| ``` |
| |
| **Desktop V3 action-conditioned** β adds 13-D delta for the next frame: |
| |
| ```python |
| from gnn_world_model_loader import load_pyg_frame_with_robot_action |
|
|
| data = load_pyg_frame_with_robot_action(episode, frame_idx=42) |
| # β Data(x=[15, 270], edge_index=[2, 210], edge_attr=[210, 3], |
| # robot_state=[13], robot_action=[13]) |
| ``` |
| |
| **Hanoi V1** β 4 ring nodes, 270-D features, 12 fully-connected edges: |
| |
| ```python |
| episode = Path("hanoi/session_hanoi_0415_190808/episode_00") |
| data = load_pyg_frame_products_only(episode, frame_idx=250) |
| print(data) |
| # β Data(x=[4, 270], edge_index=[2, 12], edge_attr=[12, 3]) |
| ``` |
| |
| **Hanoi V3 (recommended)** β V3 works for Hanoi too because `robot_states.npy` is recorded for every episode: |
|
|
| ```python |
| data = load_pyg_frame_with_robot_state(episode, frame_idx=250) |
| print(data) |
| # β Data(x=[4, 270], edge_index=[2, 12], edge_attr=[12, 3], robot_state=[13]) |
| ``` |
|
|
| **V2 note.** `load_pyg_frame_with_robot` falls back to `load_pyg_frame_products_only` on Hanoi (no robot mask), so for Hanoi V1 and V2 return identical graphs. On Desktop V2 attaches the robot as a 16-th node (x shape becomes `[16, 270]`). |
|
|
| ## How to use this dataset β full instructions |
|
|
| The sections below walk through every common task from scratch. All examples target the Hanoi subset (`hanoi/`), which is the more heavily instrumented of the two domains. |
|
|
| ### Step 0 β Download and set up |
|
|
| ```bash |
| pip install huggingface_hub torch torch_geometric numpy pyyaml opencv-python pillow |
| |
| # Pull the whole dataset (~150 GB) β or use allow_patterns to slim it down |
| hf download ChangChrisLiu/GNN_Disassembly_WorldModel --repo-type dataset --local-dir ./gnn_world_model |
| |
| # Or cherry-pick just a few Hanoi episodes: |
| hf download ChangChrisLiu/GNN_Disassembly_WorldModel --repo-type dataset \ |
| --include "hanoi/session_hanoi_0415_190808/episode_00/*" \ |
| "hanoi/session_hanoi_0415_190808/episode_00/**/*" \ |
| "config/type_encoding_*.yaml" \ |
| --local-dir ./gnn_world_model |
| |
| cd gnn_world_model |
| ``` |
|
|
| Unzip the two zipped episodes (only `episode_18.zip` and `episode_19.zip` in `session_hanoi_0417_164816` are zipped; all others are expanded): |
|
|
| ```bash |
| cd hanoi/session_hanoi_0417_164816 |
| unzip episode_18.zip # β episode_18/ |
| unzip episode_19.zip # β episode_19/ |
| cd ../.. |
| ``` |
|
|
| Save the loader code from the [PyG loader](#shared-pyg-loader--self-contained-python) section above as `gnn_world_model_loader.py` in the dataset root so `from gnn_world_model_loader import ...` resolves. The loader reads `./config/type_encoding_*.yaml`, so make sure both YAMLs are in place. |
|
|
| ### Step 1 β Load one episode and inspect its per-frame graphs |
|
|
| Every labeled frame produces a distinct `torch_geometric.data.Data` object. The following script loads one Hanoi episode, picks a middle frame, shows the full graph, and iterates over the first few frames to demonstrate that `is_locked` bits change over time: |
|
|
| ```python |
| from pathlib import Path |
| from gnn_world_model_loader import ( |
| load_pyg_frame_with_robot_state, |
| list_labeled_frames, |
| list_all_frame_graphs, |
| ) |
| |
| episode = Path("hanoi/session_hanoi_0415_190808/episode_00") |
| |
| # 1a. All labeled frame indices for this episode |
| frames = list_labeled_frames(episode) |
| print(f"{len(frames)} labeled frames ({frames[0]} .. {frames[-1]})") |
| |
| # 1b. Load one specific frame |
| frame_idx = frames[len(frames) // 2] |
| data = load_pyg_frame_with_robot_state(episode, frame_idx, encoding_method="random") |
| print(data) |
| # β Data(x=[4, 270], edge_index=[2, 12], edge_attr=[12, 3], robot_state=[13], ...) |
| print("is_locked :", data.edge_attr[:, 1].tolist()) |
| print("src_blocks :", data.edge_attr[:, 2].tolist()) |
| |
| # 1c. Iterate all frames β each Data carries that frame's exact state |
| for f, g in list_all_frame_graphs(episode, variant="with_robot_state"): |
| locked = int(g.edge_attr[:, 1].sum().item()) |
| print(f"frame {f:6d} locked_edges={locked}/12") |
| ``` |
|
|
| The `variant` argument picks which of the four loader signatures to use: |
| - `"products_only"` β graph alone (no robot info) |
| - `"with_robot"` β Desktop V2 (Hanoi falls back to products-only) |
| - `"with_robot_state"` β graph + 13-D `robot_state` side tensor (**recommended for both domains**) |
| - `"with_robot_action"` β also adds a 13-D `robot_action` (next-frame delta) |
|
|
| ### Step 2 β Build a training DataLoader and train a GNN |
|
|
| Concatenate frames across any number of episodes into a plain list of `Data`, hand it to PyG's `DataLoader`, and you have batched mini-batches. This full training skeleton also shows the Rule-2 soft-compliance loss (discouraging the model from ever predicting `is_locked=1` on a largerβsmaller edge): |
|
|
| ```python |
| from pathlib import Path |
| from typing import List |
| import torch |
| import torch.nn.functional as F |
| from torch_geometric.data import Data |
| from torch_geometric.loader import DataLoader |
| from torch_geometric.nn import GATConv |
| from gnn_world_model_loader import ( |
| list_all_frame_graphs, |
| NODE_DIM, # = 270 |
| ROBOT_STATE_DIM, # = 13 |
| ) |
| |
| # 2a. Build the dataset β concatenate every frame of every selected episode. |
| def build_hanoi_dataset(roots: List[Path]) -> List[Data]: |
| return [g for ep in roots for _, g in list_all_frame_graphs(ep, variant="with_robot_state")] |
| |
| hanoi_root = Path("hanoi") |
| episodes = sorted( |
| ep for sess in hanoi_root.glob("session_hanoi_*") for ep in sess.glob("episode_*") if ep.is_dir() |
| ) |
| samples = build_hanoi_dataset(episodes[:5]) # first 5 episodes as a quick smoke-test |
| loader = DataLoader(samples, batch_size=32, shuffle=True) |
| |
| # 2b. A minimal GNN head that predicts per-edge `is_locked`. |
| class IsLockedPredictor(torch.nn.Module): |
| def __init__(self, node_dim=NODE_DIM, edge_dim=3, hidden=128, robot_dim=ROBOT_STATE_DIM): |
| super().__init__() |
| self.gat1 = GATConv(node_dim + robot_dim, hidden, heads=4, concat=True, edge_dim=edge_dim) |
| self.gat2 = GATConv(hidden * 4, hidden, heads=1, edge_dim=edge_dim) |
| self.edge_head = torch.nn.Sequential( |
| torch.nn.Linear(2 * hidden, hidden), torch.nn.ReLU(), |
| torch.nn.Linear(hidden, 1), |
| ) |
| |
| def forward(self, data: Data): |
| # PyG concatenates 1-D per-graph attrs along dim 0 (default __cat_dim__ = 0), |
| # so after batching data.robot_state has shape [num_graphs * 13]. Reshape to |
| # [num_graphs, 13] and broadcast to every node via data.batch. |
| robot = data.robot_state.view(-1, ROBOT_STATE_DIM)[data.batch] # [N_total, 13] |
| x = torch.cat([data.x, robot], dim=-1) |
| x = self.gat1(x, data.edge_index, data.edge_attr).relu() |
| x = self.gat2(x, data.edge_index, data.edge_attr) |
| src, dst = data.edge_index |
| return self.edge_head(torch.cat([x[src], x[dst]], dim=-1)).squeeze(-1) |
| |
| # 2c. Training loop with BCE loss on `is_locked` plus a Rule-2 compliance term. |
| device = "cuda" if torch.cuda.is_available() else "cpu" |
| model = IsLockedPredictor().to(device) |
| opt = torch.optim.AdamW(model.parameters(), lr=3e-4) |
| |
| for epoch in range(3): |
| for batch in loader: |
| batch = batch.to(device) |
| logits = model(batch) # [E_total] |
| target = batch.edge_attr[:, 1] # ground-truth is_locked |
| ce = F.binary_cross_entropy_with_logits(logits, target) |
| # Rule-2: penalise predicting locked=1 on an illegal (largerβsmaller) edge. |
| legal = batch.edge_attr[:, 2] |
| rule2 = (torch.sigmoid(logits) * (1 - legal)).mean() |
| loss = ce + 0.1 * rule2 |
| opt.zero_grad(); loss.backward(); opt.step() |
| print(f"epoch {epoch} ce={ce.item():.4f} rule2={rule2.item():.4f}") |
| ``` |
|
|
| ### Step 3 β Inference: turn a predicted RGB into a graph |
|
|
| When your world model has generated a future RGB (and optionally a matching depth), use the **single-frame inferer** to produce the same graph schema you trained on. It loads SAM2 base plus the Hanoi-FT decoder once, then maps an image to `{graph, masks, embeddings, depth_info, ring_states}` with no temporal context required. |
|
|
| ```python |
| import cv2 |
| import numpy as np |
| from tools.hanoi_pipeline.infer_graph_from_frame import HanoiGraphInferer |
| |
| inferer = HanoiGraphInferer() # loads SAM2 base + sam2_hanoi_ft.pt |
| |
| # A real frame from the dataset is a fine sanity-check input. |
| rgb = cv2.cvtColor(cv2.imread( |
| "hanoi/session_hanoi_0415_190808/episode_00/side/rgb/frame_000100.png"), |
| cv2.COLOR_BGR2RGB) |
| depth = np.load( |
| "hanoi/session_hanoi_0415_190808/episode_00/side/depth/frame_000100.npy") # uint16 mm |
| |
| result = inferer(rgb, depth=depth) |
| |
| # Five-field output. Schema matches the offline pipeline exactly. |
| # result["graph"] β same dict as side_graph.json (frame_states empty) |
| # result["masks"] β {"ring_1".."ring_4": (H, W) uint8} |
| # result["embeddings"] β {"ring_1".."ring_4": (256,) float32} |
| # result["depth_info"] β flat-keyed 3D bundle (centroids, point clouds, bboxes) |
| # result["ring_states"] β {"ring_id": RingState(peg, stack_index)} |
| ``` |
|
|
| Convert the result to a PyG `Data` that matches the training format: |
|
|
| ```python |
| import torch |
| from gnn_world_model_loader import ( |
| NODE_DIM, SAM2_EMB_DIM, POS_DIM, type_encode, |
| ) |
| |
| components = result["graph"]["components"] |
| feats = [] |
| for c in components: |
| cid = c["id"] |
| emb = result["embeddings"][cid].astype(np.float32) |
| centroid_key = f"{cid}_centroid" |
| pos = (result["depth_info"][centroid_key].astype(np.float32) |
| if centroid_key in result["depth_info"] |
| else np.zeros(POS_DIM, dtype=np.float32)) |
| feats.append(np.concatenate([ |
| emb, pos, type_encode(c["type"]), np.array([1.0], dtype=np.float32), |
| ])) |
| x = torch.tensor(np.stack(feats), dtype=torch.float32) # [4, 270] for Hanoi |
| |
| # Fully-connected NΓ(N-1) edges with has_constraint / src_blocks_dst β reuse the |
| # same _build_product_edges helper from the loader module that the training |
| # pipeline uses, or expand manually from result["graph"]["edges"]. |
| ``` |
|
|
| The same `HanoiGraphInferer` can be pointed at a different fine-tuned checkpoint via the `SAM2_FINETUNE_CKPT` environment variable, or set to the empty string to force vanilla SAM2. |
|
|
| ### Step 4 β Auto-label a freshly-captured session |
|
|
| If you collect new Hanoi data using the source repo's orchestrator, run the bundled auto-labeler to produce the full `annotations/` tree. That's all that's needed β the PyG loaders above then work on the new session unchanged. |
|
|
| ```bash |
| # (optional β in the source repo https://github.com/ChangChrisLiu/gnn-world-model) |
| # Collect a fresh session: |
| # python scripts/hanoi/orchestrator.py --n-episodes 20 --data-root /path/to/sessions |
| |
| # Auto-label the captured session β this is what ships with the dataset: |
| python tools/hanoi_pipeline/scripts/hanoi/auto_label.py \ |
| /path/to/sessions/session_hanoi_<date>_<time>/ |
| ``` |
|
|
| `auto_label.py` produces, for every episode: |
|
|
| - `annotations/side_masks/frame_XXXXXX.npz` β SAM2 masks (Hanoi-FT auto-selected if present) |
| - `annotations/side_embeddings/frame_XXXXXX.npz` β 256-D pooled SAM2 embeddings |
| - `annotations/side_depth_info/frame_XXXXXX.npz` β 3D positions, bboxes, depth-valid flags |
| - `annotations/side_robot/frame_XXXXXX.npz` β robot bundle (zero-filled in Hanoi v1 for format uniformity) |
| - `annotations/side_graph.json` β structural edges + `frame_states` deltas derived from `solver_moves` + the gripper-based held-interval detection |
| - `annotations/dataset_card.json` β schema pointer |
|
|
| Then the usual pipeline: |
|
|
| ```python |
| from gnn_world_model_loader import list_all_frame_graphs |
| for f, g in list_all_frame_graphs("/path/to/sessions/session_hanoi_<date>_<time>/episode_00"): |
| print(f, g) |
| ``` |
|
|
| ### Step 5 β Retrain the SAM2 Hanoi-FT checkpoint on your own labels |
|
|
| After you've corrected enough frames in the browser UI (step 6), the source-repo training harness pulls `(image, bbox, ground-truth-mask)` triples into a `samples.jsonl` and fine-tunes SAM2's decoder + prompt_encoder (the encoder stays frozen): |
| |
| ```bash |
| # from source repo: https://github.com/ChangChrisLiu/gnn-world-model |
| |
| # 5a. Collect triples. Prefer collect_hanoi_from_sessions.py for native Hanoi |
| # sessions under data/hanoi/ β it accepts explicit --episode, --val-episode, |
| # or --all-episodes, and writes a JSONL samples file. |
| python scripts/sam2_finetune/collect_hanoi_from_sessions.py --all-episodes \ |
| --out data/sam2_finetune_hanoi/samples.jsonl |
| |
| # 5b. Fine-tune. Encoder stays frozen; only decoder + prompt_encoder update. |
| python scripts/sam2_finetune/train.py \ |
| --samples data/sam2_finetune_hanoi/samples.jsonl \ |
| --out tools/hanoi_pipeline/checkpoints/sam2_hanoi_ft.pt \ |
| --epochs 25 --lr 1e-4 |
| ``` |
| |
| On the next run, both `auto_label.py` and `HanoiGraphInferer()` pick up the new checkpoint automatically from `tools/hanoi_pipeline/checkpoints/sam2_hanoi_ft.pt`. Set `SAM2_FINETUNE_CKPT=<path>` to override, or set it to an empty string to force vanilla SAM2. |
|
|
| ### Step 6 β Verify / correct labels in the browser UI (source repo) |
|
|
| The correction UI is a web app (React + FastAPI) that lives in the source repo β it's not bundled here because it's not just a Python module. Clone the source, start the server, and open it: |
|
|
| ```bash |
| # source repo |
| git clone https://github.com/ChangChrisLiu/gnn-world-model |
| cd gnn-world-model |
| bash scripts/run_annotator.sh --hanoi |
| # β browse to http://localhost:8000 |
| ``` |
|
|
| The UI loads any labeled Hanoi episode under `data/hanoi/` and lets you fix masks frame-by-frame with bbox / point / brush / eraser / polygon tools. Save writes back to the same `annotations/side_masks/*.npz` files. The format does not change pre- vs post-correction, so downstream loaders are unaffected. The only piece of the UI bundled in the dataset is `tools/hanoi_pipeline/src/annotator/labeling_server.py`, which is the SAM2 backend reused by `infer_graph_from_frame.py`. |
|
|
| ### Step 7 β Materialize per-frame graphs to disk (optional, for debugging) |
|
|
| For offline inspection, non-PyTorch consumers, or diff-friendly JSON, the `materialize_per_frame_graphs.py` script writes one `.pt` (and optional `.json`) file per labeled frame: |
|
|
| ```bash |
| python tools/hanoi_pipeline/scripts/materialize_per_frame_graphs.py \ |
| hanoi/session_hanoi_0415_190808/episode_00 \ |
| --out ./per_frame_graphs \ |
| --variant with_robot_state \ |
| --also-json |
| ``` |
|
|
| Reload: |
|
|
| ```python |
| import torch |
| data = torch.load("per_frame_graphs/frame_000100.pt", weights_only=False) |
| print(data) # Data(x=[4, 270], edge_index=[2, 12], edge_attr=[12, 3], robot_state=[13]) |
| print("is_locked:", data.edge_attr[:, 1].tolist()) |
| ``` |
|
|
| To iterate in-process without touching disk, `list_all_frame_graphs(episode_dir, variant="with_robot_state")` yields the same `(frame_idx, Data)` pairs directly. |
|
|
| ## Shared: common v3 file schemas |
|
|
| ### `side_graph.json` |
| |
| ```jsonc |
| { |
| "episode_id": "episode_00", |
| "goal_component": "ring_1", // Desktop: a product id; Hanoi: a ring id |
| "view": "side", |
| "components": [ |
| {"id": "ring_1", "type": "ring_1", "color": "#FF0000"} |
| ], |
| "edges": [ |
| {"src": "ring_1", "dst": "ring_3", "directed": true} |
| ], |
| "frame_states": { |
| "0": {"constraints": {"ring_1->ring_3": true}, "visibility": {"ring_1": true}, "held": {}}, |
| "120": {"constraints": {"ring_1->ring_3": false}, "held": {"ring_1": true}} |
| }, |
| "node_positions": {"ring_1": [640, 360]}, |
| "type_vocab": ["ring_1", "ring_2", "ring_3", "ring_4"], // Hanoi v1 β no robot |
| "embedding_dim": 256, |
| "feature_extractor": "sam2.1_hiera_base_plus", |
| |
| // Hanoi-only extras: |
| "goal_prompt": "Move the red ring to peg B", |
| "mission_kind": "single_ring", |
| "target_state": {"peg_A": [], "peg_B": ["ring_1"], "peg_C": []} |
| } |
| ``` |
| |
| ### `side_depth_info/frame_XXXXXX.npz` β 7 flat keys per component |
| |
| | Key | Shape | Dtype | Meaning | |
| |---|---|---|---| |
| | `{cid}_point_cloud` | (N, 3) | float32 | 3D points in camera frame (m). (0, 3) if no valid depth | |
| | `{cid}_pixel_coords` | (N, 2) | int32 | (u, v) of valid depth pixels | |
| | `{cid}_raw_depths_mm` | (N,) | uint16 | Filtered to [50, 2000] | |
| | `{cid}_centroid` | (3,) | float32 | Mean of `point_cloud`; `[0,0,0]` if invalid | |
| | `{cid}_bbox_2d` | (4,) | int32 | `[x1, y1, x2, y2]` from mask | |
| | `{cid}_area` | (1,) | int32 | Mask pixel count | |
| | `{cid}_depth_valid` | (1,) | uint8 | 1 if N > 0 else 0 | |
| |
| ### `side_robot/frame_XXXXXX.npz` β always 10 keys |
| |
| | Key | Shape | Dtype | Meaning | |
| |---|---|---|---| |
| | `visible` | (1,) | uint8 | 1 if robot labeled, 0 otherwise | |
| | `mask` | (H, W) | uint8 | Binary mask | |
| | `embedding` | (256,) | float32 | SAM2 256-D | |
| | `point_cloud` | (N, 3) | float32 | 3D points (m) | |
| | `pixel_coords` | (N, 2) | int32 | (u, v) | |
| | `raw_depths_mm` | (N,) | uint16 | mm | |
| | `centroid` | (3,) | float32 | Mean of point cloud | |
| | `bbox_2d` | (4,) | int32 | From mask | |
| | `area` | (1,) | int32 | Pixel count | |
| | `depth_valid` | (1,) | uint8 | 1 if N > 0 else 0 | |
| |
| ## Recording hardware |
| |
| UR5e + Robotiq 2F-85 gripper; static-mounted Luxonis OAK-D Pro side view with intrinsics `fx = 1033.8`, `fy = 1033.7`, `cx = 632.9`, `cy = 359.9`; recording at 30 Hz, 1280 Γ 720 RGB and uint16 depth (mm) filtered to `[50, 2000]`. |
| |
| ## License |
| |
| Released under **CC BY 4.0**. Use, share, and adapt freely with attribution. |
| |
| ## Acknowledgements |
| |
| - [Segment Anything Model 2 (SAM2)](https://github.com/facebookresearch/sam2) by Meta AI |
| - [PyTorch Geometric](https://pytorch-geometric.readthedocs.io/) |
| - [Hugging Face Datasets](https://huggingface.co/docs/datasets) |
| - Source code: https://github.com/ChangChrisLiu/gnn-world-model |
| |