React / examples /README.md
yxma's picture
examples/: upgraded ReactWindowDataset (adds motion filter to catch operator-paused windows the bad_frames check cant); canonical self-contained demo_react_window.py (no twm dependency); new examples/README.md with four-filter explanation and recipes per use case
cc62065 verified
|
raw
history blame
5.33 kB

React — usage examples

Reference code for sampling clean training windows from this dataset. Use these examples (or copy their patterns) to avoid sampling on top of known data-quality issues.

What's in here

File Purpose
react_window_dataset.py A PyTorch Dataset that yields short multimodal windows with all four quality filters applied at enumeration time. Drop-in usable.
demo_react_window.py End-to-end usage example — builds the dataset, prints one sample's structure, renders a static grid of N random windows as a PNG.

What the dataloader filters out

The published .pt files have already had OT-uninitialized recording prefixes trimmed (those bad spans were before the dataloader ever sees the data — see docs/caveats.md). On top of that, ReactWindowDataset applies four enumeration-time filters:

# Filter What it catches
1 skip_bad_frames Windows overlapping any interval in bad_frames.json (intensity_spikes, pose_teleports_{L,R}, ot_loss_{L,R}). These are broken data: LED glitches, mocap solver flips, mid-episode OptiTrack track loss.
2 respect_active_sensors Ignores inactive sensors per tasks.json:per_date_notes when checking contact + motion predicates.
3 min_contact_fraction Drops windows where fewer than min_contact_fraction of frames have tactile contact (chosen sensor + metric + threshold). Forces samples to be contact-rich.
4 require_motion Drops windows where the active sensors are essentially stationary (operator paused mid-manipulation). The recorded data is healthy, but a near-zero-motion window contains no dynamics to learn.

Filter (4) is the one most people forget. Without it, you'll get the occasional "wait, the sensor isn't moving in this clip" sample even though everything else is clean.

Minimal recipe

from examples.react_window_dataset import ReactWindowDataset
from torch.utils.data import DataLoader

ds = ReactWindowDataset(
    data_root        = "processed/mode1_v1/motherboard",
    bad_frames_path  = "bad_frames.json",
    tasks_json_path  = "tasks.json",
    window_length    = 16,
    # (1) (2) — broken data + inactive-sensor handling
    skip_bad_frames        = True,
    respect_active_sensors = True,
    # (3) — contact-richness
    contact_metric         = "mixed",
    tactile_threshold      = 0.4,
    min_contact_fraction   = 0.5,
    which_sensors          = "any",
    # (4) — motion content (recommended for dynamics learning)
    require_motion              = True,
    min_motion_mps              = 0.03,    # 30 mm/s
    min_motion_fraction         = 0.5,
    which_sensors_must_move     = "all_active",
)
loader = DataLoader(ds, batch_size=8, shuffle=True, num_workers=2)

Recommended defaults by use case

  • Dynamics / world-model learning: all four filters on. The recipe above.
  • UMI-style imitation / pose-as-action: same recipe; filter (4) is critical here because stationary windows give you constant-action labels.
  • Studying static tactile patterns (e.g. classification of contact shapes): turn filter (4) OFF (require_motion=False) — you specifically want windows where the sensor is held still on an object.

Loading a single .pt directly (without this dataloader)

If you're rolling your own sampler, replicate the filter logic by hand:

import json, torch, numpy as np

ep_key = "2026-05-11/episode_017"
ep = torch.load(f"processed/mode1_v1/motherboard/{ep_key}.pt", weights_only=False)
T = ep["view"].shape[0]
bad = json.load(open("bad_frames.json"))["episodes"][ep_key]

# Frame-level mask (True = drop)
mask = np.zeros(T, dtype=bool)
for s, e in (bad["intensity_spikes"]
             + bad["pose_teleports_L"] + bad["pose_teleports_R"]
             + bad["ot_loss_L"] + bad["ot_loss_R"]):
    mask[s:e + 1] = True

# Per-frame motion mask (use this in addition to bad_frames)
pose_L = ep["sensor_left_pose"].numpy()
pose_R = ep["sensor_right_pose"].numpy()
speed_L = np.linalg.norm(np.diff(pose_L[:, :3], axis=0), axis=1) * 30      # m/s
speed_R = np.linalg.norm(np.diff(pose_R[:, :3], axis=0), axis=1) * 30
moving_L = np.concatenate([[speed_L[0]], speed_L]) >= 0.03                  # 30 mm/s
moving_R = np.concatenate([[speed_R[0]], speed_R]) >= 0.03

# Then when picking a window [t, t+L):
def good(t, L):
    if mask[t:t + L].any():
        return False
    return moving_L[t:t + L].mean() >= 0.5 and moving_R[t:t + L].mean() >= 0.5

Coordinates note

All frame indices in bad_frames.json and in the .pt files are in trimmed coordinates — the OT-uninitialized prefixes were cut from the published .pt files. The trim offset per file is recorded as _contact_meta.trim_offset inside the .pt. You don't need to apply it yourself: this loader and the metadata are already aligned.

If you also need to read the original H5 archive (held in MultimodalData/twm/data/<task>/<date>/), remember to add the trim offset back before indexing into the H5 — the H5 still has the pre-trim timeline.

trim_offset = ep["_contact_meta"]["trim_offset"]
h5_index = pt_index + trim_offset    # only needed when reading raw H5