File size: 9,225 Bytes
b4396f0 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 | #!/usr/bin/env python3
"""Zero-shot / adapted rollout driver for LIBERO-Skill (libero_skill_obj).
Reuses the EXACT P2/P3 plumbing (LiberoEnvConfig -> make_env -> eval_policy)
after registering the SkillNet suite in-process:
1. install LIBERO-Skill assets (bddl + pruned_init) into the container's
libero package paths (fallback: ~/.libero/config.yaml redirect),
2. monkeypatch libero's benchmark dict with a stub suite whose tasks are
the 9 public manifest tasks (order = manifest order),
3. patch TASK_SUITE_MAX_STEPS['libero_skill_obj'] = 800 (SkillNet base cap).
Per episode it records: success, sum_reward, wall seconds, goal atoms
satisfied at the terminal state (parsed_problem goal_state evaluated via
_eval_predicate — end-state proxy for sub-skill completion), and a video.
Results are JSONL, resumable via SKIP of done (model, task_id, ep) rows.
"""
import argparse, json, time
from pathlib import Path
import os
ASSETS = Path(os.environ.get(
"SERA_SKILL_ASSETS",
str(Path.home() / "sera_v4_experiments" / "skill" / "libero_skill_assets")))
SUITE = "libero_skill_obj"
MAX_STEPS = 800
TASKS = [ # manifest order; (bddl stem, language)
("skill_obj_01", "put both the alphabet soup and the tomato sauce in the basket"),
("skill_obj_02", "open the top drawer of the cabinet and put the bowl on the plate"),
("skill_obj_03", "put the black bowl in the bottom drawer of the cabinet and close the bottom drawer of the cabinet"),
("skill_obj_04", "close the top drawer of the cabinet and put the black bowl on the plate"),
("skill_obj_05", "close the top drawer of the cabinet and close the microwave"),
("skill_obj_06", "stack the middle black bowl on the back black bowl and open the top drawer of the cabinet"),
("skill_obj_07", "put the black bowl on the plate and close the microwave"),
("skill_obj_08", "close the drawer of the cabinet and turn off the stove"),
("skill_obj_09", "put the black bowl on the plate and open the microwave"),
]
def install_assets_and_register():
import shutil
from libero.libero import benchmark, get_libero_path
for kind, key in (("bddl_files", "bddl_files"), ("init_files", "init_states")):
src = ASSETS / kind / SUITE
dst = Path(get_libero_path(key)) / SUITE
try:
dst.mkdir(parents=True, exist_ok=True)
for f in src.iterdir():
if f.is_file() and not (dst / f.name).exists():
shutil.copy2(f, dst / f.name)
route = "copy"
except Exception as e:
route = f"copy_failed:{e}"
probe = Path(get_libero_path(key)) / SUITE / "skill_obj_02.pruned_init" \
if kind == "init_files" else Path(get_libero_path(key)) / SUITE / "skill_obj_02.bddl"
print(f"ASSETS {kind}: route={route} probe_exists={probe.exists()} dst={dst}", flush=True)
if not probe.exists():
raise RuntimeError(f"asset install failed for {kind}: {probe} missing")
from libero.libero.benchmark import Task
tasks = []
for stem, lang in TASKS:
tasks.append(Task(name=stem, language=lang, problem=SUITE,
problem_folder=SUITE, bddl_file=f"{stem}.bddl",
init_states_file=f"{stem}.pruned_init"))
base = benchmark.get_benchmark_dict()["libero_goal"]()
base.tasks = tasks
base.name = SUITE
def get_task(i, _t=tasks):
return _t[i]
base.get_task = get_task
orig = benchmark.get_benchmark_dict
benchmark.get_benchmark_dict = lambda: {**orig(), SUITE: (lambda: base)}
import lerobot.envs.libero as lrl
lrl.TASK_SUITE_MAX_STEPS[SUITE] = MAX_STEPS
n_init = None
try:
states = lrl.get_task_init_states(base, 0)
n_init = len(states)
except Exception as e:
print(f"INIT PROBE failed: {e}", flush=True)
print(f"REGISTERED suite {SUITE}: {len(tasks)} tasks, init_states[task0]={n_init}", flush=True)
def goal_atoms(sub):
"""Evaluate BDDL goal atoms on the env's current (terminal) state."""
try:
inner = sub._env.env # OffScreenRenderEnv -> BDDL inner env
atoms = inner.parsed_problem["goal_state"]
out = []
for a in atoms:
try:
out.append({"atom": " ".join(str(x) for x in a),
"true": bool(inner._eval_predicate(a))})
except Exception as e:
out.append({"atom": " ".join(str(x) for x in a), "true": None, "err": str(e)})
return out
except Exception as e:
return [{"atom": "__unavailable__", "true": None, "err": str(e)}]
def main():
import sys
sys.path.insert(0, str(Path.home() / "sera_v4_experiments" / "tools"))
import train_v4 # noqa: F401 (processor registry fix, as in training)
ap = argparse.ArgumentParser()
ap.add_argument("--ckpt", required=True)
ap.add_argument("--model", required=True, help="v2 | v3 | dino (label only)")
ap.add_argument("--tasks", required=True, help="comma task_ids, e.g. 1,3,4,6,7,8")
ap.add_argument("--eps", default="0,1,2,3,4,5,6,7,8,9")
ap.add_argument("--out", required=True)
ap.add_argument("--seed", type=int, default=0)
ap.add_argument("--record_dir", default=None)
a = ap.parse_args()
import torch
from lerobot.configs.policies import PreTrainedConfig
from lerobot.envs import make_env, make_env_pre_post_processors
from lerobot.envs.configs import LiberoEnv as LiberoEnvConfig
from lerobot.policies import make_policy, make_pre_post_processors
from lerobot.scripts.lerobot_eval import eval_policy
from lerobot.utils.import_utils import register_third_party_plugins
from lerobot.utils.random_utils import set_seed
register_third_party_plugins()
install_assets_and_register()
task_ids = [int(x) for x in a.tasks.split(",")]
eps = [int(x) for x in a.eps.split(",")]
out = Path(a.out)
out.parent.mkdir(parents=True, exist_ok=True)
done = set()
if out.exists():
for line in out.read_text().splitlines():
if line.strip():
r = json.loads(line)
done.add((r["task_id"], r["ep"]))
set_seed(a.seed)
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
pcfg = PreTrainedConfig.from_pretrained(a.ckpt)
pcfg.pretrained_path = a.ckpt
pcfg.device = "cuda"
pcfg.use_amp = True
template = LiberoEnvConfig(task="libero_spatial")
policy = make_policy(cfg=pcfg, env_cfg=template, rename_map={})
policy.eval()
pre, post = make_pre_post_processors(
policy_cfg=pcfg, pretrained_path=a.ckpt,
preprocessor_overrides={
"device_processor": {"device": str(policy.config.device)},
"rename_observations_processor": {"rename_map": {}},
})
with torch.no_grad(), torch.autocast(device_type="cuda"):
for tid in task_ids:
ecfg = LiberoEnvConfig(task=SUITE, task_ids=[tid])
envs = make_env(ecfg, n_envs=1, use_async_envs=False)
vec = envs[SUITE][tid]
sub = vec.envs[0]
sub._reset_stride = 0
env_pre, env_post = make_env_pre_post_processors(env_cfg=ecfg, policy_cfg=pcfg)
for ep in eps:
if (tid, ep) in done:
print(f"SKIP done task {tid} ep {ep}", flush=True)
continue
t0 = time.time()
sub.init_state_id = ep
vdir, max_render = None, 0
if a.record_dir:
vdir = Path(a.record_dir) / f"{a.model}_{TASKS[tid][0]}_ep{ep}"
vdir.mkdir(parents=True, exist_ok=True)
max_render = 1
res = eval_policy(
env=vec, policy=policy, env_preprocessor=env_pre,
env_postprocessor=env_post, preprocessor=pre, postprocessor=post,
n_episodes=1, max_episodes_rendered=max_render, videos_dir=vdir,
start_seed=a.seed)
pe = res["per_episode"][0]
if ep == eps[0] and tid == task_ids[0]:
print("PER_EPISODE_KEYS", sorted(pe.keys()), flush=True)
atoms = goal_atoms(sub)
rec = {"model": a.model, "suite": SUITE, "task_id": tid,
"task": TASKS[tid][0], "ep": ep,
"success": bool(pe["success"]),
"sum_reward": float(pe["sum_reward"]),
"atoms_true": sum(1 for x in atoms if x["true"] is True),
"atoms_total": len(atoms), "atoms": atoms,
"seconds": round(time.time() - t0, 1)}
with open(out, "a") as f:
f.write(json.dumps(rec) + "\n")
print("RESULT", json.dumps({k: rec[k] for k in
("model", "task", "ep", "success", "atoms_true", "atoms_total", "seconds")}),
flush=True)
try:
vec.close()
except Exception:
pass
print("DRIVER DONE", flush=True)
if __name__ == "__main__":
main()
|