shadowbench / scripts /search_baseline.py
spratyey's picture
ShadowBench: environment, certified targets, episodes, transcripts and tasks (part 2)
3c29d68 verified
Raw History Blame Contribute Delete
5.93 kB
"""A reference that knows nothing about hands: CMA-ES over the same gated two-hand pose space.
The optimizer sees only the target silhouette and the score, like the models (no book figure), and is told the score
of every pose it tries, about 6,000 per plate. Every reported pose passes the environment's static gate: joint and
flexion-dependent spread limits, workspace bounds, skin self-intersection and hand-hand collision. It ignores the
per-call step limits and the 100-call budget, so it estimates what is reachable in this simulator, not a
like-for-like competitor. The `tasks` config holds its result for each plate (`search_*`).
uv sync --extra search
uv run python scripts/search_baseline.py --task hilliar_giraffe
"""
from __future__ import annotations
import argparse
import json
from pathlib import Path
import time
import cma
import numpy as np
from scipy.spatial.transform import Rotation
from shadowbench import native_environment as ne
from shadowbench.factory import load_task
from shadowbench.pose import InvalidPose, Pose
from shadowbench.render import shadow
from shadowbench.score import grade
from shadowbench.targets import ROOT
from shadowbench.wrist_posture import posture_effort
LO = np.array([ne.LIMITS[a][0] for a in ne.ALIASES] * 2)
HI = np.array([ne.LIMITS[a][1] for a in ne.ALIASES] * 2)
P_LO, P_HI = np.array([-.6, -.5, .3] * 2), np.array([.6, .5, 2.1] * 2)
START = Pose(np.zeros(46), np.array([[.1, -.12, 1.3], [-.1, -.12, 1.3]]), np.array([[1., 0, 0, 0], [1., 0, 0, 0]]))
CHECKPOINTS = (100, 300, 1000, 3000)
def decode(x: np.ndarray) -> Pose:
x = np.clip(x, 0., 1.)
degrees = LO + x[:46] * (HI - LO)
for hand in range(2):
for finger in ("index", "middle", "ring", "little"):
limit = ne.spread_limit(degrees[hand * 23 + ne.INDEX[f"{finger}.mcp"]])
spread = hand * 23 + ne.INDEX[f"{finger}.spread"]
degrees[spread] = np.clip(degrees[spread], -limit, limit)
positions = (P_LO + x[46:52] * (P_HI - P_LO)).reshape(2, 3)
rotations = Rotation.from_rotvec(((x[52:58] * 2 - 1) * np.pi).reshape(2, 3))
return Pose(np.radians(degrees), positions, rotations.as_quat(scalar_first=True))
def encode(pose: Pose) -> np.ndarray:
joints = (np.degrees(pose.q) - LO) / (HI - LO)
positions = (pose.positions.reshape(-1) - P_LO) / (P_HI - P_LO)
rotations = Rotation.from_quat(pose.quaternions, scalar_first=True).as_rotvec().reshape(-1) / np.pi / 2 + .5
return np.concatenate([joints, positions, rotations])
def run(task_id: str, restarts: int, budget: int, seed: int) -> dict:
task = load_task(task_id)
rig = ne.NativeRig()
gate = ne.NativeGate(rig)
def score(pose: Pose) -> dict:
return grade(shadow(ne.meshes_for(rig, pose)), task, posture_effort(pose)["ease"])
start = score(START)
best = {"reward": start["reward"], "pose": START.dump(), "metrics": start}
evaluations = validations = 0
curve = {}
began = time.time()
for restart in range(restarts):
es = cma.CMAEvolutionStrategy(encode(START), .25, {
"bounds": [0., 1.], "seed": seed + restart, "maxfevals": budget, "verbose": -9})
while not es.stop():
candidates = es.ask()
poses = [decode(x) for x in candidates]
rewards = []
for pose in poses:
try:
rewards.append(score(pose)["reward"])
except ValueError: # skin crossing the lamp plane cannot be rendered
rewards.append(-1.)
evaluations += len(candidates)
fitness = [-r for r in rewards]
# Only the selected half drives the mean, so validity is checked lazily from the top.
valid = 0
for i in np.argsort(rewards)[::-1]:
if valid >= es.sp.weights.mu:
break
validations += 1
try:
gate.check(poses[i])
except InvalidPose:
fitness[i] = 1. - rewards[i]
continue
valid += 1
if rewards[i] > best["reward"]:
best = {"reward": rewards[i], "pose": poses[i].dump(), "metrics": score(poses[i])}
es.tell(candidates, fitness)
for checkpoint in CHECKPOINTS:
if checkpoint not in curve and evaluations >= checkpoint:
curve[checkpoint] = best["metrics"]["score"]
gate.check(Pose.parse(best["pose"]))
metrics = best["metrics"]
return {"task_id": task_id, "revision": task.metadata["revision"], "score": metrics["score"],
"iou": metrics["iou"], "boundary_f1": metrics["boundary_f1"], "hole_preservation": metrics["hole_preservation"],
"ease": metrics["ease"], "start_score": start["score"], "evaluations": evaluations,
"validations": validations, "seconds": round(time.time() - began, 1),
"best_after_evaluations": curve, "restarts": restarts, "budget_per_restart": budget,
"pose": best["pose"]}
def main():
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument("--task", required=True)
parser.add_argument("--restarts", type=int, default=3)
parser.add_argument("--budget", type=int, default=2000, help="scored candidates per restart")
parser.add_argument("--seed", type=int, default=1)
parser.add_argument("--out", type=Path, default=ROOT / "runs" / "search")
args = parser.parse_args()
args.out.mkdir(parents=True, exist_ok=True)
result = run(args.task, args.restarts, args.budget, args.seed)
(args.out / f"{args.task}.json").write_text(json.dumps(result, indent=2))
print(json.dumps({k: result[k] for k in ("task_id", "score", "iou", "boundary_f1", "evaluations", "seconds")}))
if __name__ == "__main__":
main()