diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..3f536157b919bb9c53a83400f7ce9a55f39ad085 --- /dev/null +++ b/README.md @@ -0,0 +1,135 @@ +--- +license: mit +task_categories: + - robotics +tags: + - behavior-cloning + - diffusion-policy + - pusht + - bimodal + - mode-editing +size_categories: + - n<1K +--- + +# Push-T Controlled Bimodal Teleop Dataset + +100 human-teleoperated Push-T demonstrations (50 LEFT-wrap + 50 RIGHT-wrap), collected +under a **controlled fixed initial state** so the two modes have kinematically equivalent +costs. Intended for downstream bimodal behavior-cloning and mode-editing experiments. + +All demos reach `coverage >= 0.95` shapely-IoU success threshold (env-defined). Demos +were collected at 10 Hz mouse-driven teleop on the 2D pygame Push-T env from the +Diffusion Policy paper (Chi et al., RSS 2023). + +## What "LEFT" vs "RIGHT" means + +T starts at lower-left `(185, 327, π/4)` and must translate up-right to the green goal +silhouette at `(256, 256, π/4)`. The agent (blue circle) spawns upper-right of the T +at `(327, 185) ± 15 px`. Two equal-cost wrap paths exist: + +- **LEFT** — agent wraps the **upper-left** side of the T (counter-clockwise about T's center) +- **RIGHT** — agent wraps the **lower-right** side of the T (clockwise about T's center) + +Modes alternate by seed parity: even seed → LEFT, odd seed → RIGHT. + +![Trajectory overlay](pusht_controlled_mixed_paths.png) + +## Files + +| File | Purpose | +|------|---------| +| `pusht_controlled_mixed.zarr/` | The dataset (zarr v2 directory store, 100 episodes / 8060 steps) | +| `pusht_controlled_mixed_paths.png` | All 100 agent paths, split by mode (visual sanity check) | +| `demo_pusht.py` | The patched collection script used to generate this dataset | + +## Zarr layout + +``` +pusht_controlled_mixed.zarr/ +├── data/ # 8060 timesteps total, 10 Hz +│ ├── state (8060, 5) float32 # [agent_x, agent_y, T_x, T_y, T_angle] +│ ├── action (8060, 2) float32 # teleop mouse-target action +│ ├── img (8060, 96, 96, 3) uint8 # 96×96 RGB env render +│ ├── keypoint (8060, 9, 2) float32 # 9 T-block keypoints +│ └── n_contacts (8060, 1) float32 +└── meta/ # 100 episodes + ├── episode_ends (100,) int64 # cumulative end-indices (DP standard) + ├── episode_modes (100,) int8 # 0 = LEFT, 1 = RIGHT ← extra + └── episode_coverages (100,) float32 # final IoU coverage ← extra +``` + +The `data/*` arrays and `meta/episode_ends` follow the **same layout** as the canonical +`pusht_cchi_v7_replay.zarr` from the DP repo. The two extra `meta/*` arrays are +additions for mode-editing work; the original DP training code ignores them. + +## Loading + +```python +import zarr, numpy as np +from huggingface_hub import snapshot_download + +local_dir = snapshot_download( + repo_id='haohw/pusht-controlled-mixed', + repo_type='dataset', +) +r = zarr.open(f'{local_dir}/pusht_controlled_mixed.zarr', mode='r') + +ends = np.asarray(r['meta/episode_ends']) +modes = np.asarray(r['meta/episode_modes']) # 0=LEFT, 1=RIGHT +covs = np.asarray(r['meta/episode_coverages']) +state = np.asarray(r['data/state']) +action = np.asarray(r['data/action']) + +# Per-episode iteration +starts = np.concatenate([[0], ends[:-1]]) +for s, e, m in zip(starts, ends, modes): + ep_state = state[s:e] + ep_action = action[s:e] + mode_name = 'LEFT' if m == 0 else 'RIGHT' + ... +``` + +For fast pulls on a cluster, set `HF_HUB_ENABLE_HF_TRANSFER=1` and install `hf_transfer`. + +## Splitting into per-mode zarrs + +If downstream code expects two single-mode zarr files +(`pusht_controlled_left.zarr` + `pusht_controlled_right.zarr`), the split is just a +filter on `meta/episode_modes`. The original DP collection guide's two-file format +can be reconstructed from this single mixed file at training time. + +## Collection spec + +**Env**: `PushTKeypointsEnv` from `diffusion_policy.env.pusht.pusht_keypoints_env`, +render_size=96, control_hz=10. + +**Per-episode init** (overrides env's random init via `env.reset_to_state`): + +| Object | Position | Angle | +|--------|----------|-------| +| T block | fixed `(185, 327)` | fixed `π/4` | +| Goal | fixed `(256, 256)` (env default) | fixed `π/4` | +| Agent | `(327, 185) + uniform(-15, +15)` (seeded by episode index) | — | + +**Success**: shapely-IoU between current T polygon and goal T polygon `>= 0.95`. +DP paper reports continuous max-coverage per episode (clipped at 0.95), not binary +success rate — so 95% is the env's done flag, not the eval metric. + +## Episode-length stats + +Mean 80.6 steps (≈8.1 s @ 10 Hz), median 78, min 60, max 141. + +## Reproducing + +See `demo_pusht.py`. Key changes from the stock DP script: + +1. Controlled init via `env.reset_to_state` (T fixed, agent perturbed ±15 px) +2. Mode auto-assigned by seed parity, displayed in-window (red/blue overlay + IoU bar) +3. Extra `meta/episode_modes` and `meta/episode_coverages` saved per episode +4. `S` key to save partial demos before 95%, `C` key to cancel and restart same seed + +## License + +MIT. Re-uses geometry / env from +[real-stanford/diffusion_policy](https://github.com/real-stanford/diffusion_policy). diff --git a/demo_pusht.py b/demo_pusht.py new file mode 100644 index 0000000000000000000000000000000000000000..71f2958b0a932c3209945216997d9fb526cecfd5 --- /dev/null +++ b/demo_pusht.py @@ -0,0 +1,258 @@ +import numpy as np +import click +import zarr +from diffusion_policy.common.replay_buffer import ReplayBuffer +from diffusion_policy.env.pusht.pusht_keypoints_env import PushTKeypointsEnv +import pygame + +# --- Mixed-mode controlled collection --- +# Seed parity determines mode: even = LEFT, odd = RIGHT. +# After each saved episode, the integer mode (0=LEFT, 1=RIGHT) and the final +# coverage are appended to meta/episode_modes and meta/episode_coverages in +# the zarr, alongside the standard meta/episode_ends. +MODE_NAMES = {0: 'LEFT', 1: 'RIGHT'} +MODE_COLORS = {0: (220, 30, 30), 1: (30, 80, 220)} # red for LEFT, blue for RIGHT +SUCCESS_THRESHOLD = 0.95 # matches PushTEnv.success_threshold + +_FONT_CACHE = {} + + +def _font(size, bold=False): + key = (size, bold) + if key not in _FONT_CACHE: + if not pygame.font.get_init(): + pygame.font.init() + _FONT_CACHE[key] = pygame.font.SysFont(None, size, bold=bold) + return _FONT_CACHE[key] + + +def draw_overlay(mode_int, seed, coverage): + """Blit mode label + live coverage bar over the env render and flip.""" + screen = pygame.display.get_surface() + if screen is None: + return + w = screen.get_width() + color = MODE_COLORS[mode_int] + name = MODE_NAMES[mode_int] + pad = 6 + + # Mode label: large text top-left with translucent backdrop + mode_font = _font(56, bold=True) + mode_surf = mode_font.render(name, True, color) + mode_rect = mode_surf.get_rect(topleft=(10, 6)) + bg = pygame.Surface((mode_rect.width + pad * 2, mode_rect.height + pad * 2), + pygame.SRCALPHA) + bg.fill((255, 255, 255, 200)) + screen.blit(bg, (mode_rect.x - pad, mode_rect.y - pad)) + screen.blit(mode_surf, mode_rect) + + # Seed number under the mode label + seed_font = _font(20) + seed_surf = seed_font.render(f'seed {seed}', True, (40, 40, 40)) + seed_rect = seed_surf.get_rect(topleft=(10, mode_rect.bottom + 4)) + sbg = pygame.Surface((seed_rect.width + pad * 2, seed_rect.height + pad), + pygame.SRCALPHA) + sbg.fill((255, 255, 255, 180)) + screen.blit(sbg, (seed_rect.x - pad, seed_rect.y - pad // 2)) + screen.blit(seed_surf, seed_rect) + + # Coverage bar across the top-right: shows current IoU coverage out of 95% + bar_w = 200 + bar_h = 18 + bar_x = w - bar_w - 10 + bar_y = 12 + pygame.draw.rect(screen, (255, 255, 255), (bar_x, bar_y, bar_w, bar_h)) + pygame.draw.rect(screen, (60, 60, 60), (bar_x, bar_y, bar_w, bar_h), 1) + cov_frac = float(min(coverage, SUCCESS_THRESHOLD)) / SUCCESS_THRESHOLD + fill_w = int(bar_w * cov_frac) + if cov_frac < 0.6: + bar_color = (180, 40, 40) + elif cov_frac < 0.9: + bar_color = (200, 150, 30) + else: + bar_color = (40, 170, 60) + pygame.draw.rect(screen, bar_color, (bar_x, bar_y, fill_w, bar_h)) + + cov_pct = coverage * 100.0 + cov_font = _font(18, bold=True) + cov_surf = cov_font.render(f'IoU {cov_pct:5.1f}% / 95%', True, (20, 20, 20)) + cov_rect = cov_surf.get_rect(topright=(w - 10, bar_y + bar_h + 4)) + cbg = pygame.Surface((cov_rect.width + pad * 2, cov_rect.height + pad), + pygame.SRCALPHA) + cbg.fill((255, 255, 255, 200)) + screen.blit(cbg, (cov_rect.x - pad, cov_rect.y - pad // 2)) + screen.blit(cov_surf, cov_rect) + + # Keybinding hint at the bottom + hint_font = _font(16) + hint_surf = hint_font.render('S save C cancel R retry Q quit', + True, (30, 30, 30)) + hint_rect = hint_surf.get_rect(midbottom=(w // 2, screen.get_height() - 4)) + hbg = pygame.Surface((hint_rect.width + pad * 2, hint_rect.height + pad), + pygame.SRCALPHA) + hbg.fill((255, 255, 255, 200)) + screen.blit(hbg, (hint_rect.x - pad, hint_rect.y - pad // 2)) + screen.blit(hint_surf, hint_rect) + + pygame.display.flip() + + +def append_episode_metadata(zarr_path, mode_int, coverage): + """Append (mode, coverage) to meta/episode_modes and meta/episode_coverages.""" + root = zarr.open(zarr_path, mode='a') + meta = root.require_group('meta') + if 'episode_modes' in meta: + arr = meta['episode_modes'] + arr.resize((arr.shape[0] + 1,)) + arr[-1] = mode_int + else: + meta.create_dataset( + 'episode_modes', + data=np.array([mode_int], dtype='i1'), + chunks=(64,), dtype='i1', + ) + if 'episode_coverages' in meta: + arr = meta['episode_coverages'] + arr.resize((arr.shape[0] + 1,)) + arr[-1] = float(coverage) + else: + meta.create_dataset( + 'episode_coverages', + data=np.array([coverage], dtype='f4'), + chunks=(64,), dtype='f4', + ) + + +@click.command() +@click.option('-o', '--output', required=True) +@click.option('-rs', '--render_size', default=96, type=int) +@click.option('-hz', '--control_hz', default=10, type=int) +def main(output, render_size, control_hz): + """ + Mixed-mode Push-T teleop with controlled init. + + Mode auto-assigned by seed parity: + seed even = LEFT (wrap T from upper-left side, red label) + seed odd = RIGHT (wrap T from lower-right side, blue label) + + Saved per episode in the zarr: + data/{state,action,img,keypoint,n_contacts} + meta/episode_ends (standard DP layout) + meta/episode_modes (int8: 0=LEFT, 1=RIGHT) + meta/episode_coverages (float32: final IoU coverage, 0..1) + + Keys: + S = save current episode now (no need to reach 95% IoU) + C = cancel current episode and restart same seed + R = same as C (retry) + Q = quit (script exits; saved episodes persist) + Space = pause + """ + replay_buffer = ReplayBuffer.create_from_path(output, mode='a') + + kp_kwargs = PushTKeypointsEnv.genenerate_keypoint_manager_params() + env = PushTKeypointsEnv(render_size=render_size, render_action=False, **kp_kwargs) + agent = env.teleop_agent() + clock = pygame.time.Clock() + + while True: + episode = list() + seed = replay_buffer.n_episodes + mode_int = seed % 2 + mode_name = MODE_NAMES[mode_int] + print(f'starting seed {seed} mode={mode_name}', flush=True) + + # --- Controlled init: T fixed on 45-deg symmetry axis through goal, + # agent perturbed +/- 15 px around (327, 185). + T_INIT_XY = np.array([185.0, 327.0]) + T_INIT_ANG = np.pi / 4 + AGENT_NOMINAL = np.array([327.0, 185.0]) + + np.random.seed(seed) + agent_xy = AGENT_NOMINAL + np.random.uniform(-15, 15, size=2) + init_state = np.array( + [agent_xy[0], agent_xy[1], T_INIT_XY[0], T_INIT_XY[1], T_INIT_ANG], + dtype=np.float64, + ) + env.reset_to_state = init_state + env.seed(seed) + # --- end controlled init + + obs = env.reset() + info = env._get_info() + img = env.render(mode='human') + + retry = False + force_save = False + pause = False + done = False + coverage = 0.0 + pygame.display.set_caption( + f'[{mode_name}] seed {seed} IoU {coverage*100:.1f}% / 95%') + draw_overlay(mode_int, seed, coverage) + + while not (done or force_save or retry): + for event in pygame.event.get(): + if event.type == pygame.KEYDOWN: + if event.key == pygame.K_SPACE: + pause = True + elif event.key in (pygame.K_r, pygame.K_c): + retry = True + elif event.key == pygame.K_s: + force_save = True + elif event.key == pygame.K_q: + exit(0) + if event.type == pygame.KEYUP: + if event.key == pygame.K_SPACE: + pause = False + + if retry or force_save: + break + if pause: + continue + + act = agent.act(obs) + if act is not None: + state = np.concatenate([info['pos_agent'], info['block_pose']]) + keypoint = obs.reshape(2, -1)[0].reshape(-1, 2)[:9] + data = { + 'img': img, + 'state': np.float32(state), + 'keypoint': np.float32(keypoint), + 'action': np.float32(act), + 'n_contacts': np.float32([info['n_contacts']]), + } + episode.append(data) + + obs, reward, done, info = env.step(act) + # reward = clip(coverage / 0.95, 0, 1) per PushTEnv.step + coverage = float(reward) * SUCCESS_THRESHOLD + img = env.render(mode='human') + pygame.display.set_caption( + f'[{mode_name}] seed {seed} IoU {coverage*100:.1f}% / 95%') + draw_overlay(mode_int, seed, coverage) + + clock.tick(control_hz) + + if retry: + print(f'cancel seed {seed} mode={mode_name}', flush=True) + continue + + if not episode: + print(f'skip seed {seed} (no teleop data — mouse never engaged)', + flush=True) + continue + + data_dict = dict() + for key in episode[0].keys(): + data_dict[key] = np.stack([x[key] for x in episode]) + replay_buffer.add_episode(data_dict, compressors='disk') + append_episode_metadata(output, mode_int, coverage) + suffix = ' [PARTIAL]' if force_save and not done else '' + print(f'saved seed {seed} mode={mode_name} ' + f'IoU={coverage*100:.1f}%{suffix} ' + f'(total {replay_buffer.n_episodes} episodes)', flush=True) + + +if __name__ == "__main__": + main() diff --git a/pusht_controlled_mixed.zarr/.zgroup b/pusht_controlled_mixed.zarr/.zgroup new file mode 100644 index 0000000000000000000000000000000000000000..3b7daf227c1687f28bc23b69f183e27ce9a475c1 --- /dev/null +++ b/pusht_controlled_mixed.zarr/.zgroup @@ -0,0 +1,3 @@ +{ + "zarr_format": 2 +} \ No newline at end of file diff --git a/pusht_controlled_mixed.zarr/data/.zgroup b/pusht_controlled_mixed.zarr/data/.zgroup new file mode 100644 index 0000000000000000000000000000000000000000..3b7daf227c1687f28bc23b69f183e27ce9a475c1 --- /dev/null +++ b/pusht_controlled_mixed.zarr/data/.zgroup @@ -0,0 +1,3 @@ +{ + "zarr_format": 2 +} \ No newline at end of file diff --git a/pusht_controlled_mixed.zarr/data/action/.zarray b/pusht_controlled_mixed.zarr/data/action/.zarray new file mode 100644 index 0000000000000000000000000000000000000000..79b14703f44bfeb6e1bbb71f5ca2055b5f862903 --- /dev/null +++ b/pusht_controlled_mixed.zarr/data/action/.zarray @@ -0,0 +1,23 @@ +{ + "chunks": [ + 121, + 2 + ], + "compressor": { + "blocksize": 0, + "clevel": 5, + "cname": "zstd", + "id": "blosc", + "shuffle": 2 + }, + "dimension_separator": ".", + "dtype": "