AlexWortega commited on
Commit
aa8868c
·
verified ·
1 Parent(s): 57a4b2a

Upload tinyvla2/scripts/eval_libero_canon.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. tinyvla2/scripts/eval_libero_canon.py +190 -0
tinyvla2/scripts/eval_libero_canon.py ADDED
@@ -0,0 +1,190 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ """Closed-loop LIBERO evaluation for CANONICAL-action TinyVLA-2 checkpoints.
3
+
4
+ The v2 line predicts base-frame EE deltas (metres / rotvec radians / gripper
5
+ openness), not LIBERO's OSC action units, so the policy output has to be decoded
6
+ before it can be stepped into the env:
7
+
8
+ normalized canonical --(q01/q99 span)--> physical deltas
9
+ physical deltas --(per-dim scale)--> OSC action
10
+
11
+ The scale is fitted once from ground truth (scripts fit in libero_canon2osc.json;
12
+ correlation 0.84-0.98 per motion dim). The gripper channel is absolute openness,
13
+ which is decoded by a threshold (92.5% sign agreement with the GT command, vs
14
+ 86.8% for a linear map).
15
+
16
+ One subtlety: for sidecars built from observation state, the anchor delta is
17
+ identically zero (state pose == action pose), so the executable stream is
18
+ chunk[1:], not chunk[0:].
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import json
25
+ from pathlib import Path
26
+
27
+ import numpy as np
28
+ import torch
29
+
30
+ SCALE_JSON = Path.home() / "tinyvla_data" / "libero_canon2osc.json"
31
+ LIBERO_ROOT = str(Path("~/tinyvla_data/libero_local").expanduser())
32
+ _SC = {"arm_dof": 0.1, "reach_m": 2, "gripper_width_m": 10, "num_cameras": 1 / 3,
33
+ "control_hz": 1 / 30, "joint_lo_mean": 1 / 3.1416, "joint_hi_mean": 1 / 3.1416,
34
+ "workspace_x": 2, "workspace_y": 2, "workspace_z": 2, "payload_kg": 0.2}
35
+
36
+
37
+ @torch.no_grad()
38
+ def main():
39
+ p = argparse.ArgumentParser()
40
+ p.add_argument("--checkpoint", type=Path, required=True)
41
+ p.add_argument("--suite", default="libero_spatial",
42
+ choices=["libero_spatial", "libero_object", "libero_goal", "libero_10", "libero_90"])
43
+ p.add_argument("--episodes", type=int, default=20)
44
+ p.add_argument("--refresh-s", type=float, default=None,
45
+ help="dual-rate: refresh the semantic latent only every N seconds")
46
+ p.add_argument("--max-steps", type=int, default=520)
47
+ p.add_argument("--n-action-steps", type=int, default=25,
48
+ help="actions executed per predicted chunk before re-planning")
49
+ p.add_argument("--grip-mode", default="threshold", choices=["threshold", "linear"])
50
+ p.add_argument("--save-video-dir", type=Path, default=None)
51
+ args = p.parse_args()
52
+
53
+ import yaml
54
+ from lerobot.datasets.lerobot_dataset import LeRobotDatasetMetadata
55
+ from lerobot.envs.factory import make_env, make_env_config
56
+ from scipy.spatial.transform import Rotation
57
+ from transformers import AutoTokenizer
58
+
59
+ from tinyvla.data.canonical import CanonicalChunkStore
60
+ from tinyvla.modeling_tinyvla import TinyVLAPolicy
61
+ from tinyvla.modules.embodiment import MORPH_FIELDS
62
+
63
+ policy = TinyVLAPolicy.from_pretrained(args.checkpoint).cuda().eval()
64
+ cfg = policy.config
65
+ tok = AutoTokenizer.from_pretrained(cfg.lm_model_name)
66
+
67
+ meta = LeRobotDatasetMetadata("libero_local", root=LIBERO_ROOT)
68
+ sstats = meta.stats["observation.state"]
69
+ s_mu = torch.as_tensor(sstats["mean"], dtype=torch.float32)
70
+ s_sd = torch.as_tensor(sstats["std"], dtype=torch.float32).clamp(min=1e-6)
71
+
72
+ store = CanonicalChunkStore("libero_local", src_fps=meta.fps, chunk=cfg.chunk_size)
73
+ cst = store.compute_stats()
74
+ q01, q99 = np.asarray(cst["q01"]), np.asarray(cst["q99"])
75
+ span = np.maximum(q99 - q01, 0.01 * np.median(np.abs(np.concatenate([q01, q99])) + 1e-6))
76
+ mid = 0.5 * (q01 + q99)
77
+
78
+ fit = json.load(open(SCALE_JSON))
79
+ mscale = np.asarray(fit["motion_scale"], dtype=np.float64)
80
+ desc = yaml.safe_load(open("configs/morphology/descriptors.yaml"))
81
+ morph = torch.tensor([desc["libero"].get(f, 0) * _SC.get(f, 1) for f in MORPH_FIELDS],
82
+ dtype=torch.float32)[None].cuda()
83
+
84
+ env_cfg = make_env_config("libero", task=args.suite)
85
+ task_envs = make_env(env_cfg, n_envs=1)[args.suite]
86
+
87
+ def to_batch(obs, task_text):
88
+ imgs = {}
89
+ for slot, key in (("cam0", "image"), ("cam1", "image2")):
90
+ x = torch.as_tensor(np.asarray(obs["pixels"][key]))
91
+ if x.dim() == 4:
92
+ x = x[0]
93
+ x = x.flip(0).flip(1) # robosuite renders 180-deg rotated vs the dataset
94
+ x = x.permute(2, 0, 1).float() / 255.0
95
+ if x.shape[-2:] != (cfg.image_size, cfg.image_size):
96
+ x = torch.nn.functional.interpolate(x[None], size=(cfg.image_size, cfg.image_size),
97
+ mode="bilinear", align_corners=False)[0]
98
+ imgs[slot] = x
99
+ rs = obs["robot_state"]
100
+ pos = np.asarray(rs["eef"]["pos"]).flatten()
101
+ rotvec = Rotation.from_quat(np.asarray(rs["eef"]["quat"]).flatten()).as_rotvec()
102
+ if rotvec[0] < 0: # match the dataset's antipodal choice
103
+ th = np.linalg.norm(rotvec)
104
+ if th > 1e-6:
105
+ rotvec = rotvec * (th - 2 * np.pi) / th
106
+ grip = np.asarray(rs["gripper"]["qpos"]).flatten()
107
+ state = torch.tensor(np.concatenate([pos, rotvec, grip]), dtype=torch.float32)
108
+ state = (state - s_mu) / s_sd
109
+ state = torch.nn.functional.pad(state, (0, cfg.max_state_dim - state.shape[-1]))
110
+ t = tok([task_text], padding=True, truncation=True,
111
+ max_length=cfg.tokenizer_max_length, return_tensors="pt")
112
+ return {"observation.images.cam0": imgs["cam0"][None].cuda(),
113
+ "observation.images.cam1": imgs["cam1"][None].cuda(),
114
+ "observation.state": state[None].cuda(),
115
+ "observation.language.tokens": t["input_ids"].cuda(),
116
+ "observation.language.attention_mask": t["attention_mask"].bool().cuda(),
117
+ "morphology": morph,
118
+ "embodiment_id": torch.tensor([0], device="cuda")}
119
+
120
+ def decode(chunk_norm):
121
+ """(chunk, >=7) normalized canonical -> (chunk-1, 7) OSC actions."""
122
+ phys = chunk_norm[:, :7] * span / 2 + mid
123
+ phys = phys[1:] # drop the identically-zero anchor delta
124
+ osc = np.zeros((len(phys), 7), dtype=np.float32)
125
+ osc[:, :6] = phys[:, :6] * mscale
126
+ if args.grip_mode == "threshold":
127
+ osc[:, 6] = np.where(phys[:, 6] > fit["grip_threshold"], -1.0, 1.0)
128
+ else:
129
+ osc[:, 6] = phys[:, 6] * fit["grip_a"] + fit["grip_b"]
130
+ return np.clip(osc, -1.0, 1.0)
131
+
132
+ fps = meta.fps
133
+ total = succ = 0
134
+ per_task = {}
135
+ task_ids = sorted(task_envs.keys())
136
+ plan = [(tid, i) for i in range((args.episodes + len(task_ids) - 1) // len(task_ids)) for tid in task_ids]
137
+ plan = plan[: args.episodes]
138
+ if args.save_video_dir:
139
+ args.save_video_dir.mkdir(parents=True, exist_ok=True)
140
+
141
+ for ep, (tid, rep) in enumerate(plan):
142
+ env = task_envs[tid]
143
+ obs, _ = env.reset(seed=1000 + rep)
144
+ try:
145
+ task_text = env.get_attr("task_description")[0]
146
+ except Exception:
147
+ task_text = getattr(getattr(env, "envs", [None])[0], "task_description", "")
148
+ policy.reset()
149
+ frames = [] if args.save_video_dir else None
150
+ latent, last_refresh = None, -1e9
151
+ queue, done, step_i, ep_succ = [], False, 0, False
152
+ while not done and step_i < args.max_steps:
153
+ if not queue:
154
+ batch = to_batch(obs, task_text)
155
+ if args.refresh_s is not None:
156
+ if step_i / fps - last_refresh >= args.refresh_s:
157
+ latent = policy._semantic_latent(batch)
158
+ last_refresh = step_i / fps
159
+ batch["semantic_latent"] = latent
160
+ with torch.autocast("cuda", torch.bfloat16):
161
+ pred = policy.predict_action_chunk(batch)[0].float().cpu().numpy()
162
+ queue = list(decode(pred)[: args.n_action_steps])
163
+ act = queue.pop(0)
164
+ try:
165
+ obs, _, terminated, truncated, info = env.step(act[None])
166
+ except ValueError:
167
+ break
168
+ done = bool(terminated[0] or truncated[0])
169
+ if info.get("is_success") is not None:
170
+ ep_succ = ep_succ or bool(np.asarray(info["is_success"]).flatten()[0])
171
+ if frames is not None:
172
+ frames.append(np.asarray(obs["pixels"]["image"])[0][::-1, ::-1])
173
+ step_i += 1
174
+ total += 1
175
+ succ += int(ep_succ)
176
+ per_task.setdefault(task_text[:50], []).append(int(ep_succ))
177
+ print(f"ep {ep}: {'SUCCESS' if ep_succ else 'fail'} ({step_i} steps) | {task_text[:60]}", flush=True)
178
+ if frames:
179
+ import imageio.v2 as imageio
180
+ imageio.mimwrite(args.save_video_dir / f"ep{ep:02d}_task{tid}_{'succ' if ep_succ else 'fail'}.mp4",
181
+ frames, fps=20, quality=7)
182
+
183
+ print(f"\n=== {args.suite} | {args.checkpoint} | canonical | refresh={args.refresh_s} ===")
184
+ print(f"success rate: {succ}/{total} = {succ/max(total,1):.1%}")
185
+ for t, v in per_task.items():
186
+ print(f" {sum(v)}/{len(v)} {t}")
187
+
188
+
189
+ if __name__ == "__main__":
190
+ main()