Spaces:
Sleeping
Sleeping
Watch checkpoints walk: rollout video tab; NUM_EVALS sets checkpoint cadence
#8
by arminfg - opened
- README.md +7 -0
- app.py +102 -24
- requirements.txt +2 -0
- rollout.py +108 -0
README.md
CHANGED
|
@@ -34,6 +34,13 @@ Trains `G1JoystickRoughTerrain` from [MuJoCo Playground](https://playground.mujo
|
|
| 34 |
with Brax PPO on the Space's GPU. Thousands of MJX environments step in parallel,
|
| 35 |
versus the 16 CPU processes a laptop manages.
|
| 36 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
Training starts automatically on boot. Checkpoints are written to `/data` when
|
| 38 |
persistent storage is attached, and pushed to `HF_REPO` if that variable and a
|
| 39 |
write-scoped `HF_TOKEN` secret are set.
|
|
|
|
| 34 |
with Brax PPO on the Space's GPU. Thousands of MJX environments step in parallel,
|
| 35 |
versus the 16 CPU processes a laptop manages.
|
| 36 |
|
| 37 |
+
**Watch a checkpoint walk.** The reward curve says whether training is moving;
|
| 38 |
+
the *Render rollout* section says whether the robot walks. Pick a checkpoint,
|
| 39 |
+
a forward speed, snow friction and depth, and it films the policy on a Himalaya
|
| 40 |
+
crop (`rollout.py`; MJX + `MUJOCO_GL=egl`) and reports how long it stayed up and
|
| 41 |
+
how far it walked. `NUM_EVALS` (default 40) sets how many evals — and therefore
|
| 42 |
+
log lines and checkpoint uploads — a run makes.
|
| 43 |
+
|
| 44 |
Training starts automatically on boot. Checkpoints are written to `/data` when
|
| 45 |
persistent storage is attached, and pushed to `HF_REPO` if that variable and a
|
| 46 |
write-scoped `HF_TOKEN` secret are set.
|
app.py
CHANGED
|
@@ -17,6 +17,8 @@ from pathlib import Path
|
|
| 17 |
|
| 18 |
import gradio as gr
|
| 19 |
|
|
|
|
|
|
|
| 20 |
ENV_NAME = os.environ.get("ENV_NAME", "G1JoystickRoughTerrain")
|
| 21 |
NUM_TIMESTEPS = int(os.environ.get("NUM_TIMESTEPS", 200_000_000))
|
| 22 |
SEED = int(os.environ.get("SEED", 0))
|
|
@@ -35,6 +37,7 @@ SNOW = os.environ.get("SNOW", "1") == "1" # snow on t
|
|
| 35 |
SNOW_FRICTION = tuple(float(v) for v in os.environ.get("SNOW_FRICTION", "0.3,0.7").split(","))
|
| 36 |
SNOW_DEPTH = tuple(float(v) for v in os.environ.get("SNOW_DEPTH", "0.0,0.08").split(","))
|
| 37 |
SURFACE = TERRAIN + ("-snow" if SNOW else "") # checkpoint prefix
|
|
|
|
| 38 |
|
| 39 |
# /data exists only when persistent storage is attached; fall back to /tmp.
|
| 40 |
OUT = Path("/data/ckpt") if Path("/data").is_dir() else Path("/tmp/ckpt")
|
|
@@ -144,6 +147,49 @@ def install_jax_pmap_shims() -> None:
|
|
| 144 |
log(f"shimmed jax.{name} (removed in this JAX version)")
|
| 145 |
|
| 146 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 147 |
def train_worker() -> None:
|
| 148 |
try:
|
| 149 |
STATE["status"] = "importing"
|
|
@@ -160,34 +206,13 @@ def train_worker() -> None:
|
|
| 160 |
|
| 161 |
from brax.training.agents.ppo import networks as ppo_networks
|
| 162 |
from brax.training.agents.ppo import train as ppo
|
| 163 |
-
from mujoco_playground import
|
| 164 |
from mujoco_playground.config import locomotion_params
|
| 165 |
|
| 166 |
-
|
| 167 |
-
log(f"loading {ENV_NAME} ...")
|
| 168 |
-
env = registry.load(ENV_NAME)
|
| 169 |
-
env_cfg = registry.get_default_config(ENV_NAME)
|
| 170 |
-
eval_env = registry.load(ENV_NAME, config=env_cfg)
|
| 171 |
-
randomization_fn = registry.get_domain_randomizer(ENV_NAME)
|
| 172 |
-
if TERRAIN == "himalaya":
|
| 173 |
-
from himalaya_terrain import apply_terrain, make_terrains, randomizer
|
| 174 |
-
log(f"building {NUM_TERRAINS} Himalaya crops: {HIMALAYA_PATCH:.0f} m of Khumbu "
|
| 175 |
-
f"-> 20 m arena, relief {HIMALAYA_RELIEF} m ...")
|
| 176 |
-
grids = make_terrains(NUM_TERRAINS, seed=SEED, patch_m=HIMALAYA_PATCH,
|
| 177 |
-
relief=HIMALAYA_RELIEF)
|
| 178 |
-
apply_terrain(env, grids, HIMALAYA_RELIEF)
|
| 179 |
-
apply_terrain(eval_env, grids, HIMALAYA_RELIEF)
|
| 180 |
-
randomization_fn = randomizer(randomization_fn, grids)
|
| 181 |
-
log("terrain: himalaya (per-env crops via domain randomization)")
|
| 182 |
-
else:
|
| 183 |
-
log("terrain: playground stock rough terrain")
|
| 184 |
-
if SNOW:
|
| 185 |
-
from himalaya_terrain import snow_randomizer
|
| 186 |
-
randomization_fn = snow_randomizer(randomization_fn, SNOW_FRICTION, SNOW_DEPTH)
|
| 187 |
-
log(f"snow: foot-floor friction U{SNOW_FRICTION}, depth U{SNOW_DEPTH} m "
|
| 188 |
-
"(soft contact, per env)")
|
| 189 |
ppo_params = locomotion_params.brax_ppo_config(ENV_NAME)
|
| 190 |
ppo_params.num_timesteps = int(STATE["target"])
|
|
|
|
| 191 |
log(f"num_envs={ppo_params.get('num_envs')} "
|
| 192 |
f"batch_size={ppo_params.get('batch_size')} "
|
| 193 |
f"timesteps={int(STATE['target']):,}")
|
|
@@ -289,6 +314,45 @@ def logs() -> str:
|
|
| 289 |
return "\n".join(LOG) or "(no output yet)"
|
| 290 |
|
| 291 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 292 |
with gr.Blocks(title="G1 rough-terrain training") as demo:
|
| 293 |
gr.Markdown("# Unitree G1 — Himalayan terrain locomotion training")
|
| 294 |
st = gr.Markdown(status_md())
|
|
@@ -303,6 +367,20 @@ with gr.Blocks(title="G1 rough-terrain training") as demo:
|
|
| 303 |
timer.tick(logs, outputs=out)
|
| 304 |
timer.tick(status_md, outputs=st)
|
| 305 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 306 |
if AUTO_START:
|
| 307 |
start()
|
| 308 |
|
|
|
|
| 17 |
|
| 18 |
import gradio as gr
|
| 19 |
|
| 20 |
+
os.environ.setdefault("MUJOCO_GL", "egl") # offscreen rendering for rollouts
|
| 21 |
+
|
| 22 |
ENV_NAME = os.environ.get("ENV_NAME", "G1JoystickRoughTerrain")
|
| 23 |
NUM_TIMESTEPS = int(os.environ.get("NUM_TIMESTEPS", 200_000_000))
|
| 24 |
SEED = int(os.environ.get("SEED", 0))
|
|
|
|
| 37 |
SNOW_FRICTION = tuple(float(v) for v in os.environ.get("SNOW_FRICTION", "0.3,0.7").split(","))
|
| 38 |
SNOW_DEPTH = tuple(float(v) for v in os.environ.get("SNOW_DEPTH", "0.0,0.08").split(","))
|
| 39 |
SURFACE = TERRAIN + ("-snow" if SNOW else "") # checkpoint prefix
|
| 40 |
+
NUM_EVALS = int(os.environ.get("NUM_EVALS", 40)) # evals (and checkpoints) per run
|
| 41 |
|
| 42 |
# /data exists only when persistent storage is attached; fall back to /tmp.
|
| 43 |
OUT = Path("/data/ckpt") if Path("/data").is_dir() else Path("/tmp/ckpt")
|
|
|
|
| 147 |
log(f"shimmed jax.{name} (removed in this JAX version)")
|
| 148 |
|
| 149 |
|
| 150 |
+
ENVS = {}
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
def build_envs():
|
| 154 |
+
"""(env, eval_env, randomization_fn) for ENV_NAME with the Himalaya terrain
|
| 155 |
+
and snow applied. Built once and cached; the rollout tab reuses eval_env."""
|
| 156 |
+
if ENVS:
|
| 157 |
+
return ENVS["env"], ENVS["eval_env"], ENVS["randomization_fn"]
|
| 158 |
+
from mujoco_playground import registry
|
| 159 |
+
|
| 160 |
+
STATE["status"] = "building env"
|
| 161 |
+
log(f"loading {ENV_NAME} ...")
|
| 162 |
+
env = registry.load(ENV_NAME)
|
| 163 |
+
env_cfg = registry.get_default_config(ENV_NAME)
|
| 164 |
+
eval_env = registry.load(ENV_NAME, config=env_cfg)
|
| 165 |
+
randomization_fn = registry.get_domain_randomizer(ENV_NAME)
|
| 166 |
+
if TERRAIN == "himalaya":
|
| 167 |
+
from himalaya_terrain import apply_terrain, make_terrains, randomizer
|
| 168 |
+
log(f"building {NUM_TERRAINS} Himalaya crops: {HIMALAYA_PATCH:.0f} m of Khumbu "
|
| 169 |
+
f"-> 20 m arena, relief {HIMALAYA_RELIEF} m ...")
|
| 170 |
+
grids = make_terrains(NUM_TERRAINS, seed=SEED, patch_m=HIMALAYA_PATCH,
|
| 171 |
+
relief=HIMALAYA_RELIEF)
|
| 172 |
+
apply_terrain(env, grids, HIMALAYA_RELIEF)
|
| 173 |
+
apply_terrain(eval_env, grids, HIMALAYA_RELIEF)
|
| 174 |
+
randomization_fn = randomizer(randomization_fn, grids)
|
| 175 |
+
log("terrain: himalaya (per-env crops via domain randomization)")
|
| 176 |
+
else:
|
| 177 |
+
log("terrain: playground stock rough terrain")
|
| 178 |
+
if SNOW:
|
| 179 |
+
from himalaya_terrain import snow_randomizer
|
| 180 |
+
randomization_fn = snow_randomizer(randomization_fn, SNOW_FRICTION, SNOW_DEPTH)
|
| 181 |
+
log(f"snow: foot-floor friction U{SNOW_FRICTION}, depth U{SNOW_DEPTH} m "
|
| 182 |
+
"(soft contact, per env)")
|
| 183 |
+
ENVS.update(env=env, eval_env=eval_env, randomization_fn=randomization_fn)
|
| 184 |
+
return env, eval_env, randomization_fn
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def net_config():
|
| 188 |
+
from mujoco_playground.config import locomotion_params
|
| 189 |
+
cfg = locomotion_params.brax_ppo_config(ENV_NAME).get("network_factory", None)
|
| 190 |
+
return dict(cfg) if cfg is not None else None
|
| 191 |
+
|
| 192 |
+
|
| 193 |
def train_worker() -> None:
|
| 194 |
try:
|
| 195 |
STATE["status"] = "importing"
|
|
|
|
| 206 |
|
| 207 |
from brax.training.agents.ppo import networks as ppo_networks
|
| 208 |
from brax.training.agents.ppo import train as ppo
|
| 209 |
+
from mujoco_playground import wrapper
|
| 210 |
from mujoco_playground.config import locomotion_params
|
| 211 |
|
| 212 |
+
env, eval_env, randomization_fn = build_envs()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 213 |
ppo_params = locomotion_params.brax_ppo_config(ENV_NAME)
|
| 214 |
ppo_params.num_timesteps = int(STATE["target"])
|
| 215 |
+
ppo_params.num_evals = NUM_EVALS # each eval = one log line + checkpoint upload
|
| 216 |
log(f"num_envs={ppo_params.get('num_envs')} "
|
| 217 |
f"batch_size={ppo_params.get('batch_size')} "
|
| 218 |
f"timesteps={int(STATE['target']):,}")
|
|
|
|
| 314 |
return "\n".join(LOG) or "(no output yet)"
|
| 315 |
|
| 316 |
|
| 317 |
+
def list_ckpts():
|
| 318 |
+
files = sorted(OUT.glob("*.pkl"), key=lambda p: p.stat().st_mtime, reverse=True)
|
| 319 |
+
return [f.name for f in files]
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def refresh_ckpts():
|
| 323 |
+
names = list_ckpts()
|
| 324 |
+
return gr.Dropdown(choices=names, value=names[0] if names else None)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def render(ckpt: str | None, vx: float, friction: float, depth: float, seconds: float):
|
| 328 |
+
"""Load a checkpoint and film the policy walking on a snowy Himalaya crop."""
|
| 329 |
+
from rollout import apply_snow, load_params, make_inference_fn, rollout, write_video
|
| 330 |
+
|
| 331 |
+
if not ckpt:
|
| 332 |
+
return None, "no checkpoint yet -- train first (or wait for ckpt_0.pkl)"
|
| 333 |
+
path = OUT / ckpt
|
| 334 |
+
if not path.exists():
|
| 335 |
+
return None, f"{ckpt} not found"
|
| 336 |
+
try:
|
| 337 |
+
_, eval_env, _ = build_envs()
|
| 338 |
+
params = load_params(path)
|
| 339 |
+
policy = make_inference_fn(eval_env, net_config())(params, deterministic=True)
|
| 340 |
+
if SNOW:
|
| 341 |
+
apply_snow(eval_env, float(friction), float(depth))
|
| 342 |
+
log(f"rollout {ckpt}: vx={vx} friction={friction} depth={depth} m, {seconds}s ...")
|
| 343 |
+
frames, info = rollout(eval_env, policy, seconds=float(seconds), command=(float(vx), 0.0, 0.0))
|
| 344 |
+
out = write_video(frames, OUT / "rollouts" / f"{path.stem}.mp4", fps=1.0 / eval_env.dt)
|
| 345 |
+
verdict = (f"fell at {info['fell_at']:.1f}s" if info["fell_at"] is not None
|
| 346 |
+
else f"stayed up for {info['seconds']:.1f}s")
|
| 347 |
+
msg = f"{ckpt}: {verdict}, walked {info['distance_m']:.2f} m (commanded {vx} m/s)"
|
| 348 |
+
log(msg)
|
| 349 |
+
return str(out), msg
|
| 350 |
+
except Exception as e:
|
| 351 |
+
log(f"rollout FAILED: {type(e).__name__}: {e}")
|
| 352 |
+
log(traceback.format_exc()[-1500:])
|
| 353 |
+
return None, f"rollout failed: {type(e).__name__}: {str(e)[:300]}"
|
| 354 |
+
|
| 355 |
+
|
| 356 |
with gr.Blocks(title="G1 rough-terrain training") as demo:
|
| 357 |
gr.Markdown("# Unitree G1 — Himalayan terrain locomotion training")
|
| 358 |
st = gr.Markdown(status_md())
|
|
|
|
| 367 |
timer.tick(logs, outputs=out)
|
| 368 |
timer.tick(status_md, outputs=st)
|
| 369 |
|
| 370 |
+
gr.Markdown("## Watch a checkpoint walk")
|
| 371 |
+
with gr.Row():
|
| 372 |
+
ckpt_dd = gr.Dropdown(choices=list_ckpts(), label="checkpoint",
|
| 373 |
+
value=(list_ckpts() or [None])[0])
|
| 374 |
+
gr.Button("Refresh").click(refresh_ckpts, outputs=ckpt_dd)
|
| 375 |
+
vx_in = gr.Slider(0.0, 1.0, value=0.5, step=0.1, label="forward speed (m/s)")
|
| 376 |
+
mu_in = gr.Slider(0.2, 1.0, value=0.5, step=0.05, label="snow friction")
|
| 377 |
+
depth_in = gr.Slider(0.0, 0.10, value=0.05, step=0.01, label="snow depth (m)")
|
| 378 |
+
secs_in = gr.Slider(2, 20, value=8, step=1, label="seconds")
|
| 379 |
+
verdict = gr.Markdown("")
|
| 380 |
+
video = gr.Video(label="rollout", autoplay=True)
|
| 381 |
+
gr.Button("Render rollout", variant="primary").click(
|
| 382 |
+
render, inputs=[ckpt_dd, vx_in, mu_in, depth_in, secs_in], outputs=[video, verdict])
|
| 383 |
+
|
| 384 |
if AUTO_START:
|
| 385 |
start()
|
| 386 |
|
requirements.txt
CHANGED
|
@@ -5,3 +5,5 @@ playground==0.2.0
|
|
| 5 |
brax>=0.12.1
|
| 6 |
huggingface_hub>=0.35
|
| 7 |
scipy>=1.10
|
|
|
|
|
|
|
|
|
| 5 |
brax>=0.12.1
|
| 6 |
huggingface_hub>=0.35
|
| 7 |
scipy>=1.10
|
| 8 |
+
imageio>=2.31
|
| 9 |
+
imageio-ffmpeg>=0.4.9
|
rollout.py
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Watch a checkpoint walk: rebuild the Brax PPO policy from a saved params
|
| 2 |
+
pickle, run it on one Himalaya/snow environment, and encode the frames to MP4.
|
| 3 |
+
|
| 4 |
+
A reward curve says whether training is moving; only a rollout says whether the
|
| 5 |
+
robot walks. `ppo.train` returns `(make_inference_fn, params, metrics)`, and the
|
| 6 |
+
checkpoints written by `policy_params_fn` are the same `params` tuple
|
| 7 |
+
`(normalizer_params, policy_params, value_params)`, so the policy is rebuilt
|
| 8 |
+
exactly the way `ppo.train` builds it: the same `network_factory` config on the
|
| 9 |
+
same env, then `make_inference_fn(params, deterministic=True)`.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import pickle
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def make_inference_fn(env, net_cfg: dict | None):
|
| 21 |
+
"""The `make_inference_fn` that `ppo.train(...)` returns, without training."""
|
| 22 |
+
from brax.training.acme import running_statistics
|
| 23 |
+
from brax.training.agents.ppo import networks as ppo_networks
|
| 24 |
+
|
| 25 |
+
ppo_network = ppo_networks.make_ppo_networks(
|
| 26 |
+
observation_size=env.observation_size,
|
| 27 |
+
action_size=env.action_size,
|
| 28 |
+
preprocess_observations_fn=running_statistics.normalize,
|
| 29 |
+
**dict(net_cfg or {}),
|
| 30 |
+
)
|
| 31 |
+
return ppo_networks.make_inference_fn(ppo_network)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def load_params(path: Path):
|
| 35 |
+
with open(path, "rb") as f:
|
| 36 |
+
params = pickle.load(f)
|
| 37 |
+
# policy_params_fn and the final return both give (normalizer, policy, value);
|
| 38 |
+
# the inference fn wants the first two.
|
| 39 |
+
return tuple(params)[:2] if len(params) == 3 else params
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def apply_snow(env, friction: float, depth: float) -> None:
|
| 43 |
+
"""Fixed snow on a single (non-randomized) Playground env: same foot-floor
|
| 44 |
+
contact-pair parameters `snow_randomizer` draws per env, then rebuild the
|
| 45 |
+
MJX model like `apply_terrain` does."""
|
| 46 |
+
from mujoco import mjx
|
| 47 |
+
|
| 48 |
+
from himalaya_terrain import snow_params
|
| 49 |
+
|
| 50 |
+
mj = env._mj_model
|
| 51 |
+
solref, solimp = snow_params(float(depth))
|
| 52 |
+
mj.pair_friction[0:2, 0:2] = friction
|
| 53 |
+
mj.pair_solref[0:2] = np.asarray(solref)
|
| 54 |
+
mj.pair_solimp[0:2] = np.asarray(solimp)
|
| 55 |
+
floor = mj.geom("floor").id # make it look like snow too
|
| 56 |
+
mj.geom_matid[floor] = -1
|
| 57 |
+
mj.geom_rgba[floor] = (0.92, 0.94, 0.98, 1.0)
|
| 58 |
+
env._mjx_model = mjx.put_model(mj, impl=env._config.impl)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def rollout(env, inference_fn, seconds: float = 8.0, command=(0.5, 0.0, 0.0),
|
| 62 |
+
seed: int = 0, width: int = 640, height: int = 480, camera: str = "track"):
|
| 63 |
+
"""Run the policy for `seconds` with a fixed joystick command and return
|
| 64 |
+
(frames, info): frames is a list of HxWx3 uint8 images at the env's control
|
| 65 |
+
rate, info has distance walked and whether it fell."""
|
| 66 |
+
import jax
|
| 67 |
+
import jax.numpy as jnp
|
| 68 |
+
|
| 69 |
+
jit_reset = jax.jit(env.reset)
|
| 70 |
+
jit_step = jax.jit(env.step)
|
| 71 |
+
jit_policy = jax.jit(inference_fn)
|
| 72 |
+
|
| 73 |
+
rng = jax.random.PRNGKey(seed)
|
| 74 |
+
state = jit_reset(rng)
|
| 75 |
+
cmd = jnp.asarray(command, dtype=jnp.float32)
|
| 76 |
+
state.info["command"] = cmd
|
| 77 |
+
|
| 78 |
+
n_steps = int(seconds / env.dt)
|
| 79 |
+
states = [state]
|
| 80 |
+
start = np.asarray(state.data.qpos[:3])
|
| 81 |
+
fell_at = None
|
| 82 |
+
for i in range(n_steps):
|
| 83 |
+
rng, key = jax.random.split(rng)
|
| 84 |
+
act, _ = jit_policy(state.obs, key)
|
| 85 |
+
state = jit_step(state, act)
|
| 86 |
+
state.info["command"] = cmd # joystick envs resample on reset only
|
| 87 |
+
states.append(state)
|
| 88 |
+
if fell_at is None and float(state.done) > 0.5:
|
| 89 |
+
fell_at = (i + 1) * env.dt
|
| 90 |
+
break
|
| 91 |
+
|
| 92 |
+
end = np.asarray(states[-1].data.qpos[:3])
|
| 93 |
+
frames = env.render(states, width=width, height=height, camera=camera)
|
| 94 |
+
info = {"seconds": len(states) * env.dt,
|
| 95 |
+
"distance_m": float(np.linalg.norm((end - start)[:2])),
|
| 96 |
+
"fell_at": fell_at}
|
| 97 |
+
return frames, info
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def write_video(frames, path: Path, fps: float) -> Path:
|
| 101 |
+
import imageio.v2 as imageio
|
| 102 |
+
|
| 103 |
+
path.parent.mkdir(parents=True, exist_ok=True)
|
| 104 |
+
with imageio.get_writer(str(path), fps=fps, codec="libx264", quality=7,
|
| 105 |
+
macro_block_size=None) as w:
|
| 106 |
+
for fr in frames:
|
| 107 |
+
w.append_data(np.asarray(fr))
|
| 108 |
+
return path
|