trace-vla-code / code /trace_validation /scripts /a01_consistency.py
phammminhhieu's picture
TRACE-VLA code snapshot 2026-11-22 11:47 +07: 456 canonical files + SHA256 manifest + sync report (part 2)
ae1ed83 verified
Raw History Blame Contribute Delete
5.81 kB
#!/usr/bin/env python3
"""Phase A - A01 data consistency (TRACE-VLA validation, v1.1 A01).
Dataset-level checks on the 9 subset train tasks (dataset indices
31, 32, 38, 24, 22, 28, 19, 12, 18), plus a cross-check that the
TRACE feature cache agrees with the dataset rows it was built from.
Checks:
1. NaN/Inf scan over states and actions of all subset-task episodes.
2. Episode boundary integrity: frame_index starts at 0 and increments
by 1; lengths match the metadata.
3. Gripper channel semantics of the action vector.
4. Time alignment: sign agreement and Pearson r between action[t][0:3]
and the EE position change state[t]->state[t+1] (hypothesis H_t),
versus state[t-1]->state[t] (hypothesis H_{t-1}). The correct
alignment must win clearly.
5. Cache cross-check: for cached episodes of ds 31/12/24, cache states
and actions equal the dataset rows of the same episode_id.
Writes a JSON report; prints PASS/FAIL lines.
"""
import json
from pathlib import Path
import numpy as np
SUBSET_DS = [31, 32, 38, 24, 22, 28, 19, 12, 18]
EXP = Path.home() / "sera_v4_experiments"
OUT = EXP / "trace_validation" / "results" / "a01_consistency.json"
def main():
from lerobot.datasets.lerobot_dataset import LeRobotDataset, LeRobotDatasetMetadata
meta = LeRobotDatasetMetadata("lerobot/libero", revision="v3.0")
ep_len = np.array(meta.episodes["length"])
full = LeRobotDataset("lerobot/libero", revision="v3.0",
video_backend="pyav")
hf = full.hf_dataset
task_col = np.array(hf["task_index"])
ep_col = np.array(hf["episode_index"])
frame_col = np.array(hf["frame_index"])
states = np.stack(hf["observation.state"]).astype(np.float64)
actions = np.stack(hf["action"]).astype(np.float64)
starts = np.zeros(len(ep_len) + 1, dtype=np.int64)
np.cumsum(ep_len, out=starts[1:])
ep_task = np.array([task_col[starts[e]] for e in range(len(ep_len))])
report = {"subset_ds": SUBSET_DS}
subset_eps = [e for e in range(len(ep_len)) if ep_task[e] in SUBSET_DS]
rows = np.isin(ep_col, subset_eps)
report["n_episodes"] = len(subset_eps)
report["n_frames"] = int(rows.sum())
# 1. NaN scan
report["nan_states"] = int((~np.isfinite(states[rows])).sum())
report["nan_actions"] = int((~np.isfinite(actions[rows])).sum())
# 2. Boundary integrity
bad_bounds = 0
for e in subset_eps:
fr = frame_col[starts[e]:starts[e + 1]]
if len(fr) != ep_len[e] or fr[0] != 0 or (np.diff(fr) != 1).any():
bad_bounds += 1
report["bad_episode_boundaries"] = bad_bounds
# 3. Gripper semantics
g = actions[rows][:, 6]
report["gripper_action"] = {
"min": float(g.min()), "max": float(g.max()),
"frac_abs_gt_0.9": float((np.abs(g) > 0.9).mean()),
"unique_rounded": sorted(set(np.round(g, 1).tolist()))[:10],
}
gs = states[rows][:, 6:8]
report["gripper_state_range"] = [float(gs.min()), float(gs.max())]
# 4. Time alignment (EE position dims 0:3)
agree_t, agree_prev, tot = 0, 0, 0
rs_t, rs_prev = [], []
for e in subset_eps:
s0, s1 = starts[e], starts[e + 1]
st = states[s0:s1]
ac = actions[s0:s1]
d_next = st[1:] - st[:-1] # change after action t
a = ac[:-1][:, :3]
d = d_next[:, :3]
strong = np.abs(a) > 0.05
agree_t += int((np.sign(a[strong]) == np.sign(d[strong])).sum())
tot += int(strong.sum())
for ax in range(3):
if np.std(a[:, ax]) > 1e-9 and np.std(d[:, ax]) > 1e-9:
rs_t.append(np.corrcoef(a[:, ax], d[:, ax])[0, 1])
d_prev = (st[1:] - st[:-1])[:, :3] # change before action t+1
a2 = ac[1:][:, :3]
strong2 = np.abs(a2) > 0.05
agree_prev += int((np.sign(a2[strong2]) == np.sign(d_prev[strong2])).sum())
for ax in range(3):
if np.std(a2[:, ax]) > 1e-9 and np.std(d_prev[:, ax]) > 1e-9:
rs_prev.append(np.corrcoef(a2[:, ax], d_prev[:, ax])[0, 1])
report["alignment"] = {
"sign_agree_action_t_to_state_t+1": agree_t / max(1, tot),
"pearson_r_action_t": float(np.mean(rs_t)),
"sign_agree_action_t+1_to_prior_change": agree_prev / max(1, tot),
"pearson_r_shifted": float(np.mean(rs_prev)),
"n_strong": tot,
}
# 5. Cache cross-check (ds 31/12/24 episodes)
import torch
cache = torch.load(EXP / "trace_vla" / "feature_cache.pt",
weights_only=False)
max_state_err = max_action_err = 0.0
checked = 0
for ep in cache["episodes"]:
if ep["task_index"] not in (31, 12, 24):
continue
e = ep["episode_id"]
s0, s1 = starts[e], starts[e + 1]
cs = cache["states"][ep["start"]:ep["start"] + ep["length"]].numpy()
ca = cache["actions"][ep["start"]:ep["start"] + ep["length"]].numpy()
max_state_err = max(max_state_err,
float(np.abs(cs - states[s0:s1]).max()))
max_action_err = max(max_action_err,
float(np.abs(ca - actions[s0:s1]).max()))
checked += 1
report["cache_crosscheck"] = {
"episodes_checked": checked,
"max_state_err": max_state_err, "max_action_err": max_action_err,
}
ok = (report["nan_states"] == 0 and report["nan_actions"] == 0
and bad_bounds == 0
and report["alignment"]["sign_agree_action_t_to_state_t+1"] >= 0.9
and max_state_err < 1e-5 and max_action_err < 1e-5)
report["verdict"] = "PASS" if ok else "CHECK"
OUT.parent.mkdir(parents=True, exist_ok=True)
OUT.write_text(json.dumps(report, indent=1))
print(json.dumps(report, indent=1))
print("A01:", report["verdict"])
if __name__ == "__main__":
main()