phi_so101_8bin_v1_trim / deadtime.py
Parv-09's picture
opening-pause trim table + audit script for phi_so101_8bin_v1
2624c23 verified
Raw
History Blame Contribute Delete
6 kB
"""Per-episode static-frame audit of phi_so101_8bin_v1.
GOAL: identify ONLY the pre-teleop dead air at the start of each episode. Interior pauses (operator
hesitating, gripper closing) and trailing pauses must be LEFT ALONE: an action chunk is N
*contiguous* frames, so deleting interior frames would teach trajectories with teleport jumps.
WHY NOT a per-frame movement threshold: rejected after measurement. Servo jitter plus the operator's
hand resting on the leader exceeds 0.1 deg/frame from frame 1 in 57 of 119 episodes, so a per-frame
test reports a 1-frame pause where the arm has in fact not gone anywhere for 100+ frames.
DEFINITION USED. Opening pause = frames before the arm first DEPARTS its start pose:
DROP = first t where max_j |action[t,j] - action[0,j]| > LEAD_TOL
This is cumulative, so it is immune to per-frame jitter, and because it takes the FIRST crossing it
can never extend past the beginning of real motion. Interior behaviour cannot influence it.
Computed on `action` (what the policy predicts). `observation.state` is NOT used for the cut: the
follower snaps to the leader on record start, a transient that departs at frame ~3 regardless.
Interior/trailing pauses are reported with a jitter-robust WINDOWED measure: the arm is static at t
if its total travel across the next WIN frames is under LEAD_TOL.
"""
from __future__ import annotations
import glob
from pathlib import Path
import numpy as np
import pandas as pd
SNAP = next(
Path.home().glob(
".cache/huggingface/lerobot/hub/datasets--BrutalCaesar--phi_so101_8bin_v1/snapshots/*"
)
)
FPS = 30
LEAD_TOL = 1.0 # degrees of departure from the start pose
WIN = 15 # 0.5 s window for the interior/trailing static test
INTERIOR_MIN = 15 # flag interior static runs of at least this many frames
def first_departure(a: np.ndarray, tol: float) -> int:
dev = np.abs(a - a[0]).max(axis=1)
return int(np.argmax(dev > tol)) if (dev > tol).any() else len(a)
def windowed_static(a: np.ndarray, tol: float, win: int) -> np.ndarray:
"""static[t] = the arm's total travel over frames [t, t+win) is under tol.
Vectorised with sliding_window_view; the per-frame Python loop was killed on the login node.
"""
n = len(a)
if n < win:
return np.zeros(n, dtype=bool)
w = np.lib.stride_tricks.sliding_window_view(a, win, axis=0) # (n-win+1, 6, win)
travel = (w.max(axis=-1) - w.min(axis=-1)).max(axis=-1) # (n-win+1,)
out = np.zeros(n, dtype=bool)
out[: len(travel)] = travel < tol
out[len(travel) :] = out[len(travel) - 1] if len(travel) else False
return out
def runs_of(flags: np.ndarray) -> list[tuple[int, int]]:
runs, i = [], 0
while i < len(flags):
if flags[i]:
j = i
while j < len(flags) and flags[j]:
j += 1
runs.append((i, j - i))
i = j
else:
i += 1
return runs
files = sorted(glob.glob(str(SNAP / "data" / "**" / "*.parquet"), recursive=True))
df = pd.concat([pd.read_parquet(f) for f in files], ignore_index=True)
eps = {int(ep): np.stack(g.sort_values("frame_index")["action"].to_numpy()) for ep, g in df.groupby("episode_index")}
rows = []
for ep, a in sorted(eps.items()):
n = len(a)
drop = first_departure(a, LEAD_TOL)
stat = windowed_static(a, LEAD_TOL, WIN)
# interior/trailing measured strictly AFTER the cut, so the opening pause cannot leak in
tail = stat[drop:]
rr = runs_of(tail)
trail = rr[-1][1] if rr and rr[-1][0] + rr[-1][1] == len(tail) else 0
interior = [(st, ln) for st, ln in rr if st != 0 and st + ln != len(tail)]
imax = max((ln for _, ln in interior), default=0)
ibig = sum(1 for _, ln in interior if ln >= INTERIOR_MIN)
rows.append(
{
"ep": ep,
"side": "left" if ep <= 58 else "right",
"frames": n,
"DROP": drop,
"drop_s": round(drop / FPS, 2),
"drop_pct": round(100 * drop / n, 1),
"kept": n - drop,
"trail": trail,
"trail_s": round(trail / FPS, 2),
"interior_max": imax,
"interior_max_s": round(imax / FPS, 2),
"interior_runs": ibig,
}
)
r = pd.DataFrame(rows)
out = Path.home() / "phi" / "deadtime_per_episode.csv"
r.to_csv(out, index=False)
print(f"episodes {len(r)} frames {r.frames.sum()} -> {out}\n")
print("=== DROP (opening pause only) ===")
print(r.groupby("side")[["DROP", "drop_s", "drop_pct"]].agg(["mean", "median", "min", "max"]).round(1))
print(f"\ntotal dropped {int(r.DROP.sum())} of {int(r.frames.sum())} = {100 * r.DROP.sum() / r.frames.sum():.1f}%")
print(f"frames remaining: {int(r.kept.sum())}")
print("\n=== KEPT: trailing + interior pauses ===")
print(r.groupby("side")[["trail", "trail_s", "interior_max", "interior_max_s", "interior_runs"]].agg(["mean", "median", "max"]).round(1))
print(f"episodes with an interior pause >= 0.5s: {(r.interior_runs > 0).sum()} of {len(r)}")
print(f"episodes with a trailing pause >= 0.5s : {(r.trail >= 15).sum()} of {len(r)}")
print("\n=== SAFETY ===")
print(f"DROP == 0 (no pause found) : {(r.DROP == 0).sum()} {list(r[r.DROP == 0].ep)}")
print(f"DROP > 35% of episode : {(r.drop_pct > 35).sum()}")
if (r.drop_pct > 35).any():
print(r[r.drop_pct > 35][["ep", "frames", "DROP", "drop_pct"]].to_string(index=False))
print(f"kept < 300 frames (10 s) after cut: {(r.kept < 300).sum()}")
if (r.kept < 300).any():
print(r[r.kept < 300][["ep", "frames", "DROP", "kept"]].to_string(index=False))
print("\n=== LEAD_TOL sensitivity (degrees -> total frames dropped) ===")
for tol in (0.5, 1.0, 2.0, 5.0, 10.0):
tot = sum(first_departure(a, tol) for a in eps.values())
print(f" {tol:>5} deg -> {tot:>6} frames ({100 * tot / len(df):.1f}%)")
print("\n=== every episode ===")
print(r[["ep", "side", "frames", "DROP", "drop_s", "kept", "interior_max", "trail"]].to_string(index=False))