Update build_longvideo_test.py
Browse files- build_longvideo_test.py +163 -254
build_longvideo_test.py
CHANGED
|
@@ -1,46 +1,42 @@
|
|
| 1 |
"""
|
| 2 |
-
|
| 3 |
-
Build a long-horizon test
|
| 4 |
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
|
|
|
|
|
|
| 12 |
|
| 13 |
Chunk k of the rollout uses:
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
so chunk k's observation is exactly the last frame chunk k-1 generated.
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
|
| 21 |
Usage:
|
| 22 |
-
python
|
| 23 |
-
--
|
| 24 |
-
--
|
| 25 |
-
--out
|
| 26 |
-
--
|
| 27 |
"""
|
| 28 |
|
| 29 |
import argparse
|
| 30 |
import json
|
| 31 |
import os
|
| 32 |
import random
|
| 33 |
-
from collections import defaultdict
|
| 34 |
-
from pathlib import Path
|
| 35 |
|
| 36 |
import numpy as np
|
| 37 |
from scipy.spatial.transform import Rotation as R
|
| 38 |
-
from tqdm import tqdm
|
| 39 |
|
| 40 |
|
| 41 |
-
# -------------------------------
|
| 42 |
-
# verbatim from build_pipeline_data.py -- do not "improve" these
|
| 43 |
-
# --------------------------------------------------------------------------- #
|
| 44 |
def load_metadata(episode_dir, camera="camera2"):
|
| 45 |
with open(os.path.join(episode_dir, "metadata.json")) as f:
|
| 46 |
meta = json.load(f)
|
|
@@ -59,127 +55,54 @@ def get_pose(entry):
|
|
| 59 |
|
| 60 |
|
| 61 |
def action_delta(entry_from, entry_to):
|
|
|
|
| 62 |
t0, r0, _ = get_pose(entry_from)
|
| 63 |
t1, r1, g1 = get_pose(entry_to)
|
| 64 |
dt = t1 - t0
|
| 65 |
-
|
| 66 |
-
R1 = R.from_euler("xyz", r1)
|
| 67 |
-
drot = (R0.inv() * R1).as_euler("xyz")
|
| 68 |
return np.array([dt[0], dt[1], dt[2], drot[0], drot[1], drot[2], g1],
|
| 69 |
dtype=np.float64)
|
| 70 |
|
| 71 |
|
| 72 |
-
def
|
| 73 |
-
d = r1 - r0
|
| 74 |
-
d = (d + np.pi) % (2 * np.pi) - np.pi
|
| 75 |
-
return float(np.linalg.norm(d))
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
def compute_valid_range(meta, trans_thresh, rot_thresh):
|
| 79 |
n = len(meta)
|
| 80 |
if n < 2:
|
| 81 |
return None
|
| 82 |
-
|
| 83 |
-
rot_d = np.zeros(n)
|
| 84 |
for i in range(1, n):
|
| 85 |
t0, r0, _ = get_pose(meta[i - 1])
|
| 86 |
t1, r1, _ = get_pose(meta[i])
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
if not moving.any():
|
| 91 |
return None
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
def
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
return 0
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
def build_long_clip(ep_dir, source_root, meta, obs_pos, n_future,
|
| 111 |
-
action_stride, chunk_len):
|
| 112 |
-
"""Schema-identical to build_pipeline_data.py's clip, with n_future frames."""
|
| 113 |
-
future_pos = [obs_pos + (i + 1) * action_stride for i in range(n_future)]
|
| 114 |
-
|
| 115 |
-
obs_entry = meta[obs_pos]
|
| 116 |
-
obs_frame_idx = obs_entry["frame_idx"]
|
| 117 |
-
future_frame_idxs = [meta[p]["frame_idx"] for p in future_pos]
|
| 118 |
-
|
| 119 |
-
obs_image_path = obs_entry.get(
|
| 120 |
-
"image_path", f"images/frame_{obs_frame_idx:06d}.png")
|
| 121 |
-
future_image_paths = [
|
| 122 |
-
meta[p].get("image_path", f"images/frame_{meta[p]['frame_idx']:06d}.png")
|
| 123 |
-
for p in future_pos
|
| 124 |
-
]
|
| 125 |
-
contact_paths = [os.path.join("modalities/contact", f"{fi:06d}.npy")
|
| 126 |
-
for fi in future_frame_idxs]
|
| 127 |
-
force_paths = [os.path.join("modalities/force", f"{fi:06d}.npy")
|
| 128 |
-
for fi in future_frame_idxs]
|
| 129 |
-
|
| 130 |
-
for p in contact_paths + force_paths:
|
| 131 |
-
if not os.path.exists(os.path.join(ep_dir, p)):
|
| 132 |
-
return None, f"missing {p}"
|
| 133 |
-
|
| 134 |
-
# action[i] = pos[s+i*stride] -> pos[s+(i+1)*stride]
|
| 135 |
-
action = np.stack([
|
| 136 |
-
action_delta(meta[obs_pos + i * action_stride],
|
| 137 |
-
meta[obs_pos + (i + 1) * action_stride])
|
| 138 |
-
for i in range(n_future)
|
| 139 |
-
])
|
| 140 |
-
|
| 141 |
-
n_nonblack = sum(contact_nonblack(os.path.join(ep_dir, cp))
|
| 142 |
-
for cp in contact_paths)
|
| 143 |
-
|
| 144 |
-
t, r, g = get_pose(obs_entry)
|
| 145 |
-
|
| 146 |
-
# per-chunk contact activity: tells you which chunks actually have contact,
|
| 147 |
-
# so a flat force curve in chunk 0 is not mistaken for model collapse
|
| 148 |
-
n_chunks = n_future // chunk_len
|
| 149 |
-
chunk_active = []
|
| 150 |
-
for k in range(n_chunks):
|
| 151 |
-
sub = contact_paths[k * chunk_len:(k + 1) * chunk_len]
|
| 152 |
-
chunk_active.append(
|
| 153 |
-
sum(contact_nonblack(os.path.join(ep_dir, cp)) for cp in sub) / chunk_len)
|
| 154 |
-
|
| 155 |
-
clip = {
|
| 156 |
-
"episode": os.path.relpath(ep_dir, source_root),
|
| 157 |
-
"obs_frame_idx": obs_frame_idx,
|
| 158 |
-
"future_frame_idxs": future_frame_idxs,
|
| 159 |
-
"obs_image_path": obs_image_path,
|
| 160 |
-
"future_image_paths": future_image_paths,
|
| 161 |
-
"contact_paths": contact_paths,
|
| 162 |
-
"force_paths": force_paths,
|
| 163 |
-
"obs_pose": [t[0], t[1], t[2], r[0], r[1], r[2], g],
|
| 164 |
-
"action_delta": action.tolist(),
|
| 165 |
-
"activate_frac": n_nonblack / n_future,
|
| 166 |
-
"n_contact_frames": n_nonblack,
|
| 167 |
-
# rollout bookkeeping
|
| 168 |
-
"n_chunks": n_chunks,
|
| 169 |
-
"chunk_len": chunk_len,
|
| 170 |
-
"chunk_activate_frac": chunk_active,
|
| 171 |
-
}
|
| 172 |
-
return clip, None
|
| 173 |
|
| 174 |
|
| 175 |
-
# --------------------------------------------------------------------------- #
|
| 176 |
def main():
|
| 177 |
ap = argparse.ArgumentParser()
|
| 178 |
-
ap.add_argument("--
|
| 179 |
-
|
| 180 |
-
|
|
|
|
|
|
|
| 181 |
ap.add_argument("--out", required=True)
|
| 182 |
-
ap.add_argument("--
|
| 183 |
ap.add_argument("--n_chunks", type=int, default=5)
|
| 184 |
ap.add_argument("--chunk_len", type=int, default=16)
|
| 185 |
ap.add_argument("--action_stride", type=int, default=3)
|
|
@@ -187,148 +110,134 @@ def main():
|
|
| 187 |
ap.add_argument("--trans_thresh", type=float, default=1.0)
|
| 188 |
ap.add_argument("--rot_thresh", type=float, default=0.01)
|
| 189 |
ap.add_argument("--seed", type=int, default=0)
|
| 190 |
-
ap.add_argument("--
|
| 191 |
-
help="
|
| 192 |
-
"
|
| 193 |
-
ap.add_argument("--allow_repeat_episode", dest="one_per_episode",
|
| 194 |
-
action="store_false")
|
| 195 |
-
ap.add_argument("--use_full_range", action="store_true",
|
| 196 |
-
help="allow rolling past the moving segment into the static "
|
| 197 |
-
"tail; default stops at the valid range's last frame")
|
| 198 |
args = ap.parse_args()
|
| 199 |
|
| 200 |
rng = random.Random(args.seed)
|
| 201 |
-
|
| 202 |
-
|
| 203 |
-
|
| 204 |
-
|
| 205 |
-
|
| 206 |
-
|
| 207 |
-
|
| 208 |
-
|
| 209 |
-
|
| 210 |
-
|
| 211 |
-
|
| 212 |
-
|
| 213 |
-
|
| 214 |
-
|
| 215 |
-
|
| 216 |
-
|
| 217 |
-
|
| 218 |
-
|
| 219 |
-
|
| 220 |
-
candidates = [] # (n_reachable, episode, obs_pos, meta, ep_dir)
|
| 221 |
-
meta_cache = {}
|
| 222 |
-
for ep, obs_idxs in tqdm(sorted(by_ep.items()), desc="scanning episodes"):
|
| 223 |
-
ep_dir = os.path.join(source_root, ep)
|
| 224 |
-
if ep not in meta_cache:
|
| 225 |
-
try:
|
| 226 |
-
meta_cache[ep] = load_metadata(ep_dir, args.camera)
|
| 227 |
-
except Exception as e:
|
| 228 |
-
print(f" [skip] {ep}: {e}")
|
| 229 |
-
meta_cache[ep] = None
|
| 230 |
-
meta = meta_cache[ep]
|
| 231 |
-
if not meta:
|
| 232 |
-
continue
|
| 233 |
|
|
|
|
| 234 |
vr = compute_valid_range(meta, args.trans_thresh, args.rot_thresh)
|
| 235 |
if vr is None:
|
|
|
|
| 236 |
continue
|
| 237 |
first, last = vr
|
| 238 |
-
|
| 239 |
-
|
| 240 |
-
|
| 241 |
-
|
| 242 |
-
for
|
| 243 |
-
|
| 244 |
-
|
| 245 |
-
|
| 246 |
-
|
| 247 |
-
|
| 248 |
-
if k > 0:
|
| 249 |
-
candidates.append((k, ep, pos, fi))
|
| 250 |
-
|
| 251 |
-
if not candidates:
|
| 252 |
-
raise RuntimeError("no start point can reach even one chunk")
|
| 253 |
-
|
| 254 |
-
hist = defaultdict(int)
|
| 255 |
-
for k, *_ in candidates:
|
| 256 |
-
hist[k] += 1
|
| 257 |
-
print("\nreachable-chunk histogram over all candidate starts:")
|
| 258 |
-
for k in sorted(hist, reverse=True):
|
| 259 |
-
print(f" {k} chunks: {hist[k]}")
|
| 260 |
-
|
| 261 |
-
# ---- select: prefer full-length, then shorter; one per episode ----
|
| 262 |
-
rng.shuffle(candidates)
|
| 263 |
-
candidates.sort(key=lambda x: -x[0]) # stable: full-length first
|
| 264 |
-
|
| 265 |
-
selected, used_eps = [], set()
|
| 266 |
-
for k, ep, pos, fi in candidates:
|
| 267 |
-
if len(selected) >= args.n_cases:
|
| 268 |
-
break
|
| 269 |
-
if args.one_per_episode and ep in used_eps:
|
| 270 |
continue
|
| 271 |
-
|
| 272 |
-
|
| 273 |
-
|
| 274 |
-
|
| 275 |
-
|
| 276 |
-
|
| 277 |
-
for
|
| 278 |
-
|
|
|
|
|
|
|
|
|
|
| 279 |
break
|
| 280 |
-
|
| 281 |
-
|
| 282 |
-
|
| 283 |
-
|
| 284 |
-
|
| 285 |
-
|
| 286 |
-
|
| 287 |
-
|
| 288 |
-
|
| 289 |
-
out_clips = []
|
| 290 |
-
for k, ep, pos, fi in tqdm(selected, desc="building"):
|
| 291 |
-
meta = meta_cache[ep]
|
| 292 |
-
clip, err = build_long_clip(
|
| 293 |
-
os.path.join(source_root, ep), source_root, meta, pos,
|
| 294 |
-
k * args.chunk_len, args.action_stride, args.chunk_len)
|
| 295 |
-
if clip is None:
|
| 296 |
-
print(f" [drop] {ep} frame {fi}: {err}")
|
| 297 |
continue
|
| 298 |
-
out_clips.append(clip)
|
| 299 |
-
|
| 300 |
-
config = dict(test.get("config", {})) if isinstance(test, dict) else {}
|
| 301 |
-
config.update({
|
| 302 |
-
"camera": args.camera,
|
| 303 |
-
"action_stride": args.action_stride,
|
| 304 |
-
"n_future": n_future,
|
| 305 |
-
"chunk_len": args.chunk_len,
|
| 306 |
-
"n_chunks": args.n_chunks,
|
| 307 |
-
"trans_thresh": args.trans_thresh,
|
| 308 |
-
"rot_thresh": args.rot_thresh,
|
| 309 |
-
"action_dim_names": ["dx", "dy", "dz", "drx", "dry", "drz", "gripper_abs"],
|
| 310 |
-
"obs_pose_names": ["x", "y", "z", "r1", "r2", "r3", "gripper"],
|
| 311 |
-
"note": ("long-horizon rollout index. n_future is VARIABLE per clip "
|
| 312 |
-
"(n_chunks*chunk_len); read clip['n_chunks']. chunk k uses "
|
| 313 |
-
"obs = future frame [16k-1] and action_delta[16k:16k+16]."),
|
| 314 |
-
"source_test_json": args.test_json,
|
| 315 |
-
"seed": args.seed,
|
| 316 |
-
})
|
| 317 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 318 |
with open(args.out, "w") as f:
|
| 319 |
-
json.dump(
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
print("
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
print(f" {c['episode'][-40:]:40s} frame={c['obs_frame_idx']:6d} [{s}]")
|
| 332 |
|
| 333 |
|
| 334 |
if __name__ == "__main__":
|
|
|
|
| 1 |
"""
|
| 2 |
+
make_longvideo_test.py
|
| 3 |
+
Build a long-horizon rollout test json, schema-identical to data_test_0730.json.
|
| 4 |
|
| 5 |
+
Picks N random episodes from one task directory, takes ONE case per episode
|
| 6 |
+
starting at the beginning of its moving segment, and extends it to
|
| 7 |
+
n_chunks * 16 future frames at action_stride.
|
| 8 |
|
| 9 |
+
samples[i] has exactly the 5 keys the dataset expects:
|
| 10 |
+
episode, obs_frame_idx, observation_frame, frames, actions
|
| 11 |
+
`frames` and `actions` are n_chunks*16 long instead of 16. `actions` are RAW
|
| 12 |
+
deltas (mm / rad / absolute gripper) -- ACWMDataset normalizes them with
|
| 13 |
+
statistics.json, same as before.
|
| 14 |
|
| 15 |
Chunk k of the rollout uses:
|
| 16 |
+
obs = frames[16k - 1] (k=0 -> observation_frame)
|
| 17 |
+
action = actions[16k : 16k+16]
|
|
|
|
| 18 |
|
| 19 |
+
Per-case chunk metadata goes in top-level "rollout_info" (parallel to samples),
|
| 20 |
+
so `samples` stays byte-compatible with what the dataset already reads.
|
| 21 |
|
| 22 |
Usage:
|
| 23 |
+
python make_longvideo_test.py \
|
| 24 |
+
--task_dir /n/lab_storage/ydu_lab/sycen/data/physical_wm/grasping/grasping_videos/grasping_gello_flip_the_switch_box_open_to_the_left_100 \
|
| 25 |
+
--source_root /n/lab_storage/ydu_lab/sycen/data/physical_wm/grasping \
|
| 26 |
+
--out /n/netscratch/ydu_lab/Lab/sycen/data/data_test_0823_longvideo.json \
|
| 27 |
+
--n_episodes 15 --n_chunks 5
|
| 28 |
"""
|
| 29 |
|
| 30 |
import argparse
|
| 31 |
import json
|
| 32 |
import os
|
| 33 |
import random
|
|
|
|
|
|
|
| 34 |
|
| 35 |
import numpy as np
|
| 36 |
from scipy.spatial.transform import Rotation as R
|
|
|
|
| 37 |
|
| 38 |
|
| 39 |
+
# --- copied verbatim from build_pipeline_data.py ---------------------------- #
|
|
|
|
|
|
|
| 40 |
def load_metadata(episode_dir, camera="camera2"):
|
| 41 |
with open(os.path.join(episode_dir, "metadata.json")) as f:
|
| 42 |
meta = json.load(f)
|
|
|
|
| 55 |
|
| 56 |
|
| 57 |
def action_delta(entry_from, entry_to):
|
| 58 |
+
"""[dx,dy,dz, drx,dry,drz, gripper_abs]; rot = SO(3) relative, euler xyz."""
|
| 59 |
t0, r0, _ = get_pose(entry_from)
|
| 60 |
t1, r1, g1 = get_pose(entry_to)
|
| 61 |
dt = t1 - t0
|
| 62 |
+
drot = (R.from_euler("xyz", r0).inv() * R.from_euler("xyz", r1)).as_euler("xyz")
|
|
|
|
|
|
|
| 63 |
return np.array([dt[0], dt[1], dt[2], drot[0], drot[1], drot[2], g1],
|
| 64 |
dtype=np.float64)
|
| 65 |
|
| 66 |
|
| 67 |
+
def compute_valid_range(meta, trans_thresh=1.0, rot_thresh=0.01):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
n = len(meta)
|
| 69 |
if n < 2:
|
| 70 |
return None
|
| 71 |
+
moving = np.zeros(n, dtype=bool)
|
|
|
|
| 72 |
for i in range(1, n):
|
| 73 |
t0, r0, _ = get_pose(meta[i - 1])
|
| 74 |
t1, r1, _ = get_pose(meta[i])
|
| 75 |
+
dr = (r1 - r0 + np.pi) % (2 * np.pi) - np.pi
|
| 76 |
+
moving[i] = (np.linalg.norm(t1 - t0) > trans_thresh
|
| 77 |
+
or np.linalg.norm(dr) > rot_thresh)
|
| 78 |
if not moving.any():
|
| 79 |
return None
|
| 80 |
+
return int(np.argmax(moving)), n - 1 - int(np.argmax(moving[::-1]))
|
| 81 |
+
# ---------------------------------------------------------------------------- #
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def rel_image(episode_rel, entry):
|
| 85 |
+
"""Full relative path with episode prefix, matching the test json."""
|
| 86 |
+
p = entry.get("image_path", f"images/frame_{entry['frame_idx']:06d}.png")
|
| 87 |
+
return os.path.join(episode_rel, p)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def contact_active(ep_dir, frame_idx):
|
| 91 |
+
p = os.path.join(ep_dir, "modalities", "contact", f"{frame_idx:06d}.npy")
|
| 92 |
+
if not os.path.exists(p):
|
| 93 |
+
return None
|
| 94 |
+
return bool(np.any(np.load(p) != 0))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 95 |
|
| 96 |
|
|
|
|
| 97 |
def main():
|
| 98 |
ap = argparse.ArgumentParser()
|
| 99 |
+
ap.add_argument("--task_dir", required=True,
|
| 100 |
+
help="directory containing the episode folders (0000, 0001, ...)")
|
| 101 |
+
ap.add_argument("--source_root", required=True,
|
| 102 |
+
help="root that `episode` is relative to; must match the "
|
| 103 |
+
"--source_root you pass to inference")
|
| 104 |
ap.add_argument("--out", required=True)
|
| 105 |
+
ap.add_argument("--n_episodes", type=int, default=15)
|
| 106 |
ap.add_argument("--n_chunks", type=int, default=5)
|
| 107 |
ap.add_argument("--chunk_len", type=int, default=16)
|
| 108 |
ap.add_argument("--action_stride", type=int, default=3)
|
|
|
|
| 110 |
ap.add_argument("--trans_thresh", type=float, default=1.0)
|
| 111 |
ap.add_argument("--rot_thresh", type=float, default=0.01)
|
| 112 |
ap.add_argument("--seed", type=int, default=0)
|
| 113 |
+
ap.add_argument("--start_offset", type=int, default=0,
|
| 114 |
+
help="frames to skip past the start of the moving segment; "
|
| 115 |
+
"raise it if the early chunks have no contact")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 116 |
args = ap.parse_args()
|
| 117 |
|
| 118 |
rng = random.Random(args.seed)
|
| 119 |
+
task_dir = os.path.abspath(args.task_dir)
|
| 120 |
+
source_root = os.path.abspath(args.source_root)
|
| 121 |
+
|
| 122 |
+
ep_names = sorted(
|
| 123 |
+
d for d in os.listdir(task_dir)
|
| 124 |
+
if os.path.isdir(os.path.join(task_dir, d))
|
| 125 |
+
and os.path.exists(os.path.join(task_dir, d, "metadata.json"))
|
| 126 |
+
)
|
| 127 |
+
print(f"{len(ep_names)} episodes in {os.path.basename(task_dir)}")
|
| 128 |
+
rng.shuffle(ep_names)
|
| 129 |
+
|
| 130 |
+
samples, info = [], []
|
| 131 |
+
n_short = n_missing = 0
|
| 132 |
+
|
| 133 |
+
for name in ep_names:
|
| 134 |
+
if len(samples) >= args.n_episodes:
|
| 135 |
+
break
|
| 136 |
+
ep_dir = os.path.join(task_dir, name)
|
| 137 |
+
episode_rel = os.path.relpath(ep_dir, source_root)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 138 |
|
| 139 |
+
meta = load_metadata(ep_dir, args.camera)
|
| 140 |
vr = compute_valid_range(meta, args.trans_thresh, args.rot_thresh)
|
| 141 |
if vr is None:
|
| 142 |
+
n_short += 1
|
| 143 |
continue
|
| 144 |
first, last = vr
|
| 145 |
+
s = min(first + args.start_offset, last)
|
| 146 |
+
|
| 147 |
+
# largest whole number of chunks that fits
|
| 148 |
+
k = 0
|
| 149 |
+
for cand in range(args.n_chunks, 0, -1):
|
| 150 |
+
if s + cand * args.chunk_len * args.action_stride <= last:
|
| 151 |
+
k = cand
|
| 152 |
+
break
|
| 153 |
+
if k == 0:
|
| 154 |
+
n_short += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
continue
|
| 156 |
+
|
| 157 |
+
n_future = k * args.chunk_len
|
| 158 |
+
fut_pos = [s + (i + 1) * args.action_stride for i in range(n_future)]
|
| 159 |
+
|
| 160 |
+
# every frame's png and modality npy must exist
|
| 161 |
+
ok = True
|
| 162 |
+
for p in fut_pos:
|
| 163 |
+
fi = meta[p]["frame_idx"]
|
| 164 |
+
if not os.path.exists(os.path.join(source_root,
|
| 165 |
+
rel_image(episode_rel, meta[p]))):
|
| 166 |
+
ok = False
|
| 167 |
break
|
| 168 |
+
for mod in ("contact", "force"):
|
| 169 |
+
if not os.path.exists(os.path.join(
|
| 170 |
+
ep_dir, "modalities", mod, f"{fi:06d}.npy")):
|
| 171 |
+
ok = False
|
| 172 |
+
break
|
| 173 |
+
if not ok:
|
| 174 |
+
break
|
| 175 |
+
if not ok:
|
| 176 |
+
n_missing += 1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 177 |
continue
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
+
actions = np.stack([
|
| 180 |
+
action_delta(meta[s + i * args.action_stride],
|
| 181 |
+
meta[s + (i + 1) * args.action_stride])
|
| 182 |
+
for i in range(n_future)
|
| 183 |
+
])
|
| 184 |
+
|
| 185 |
+
samples.append({
|
| 186 |
+
"episode": episode_rel,
|
| 187 |
+
"obs_frame_idx": meta[s]["frame_idx"],
|
| 188 |
+
"observation_frame": rel_image(episode_rel, meta[s]),
|
| 189 |
+
"frames": [rel_image(episode_rel, meta[p]) for p in fut_pos],
|
| 190 |
+
"actions": actions.tolist(),
|
| 191 |
+
})
|
| 192 |
+
|
| 193 |
+
# contact activity per chunk -- a flat force curve in a chunk with
|
| 194 |
+
# activate=0.00 is correct behaviour, not model collapse
|
| 195 |
+
act = []
|
| 196 |
+
for c in range(k):
|
| 197 |
+
sub = fut_pos[c * args.chunk_len:(c + 1) * args.chunk_len]
|
| 198 |
+
vals = [contact_active(ep_dir, meta[p]["frame_idx"]) for p in sub]
|
| 199 |
+
act.append(sum(bool(v) for v in vals) / len(vals))
|
| 200 |
+
info.append({
|
| 201 |
+
"episode": episode_rel,
|
| 202 |
+
"obs_frame_idx": meta[s]["frame_idx"],
|
| 203 |
+
"n_chunks": k,
|
| 204 |
+
"chunk_len": args.chunk_len,
|
| 205 |
+
"n_frames_total": len(meta),
|
| 206 |
+
"valid_range": [first, last],
|
| 207 |
+
"chunk_activate_frac": act,
|
| 208 |
+
})
|
| 209 |
+
|
| 210 |
+
out = {
|
| 211 |
+
"source": task_dir,
|
| 212 |
+
"config": {
|
| 213 |
+
"action_stride": args.action_stride,
|
| 214 |
+
"chunk_len": args.chunk_len,
|
| 215 |
+
"n_chunks_requested": args.n_chunks,
|
| 216 |
+
"camera": args.camera,
|
| 217 |
+
"source_root": source_root,
|
| 218 |
+
"seed": args.seed,
|
| 219 |
+
"note": ("long-horizon rollout index. `frames`/`actions` are "
|
| 220 |
+
"n_chunks*16 long. chunk k: obs = frames[16k-1] "
|
| 221 |
+
"(k=0 -> observation_frame), action = actions[16k:16k+16]. "
|
| 222 |
+
"actions are RAW deltas; normalize with statistics.json."),
|
| 223 |
+
},
|
| 224 |
+
"n_samples": len(samples),
|
| 225 |
+
"samples": samples,
|
| 226 |
+
"rollout_info": info,
|
| 227 |
+
}
|
| 228 |
with open(args.out, "w") as f:
|
| 229 |
+
json.dump(out, f)
|
| 230 |
+
|
| 231 |
+
print(f"\nwrote {args.out} ({len(samples)} cases)")
|
| 232 |
+
if n_short:
|
| 233 |
+
print(f" {n_short} episodes too short / never moving")
|
| 234 |
+
if n_missing:
|
| 235 |
+
print(f" {n_missing} episodes dropped for missing png/npy")
|
| 236 |
+
print(f"\n{'episode':>6s} {'obs':>5s} {'len':>4s} ch contact fraction per chunk")
|
| 237 |
+
for it in info:
|
| 238 |
+
s = " ".join(f"{v:.2f}" for v in it["chunk_activate_frac"])
|
| 239 |
+
print(f"{it['episode'].split('/')[-1]:>6s} {it['obs_frame_idx']:5d} "
|
| 240 |
+
f"{it['n_frames_total']:4d} {it['n_chunks']} [{s}]")
|
|
|
|
| 241 |
|
| 242 |
|
| 243 |
if __name__ == "__main__":
|