action-worldmodel-bench / build_vae_data.py
syCen's picture
Update build_vae_data.py
3475f22 verified
Raw
History Blame Contribute Delete
11.2 kB
"""
build_clip_index.py
Build the clip index + global normalization statistics for Contact/Force VAE
finetuning.
Per episode:
1. Read metadata.json, compute frame-to-frame action delta (trans mm + rot rad).
2. Trim only the static head/tail:
moving = (trans > trans_thresh) | (rot > rot_thresh)
first = first moving frame, last = last moving frame -> valid range
(zeros in the MIDDLE are kept; we only cut the two ends.)
3. Inside the valid range, take CLIPS_PER_EPISODE start positions spaced
evenly (not dense sliding) so clips overlap little and cover the whole
motion (approach -> contact -> release).
4. Each clip = 17 frames at frame_stride: positions s, s+stride, ..., s+16*stride.
Outputs:
- clips.json : list of clips, each with episode path + 17 frame_idx +
17 contact/force npy paths.
- statistics.json : global normalization constants.
contact: per-finger scale on sqrt-transformed values (p99)
force: per-channel mean/std over nonzero pixels
Usage:
python build_clip_index.py --source_root /path/to/root --out_dir ./vae_index
python build_clip_index.py --source_root /path/to/root --out_dir ./vae_index \
--clips_per_episode 15 --frame_stride 3 --trans_thresh 1.0 --rot_thresh 0.01
"""
import argparse
import json
import os
import glob
import random
import numpy as np
from pathlib import Path
# ---------------- pose / delta ----------------
def load_metadata(episode_dir, camera="camera2"):
with open(os.path.join(episode_dir, "metadata.json")) as f:
meta = json.load(f)
cam = [m for m in meta if m.get("camera") == camera]
if cam:
meta = cam
meta = sorted(meta, key=lambda m: m.get("frame_idx", 0))
return meta
def get_pose(entry):
s = entry["eef_state"]
t = np.array([s["x"], s["y"], s["z"]], dtype=np.float64) # mm
r = np.array([s["r1"], s["r2"], s["r3"]], dtype=np.float64) # rad
return t, r
def rpy_delta(r0, r1):
d = r1 - r0
d = (d + np.pi) % (2 * np.pi) - np.pi
return float(np.linalg.norm(d))
def compute_valid_range(meta, trans_thresh, rot_thresh):
"""Return (first_pos, last_pos) positions in the meta list that bound the
moving segment. Only trims the two ends; middle zeros are kept."""
n = len(meta)
trans_d = np.zeros(n)
rot_d = np.zeros(n)
for i in range(1, n):
t0, r0 = get_pose(meta[i - 1])
t1, r1 = get_pose(meta[i])
trans_d[i] = float(np.linalg.norm(t1 - t0))
rot_d[i] = rpy_delta(r0, r1)
moving = (trans_d > trans_thresh) | (rot_d > rot_thresh)
if not moving.any():
return None
first = int(np.argmax(moving))
last = n - 1 - int(np.argmax(moving[::-1]))
return first, last
# ---------------- clip sampling ----------------
def sample_clip_starts(first_pos, last_pos, frame_stride, n_frames,
clips_per_episode):
"""Evenly spaced start positions inside [first_pos, last_pos] such that a
full clip (n_frames at frame_stride) fits. Returns list of start positions."""
span = (n_frames - 1) * frame_stride # positions covered by one clip
max_start = last_pos - span
if max_start < first_pos:
return [] # valid range too short for one clip
n_possible = max_start - first_pos + 1
k = min(clips_per_episode, n_possible)
if k <= 1:
return [first_pos]
# evenly spaced, inclusive of both ends
starts = np.linspace(first_pos, max_start, k).round().astype(int).tolist()
# dedup while preserving order
seen, out = set(), []
for s in starts:
if s not in seen:
seen.add(s); out.append(s)
return out
def build_clips_for_episode(episode_dir, source_root, meta, valid_range,
frame_stride, n_frames, clips_per_episode,
contact_dir="modalities/contact",
force_dir="modalities/force"):
first_pos, last_pos = valid_range
starts = sample_clip_starts(first_pos, last_pos, frame_stride, n_frames,
clips_per_episode)
rel_ep = os.path.relpath(episode_dir, source_root)
clips = []
for s in starts:
positions = [s + i * frame_stride for i in range(n_frames)]
frame_idxs = [meta[p]["frame_idx"] for p in positions]
contact_paths = [os.path.join(contact_dir, f"{fi:06d}.npy") for fi in frame_idxs]
force_paths = [os.path.join(force_dir, f"{fi:06d}.npy") for fi in frame_idxs]
# verify the npy files exist (skip clip if any missing)
ok = all(os.path.exists(os.path.join(episode_dir, p)) for p in contact_paths)
if not ok:
continue
clips.append({
"episode": rel_ep,
"frame_indices": frame_idxs,
"contact_paths": contact_paths,
"force_paths": force_paths,
})
return clips
# ---------------- statistics ----------------
def accumulate_stats(clips, source_root, n_sample_frames, seed=0):
"""Sample frames across clips and compute global normalization stats.
contact: per-finger (2) p99 of sqrt(nonzero values)
force: per-channel (6) mean/std over nonzero pixels"""
rng = random.Random(seed)
# collect (episode, contact_path, force_path) frame entries
frame_entries = []
for c in clips:
ep = c["episode"]
for cp, fp in zip(c["contact_paths"], c["force_paths"]):
frame_entries.append((ep, cp, fp))
rng.shuffle(frame_entries)
if n_sample_frames > 0:
frame_entries = frame_entries[:n_sample_frames]
# contact: collect sqrt(nonzero) values per finger
contact_vals = [[], []] # per finger
# force: online mean/std per channel over nonzero pixels
f_sum = np.zeros(6); f_sqsum = np.zeros(6); f_cnt = np.zeros(6)
for ep, cp, fp in frame_entries:
c = np.load(os.path.join(source_root, ep, cp)) # (2,H,W)
for ch in range(2):
nz = c[ch][c[ch] != 0]
if nz.size:
contact_vals[ch].append(np.sqrt(nz))
f = np.load(os.path.join(source_root, ep, fp)) # (6,H,W)
for ch in range(6):
nz = f[ch][f[ch] != 0]
if nz.size:
f_sum[ch] += nz.sum()
f_sqsum[ch] += (nz ** 2).sum()
f_cnt[ch] += nz.size
contact_p99 = []
contact_max = []
for ch in range(2):
if contact_vals[ch]:
allv = np.concatenate(contact_vals[ch])
contact_p99.append(float(np.percentile(allv, 99)))
contact_max.append(float(allv.max()))
else:
contact_p99.append(1.0); contact_max.append(1.0)
f_cnt_safe = np.maximum(f_cnt, 1)
f_mean = f_sum / f_cnt_safe
f_std = np.sqrt(np.maximum(f_sqsum / f_cnt_safe - f_mean ** 2, 1e-12))
return {
"n_frames_used": len(frame_entries),
"contact": {
"transform": "sqrt",
"scale_p99": contact_p99, # per finger; divide sqrt(x) by this
"max_sqrt": contact_max,
},
"force": {
"transform": "per_channel_std",
"mean": f_mean.tolist(), # per channel (6), over nonzero pixels
"std": f_std.tolist(),
},
}
# ---------------- main ----------------
def is_episode(p):
return (
(p / "metadata.json").exists()
and (p / "masks.json").exists()
and (p / "modalities" / "contact").exists()
and (p / "modalities" / "force").exists()
)
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--source_root", required=True)
ap.add_argument("--out_dir", default="./vae_index")
ap.add_argument("--camera", default="camera2")
ap.add_argument("--frame_stride", type=int, default=3)
ap.add_argument("--n_frames", type=int, default=17)
ap.add_argument("--clips_per_episode", type=int, default=15)
ap.add_argument("--trans_thresh", type=float, default=1.0) # mm
ap.add_argument("--rot_thresh", type=float, default=0.01) # rad
ap.add_argument("--n_sample_frames", type=int, default=3000,
help="frames to sample for statistics (0 = use all)")
ap.add_argument("--with_stats", action="store_true",
help="also compute statistics.json (slow, reads npy)")
ap.add_argument("--stats_full", action="store_true",
help="use all frames for statistics instead of sampling")
ap.add_argument("--seed", type=int, default=0)
args = ap.parse_args()
source_root = Path(args.source_root)
out_dir = Path(args.out_dir)
out_dir.mkdir(parents=True, exist_ok=True)
candidates = [source_root] + [p for p in source_root.rglob("*") if p.is_dir()]
episode_dirs = sorted([p for p in candidates if is_episode(p)])
print(f"Found {len(episode_dirs)} episodes under {source_root}")
all_clips = []
n_skipped = 0
for ep in episode_dirs:
meta = load_metadata(str(ep), args.camera)
if len(meta) < args.n_frames:
n_skipped += 1; continue
vr = compute_valid_range(meta, args.trans_thresh, args.rot_thresh)
if vr is None:
n_skipped += 1; continue
clips = build_clips_for_episode(
str(ep), str(source_root), meta, vr,
args.frame_stride, args.n_frames, args.clips_per_episode)
all_clips.extend(clips)
print(f"Built {len(all_clips)} clips ({n_skipped} episodes skipped)")
denom = max(len(episode_dirs) - n_skipped, 1)
print(f" avg clips/episode = {len(all_clips)/denom:.1f}")
config = {
"frame_stride": args.frame_stride,
"n_frames": args.n_frames,
"clips_per_episode": args.clips_per_episode,
"trans_thresh": args.trans_thresh,
"rot_thresh": args.rot_thresh,
"camera": args.camera,
"n_episodes": len(episode_dirs) - n_skipped,
"n_clips": len(all_clips),
}
# always write the clip index (fast: no npy reads)
with open(out_dir / "clips.json", "w") as f:
json.dump({"config": config, "clips": all_clips}, f)
print(f"\nWrote: {out_dir/'clips.json'} ({len(all_clips)} clips)")
# statistics are OPTIONAL and slow (reads npy). Skip by default so you can
# start writing the dataloader / training immediately.
if args.with_stats:
print("\nComputing global statistics (reads npy, slower)...")
stats = accumulate_stats(
all_clips, str(source_root),
n_sample_frames=0 if args.stats_full else args.n_sample_frames,
seed=args.seed)
stats["config"] = config
with open(out_dir / "statistics.json", "w") as f:
json.dump(stats, f, indent=2)
print(f"Wrote: {out_dir/'statistics.json'}")
print(json.dumps(stats, indent=2)[:800])
else:
print("\n[stats skipped] pass --with_stats to compute statistics.json,")
print("or compute global normalization constants yourself and drop in a")
print("statistics.json matching the schema in accumulate_stats().")
if __name__ == "__main__":
main()