Spaces:
Sleeping
Sleeping
Add a fall-recovery task: TASK=getup trains a G1 get-up policy on a full-collision model
#10
by arminfg - opened
- README.md +28 -0
- app.py +36 -12
- g1_getup.py +335 -0
- g1_getup_model.py +100 -0
- rollout.py +11 -2
README.md
CHANGED
|
@@ -41,6 +41,34 @@ 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.
|
|
|
|
| 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 |
+
## Fall recovery (`TASK=getup`)
|
| 45 |
+
|
| 46 |
+
Walking and getting up are different tasks, and the joystick task cannot learn
|
| 47 |
+
the second: it ends the episode the moment the torso tips past horizontal (with
|
| 48 |
+
a −100 reward), so the policy never sees a timestep while fallen. `TASK=getup`
|
| 49 |
+
switches the Space to `g1_getup.py`, a humanoid port of Playground's `Go1Getup`:
|
| 50 |
+
60% of episodes *start* fallen (dropped from 0.5 m with a random orientation and
|
| 51 |
+
random joint angles, then left to settle), nothing terminates on being down, and
|
| 52 |
+
the reward asks for an upright torso at standing height — then, only once both
|
| 53 |
+
hold, for the nominal pose and for the policy to stop moving.
|
| 54 |
+
|
| 55 |
+
Playground's G1 is a *feet-only* collision model, so a fallen torso would drop
|
| 56 |
+
through the floor. `g1_getup_model.py` rewrites the robot XML: it enables the
|
| 57 |
+
thigh, shin and hand collision geoms the model already carries but leaves off,
|
| 58 |
+
and adds torso, pelvis and head capsules sized from the visual meshes. Body geoms
|
| 59 |
+
get `contype=2 / conaffinity=1` so they collide with the ground but never with
|
| 60 |
+
each other — without that the pelvis capsule overlaps the thighs and the standing
|
| 61 |
+
robot is blown over by its own contacts.
|
| 62 |
+
|
| 63 |
+
Observations (93) and actions (29) keep the joystick task's layout, so a fall
|
| 64 |
+
detector can hand control between a walking policy and a get-up policy at run
|
| 65 |
+
time. Checkpoints go under a `-getup` prefix. Flat ground only: `TERRAIN` and
|
| 66 |
+
`SNOW` are ignored for this task.
|
| 67 |
+
|
| 68 |
+
```
|
| 69 |
+
TASK=getup # then Start; ~100M steps
|
| 70 |
+
```
|
| 71 |
+
|
| 72 |
Training starts automatically on boot. Checkpoints are written to `/data` when
|
| 73 |
persistent storage is attached, and pushed to `HF_REPO` if that variable and a
|
| 74 |
write-scoped `HF_TOKEN` secret are set.
|
app.py
CHANGED
|
@@ -34,7 +34,11 @@ HIMALAYA_PATCH = float(os.environ.get("HIMALAYA_PATCH", 600.0)) # metres of r
|
|
| 34 |
SNOW = os.environ.get("SNOW", "1") == "1" # snow on the terrain
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
NUM_EVALS = int(os.environ.get("NUM_EVALS", 40)) # evals (and checkpoints) per run
|
| 39 |
|
| 40 |
# /data exists only when persistent storage is attached; fall back to /tmp.
|
|
@@ -156,6 +160,13 @@ def build_envs():
|
|
| 156 |
from mujoco_playground import registry
|
| 157 |
|
| 158 |
STATE["status"] = "building env"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
log(f"loading {ENV_NAME} ...")
|
| 160 |
env = registry.load(ENV_NAME)
|
| 161 |
env_cfg = registry.get_default_config(ENV_NAME)
|
|
@@ -182,9 +193,17 @@ def build_envs():
|
|
| 182 |
return env, eval_env, randomization_fn
|
| 183 |
|
| 184 |
|
| 185 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
| 186 |
from mujoco_playground.config import locomotion_params
|
| 187 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 188 |
return dict(cfg) if cfg is not None else None
|
| 189 |
|
| 190 |
|
|
@@ -205,10 +224,9 @@ def train_worker() -> None:
|
|
| 205 |
from brax.training.agents.ppo import networks as ppo_networks
|
| 206 |
from brax.training.agents.ppo import train as ppo
|
| 207 |
from mujoco_playground import wrapper
|
| 208 |
-
from mujoco_playground.config import locomotion_params
|
| 209 |
|
| 210 |
env, eval_env, randomization_fn = build_envs()
|
| 211 |
-
ppo_params =
|
| 212 |
ppo_params.num_timesteps = int(STATE["target"])
|
| 213 |
ppo_params.num_evals = NUM_EVALS # each eval = one log line + checkpoint upload
|
| 214 |
log(f"num_envs={ppo_params.get('num_envs')} "
|
|
@@ -254,7 +272,7 @@ def train_worker() -> None:
|
|
| 254 |
environment=env,
|
| 255 |
eval_env=eval_env,
|
| 256 |
wrap_env_fn=wrapper.wrap_for_brax_training,
|
| 257 |
-
randomization_fn
|
| 258 |
progress_fn=progress,
|
| 259 |
policy_params_fn=policy_params_fn,
|
| 260 |
seed=SEED,
|
|
@@ -335,14 +353,20 @@ def render(ckpt: str | None, vx: float, friction: float, depth: float, seconds:
|
|
| 335 |
_, eval_env, _ = build_envs()
|
| 336 |
params = load_params(path)
|
| 337 |
policy = make_inference_fn(eval_env, net_config())(params, deterministic=True)
|
| 338 |
-
if SNOW:
|
| 339 |
apply_snow(eval_env, float(friction), float(depth))
|
| 340 |
-
log(f"rollout {ckpt}: vx={vx} friction={friction} depth={depth} m, {seconds}s ...")
|
| 341 |
qpos, info = rollout(eval_env, policy, seconds=float(seconds), command=(float(vx), 0.0, 0.0))
|
| 342 |
out = write_video(eval_env, qpos, OUT / "rollouts" / f"{path.stem}.mp4", fps=1.0 / eval_env.dt)
|
| 343 |
-
|
| 344 |
-
|
| 345 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 346 |
log(msg)
|
| 347 |
return str(out), msg
|
| 348 |
except Exception as e:
|
|
@@ -352,7 +376,7 @@ def render(ckpt: str | None, vx: float, friction: float, depth: float, seconds:
|
|
| 352 |
|
| 353 |
|
| 354 |
with gr.Blocks(title="G1 rough-terrain training") as demo:
|
| 355 |
-
gr.Markdown("# Unitree G1 — Himalayan terrain locomotion training")
|
| 356 |
st = gr.Markdown(status_md())
|
| 357 |
with gr.Row():
|
| 358 |
steps_in = gr.Number(value=NUM_TIMESTEPS, precision=0, label="timesteps",
|
|
|
|
| 34 |
SNOW = os.environ.get("SNOW", "1") == "1" # snow on the terrain
|
| 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 |
+
# "walk" = Playground's joystick task (the terrain/snow work above).
|
| 38 |
+
# "getup" = fall recovery (g1_getup.py): most episodes start fallen, nothing
|
| 39 |
+
# terminates on being down, and the model gains torso/pelvis collision geoms.
|
| 40 |
+
TASK = os.environ.get("TASK", "walk").strip().lower()
|
| 41 |
+
SURFACE = TERRAIN + ("-snow" if SNOW else "") + ("-getup" if TASK == "getup" else "")
|
| 42 |
NUM_EVALS = int(os.environ.get("NUM_EVALS", 40)) # evals (and checkpoints) per run
|
| 43 |
|
| 44 |
# /data exists only when persistent storage is attached; fall back to /tmp.
|
|
|
|
| 160 |
from mujoco_playground import registry
|
| 161 |
|
| 162 |
STATE["status"] = "building env"
|
| 163 |
+
if TASK == "getup":
|
| 164 |
+
import g1_getup
|
| 165 |
+
log("task: getup (fall recovery) -- flat ground, full-collision G1")
|
| 166 |
+
env, eval_env = g1_getup.G1Getup(), g1_getup.G1Getup()
|
| 167 |
+
randomization_fn = None # no terrain or snow: this task is about the body
|
| 168 |
+
ENVS.update(env=env, eval_env=eval_env, randomization_fn=randomization_fn)
|
| 169 |
+
return env, eval_env, randomization_fn
|
| 170 |
log(f"loading {ENV_NAME} ...")
|
| 171 |
env = registry.load(ENV_NAME)
|
| 172 |
env_cfg = registry.get_default_config(ENV_NAME)
|
|
|
|
| 193 |
return env, eval_env, randomization_fn
|
| 194 |
|
| 195 |
|
| 196 |
+
def ppo_config():
|
| 197 |
+
"""Brax PPO config for the active task."""
|
| 198 |
+
if TASK == "getup":
|
| 199 |
+
import g1_getup
|
| 200 |
+
return g1_getup.brax_ppo_config()
|
| 201 |
from mujoco_playground.config import locomotion_params
|
| 202 |
+
return locomotion_params.brax_ppo_config(ENV_NAME)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def net_config():
|
| 206 |
+
cfg = ppo_config().get("network_factory", None)
|
| 207 |
return dict(cfg) if cfg is not None else None
|
| 208 |
|
| 209 |
|
|
|
|
| 224 |
from brax.training.agents.ppo import networks as ppo_networks
|
| 225 |
from brax.training.agents.ppo import train as ppo
|
| 226 |
from mujoco_playground import wrapper
|
|
|
|
| 227 |
|
| 228 |
env, eval_env, randomization_fn = build_envs()
|
| 229 |
+
ppo_params = ppo_config()
|
| 230 |
ppo_params.num_timesteps = int(STATE["target"])
|
| 231 |
ppo_params.num_evals = NUM_EVALS # each eval = one log line + checkpoint upload
|
| 232 |
log(f"num_envs={ppo_params.get('num_envs')} "
|
|
|
|
| 272 |
environment=env,
|
| 273 |
eval_env=eval_env,
|
| 274 |
wrap_env_fn=wrapper.wrap_for_brax_training,
|
| 275 |
+
**({"randomization_fn": randomization_fn} if randomization_fn else {}),
|
| 276 |
progress_fn=progress,
|
| 277 |
policy_params_fn=policy_params_fn,
|
| 278 |
seed=SEED,
|
|
|
|
| 353 |
_, eval_env, _ = build_envs()
|
| 354 |
params = load_params(path)
|
| 355 |
policy = make_inference_fn(eval_env, net_config())(params, deterministic=True)
|
| 356 |
+
if SNOW and TASK != "getup":
|
| 357 |
apply_snow(eval_env, float(friction), float(depth))
|
| 358 |
+
log(f"rollout {ckpt}: task={TASK} vx={vx} friction={friction} depth={depth} m, {seconds}s ...")
|
| 359 |
qpos, info = rollout(eval_env, policy, seconds=float(seconds), command=(float(vx), 0.0, 0.0))
|
| 360 |
out = write_video(eval_env, qpos, OUT / "rollouts" / f"{path.stem}.mp4", fps=1.0 / eval_env.dt)
|
| 361 |
+
if TASK == "getup":
|
| 362 |
+
# Root height: ~0.76 m standing, ~0.1-0.3 m sprawled.
|
| 363 |
+
msg = (f"{ckpt}: started at {info['start_height_m']:.2f} m, ended at "
|
| 364 |
+
f"{info['end_height_m']:.2f} m (peak {info['peak_height_m']:.2f}; "
|
| 365 |
+
f"standing is ~0.76 m)")
|
| 366 |
+
else:
|
| 367 |
+
verdict = (f"fell at {info['fell_at']:.1f}s" if info["fell_at"] is not None
|
| 368 |
+
else f"stayed up for {info['seconds']:.1f}s")
|
| 369 |
+
msg = f"{ckpt}: {verdict}, walked {info['distance_m']:.2f} m (commanded {vx} m/s)"
|
| 370 |
log(msg)
|
| 371 |
return str(out), msg
|
| 372 |
except Exception as e:
|
|
|
|
| 376 |
|
| 377 |
|
| 378 |
with gr.Blocks(title="G1 rough-terrain training") as demo:
|
| 379 |
+
gr.Markdown(f"# Unitree G1 — {'fall recovery' if TASK == 'getup' else 'Himalayan terrain locomotion'} training")
|
| 380 |
st = gr.Markdown(status_md())
|
| 381 |
with gr.Row():
|
| 382 |
steps_in = gr.Number(value=NUM_TIMESTEPS, precision=0, label="timesteps",
|
g1_getup.py
ADDED
|
@@ -0,0 +1,335 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fall recovery for the Unitree G1 -- a humanoid port of Playground's Go1Getup.
|
| 2 |
+
|
| 3 |
+
Walking and getting up are different tasks, and the joystick task cannot learn
|
| 4 |
+
the second one: `G1JoystickRoughTerrain._get_termination` ends the episode the
|
| 5 |
+
moment the torso tips past horizontal (with a -100 reward), so the policy never
|
| 6 |
+
sees a single timestep while fallen.
|
| 7 |
+
|
| 8 |
+
This env inverts that. Most episodes *start* fallen -- the robot is dropped from
|
| 9 |
+
0.5 m with a random orientation and random joint angles, then allowed to settle
|
| 10 |
+
-- and nothing terminates on being down. The reward asks for an upright torso at
|
| 11 |
+
standing height, and only once both hold does it ask for the nominal pose and
|
| 12 |
+
for the policy to stop moving.
|
| 13 |
+
|
| 14 |
+
It runs on the collision model from `g1_getup_model`, because Playground's G1 is
|
| 15 |
+
feet-only and a fallen torso would otherwise fall through the floor.
|
| 16 |
+
|
| 17 |
+
Observations and the action space match the joystick task's layout (29 joints,
|
| 18 |
+
gyro + up-vector + joint state + last action), so the two policies can be
|
| 19 |
+
switched between at run time by a fall detector.
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
from __future__ import annotations
|
| 23 |
+
|
| 24 |
+
from typing import Any, Dict, Optional, Union
|
| 25 |
+
|
| 26 |
+
import jax
|
| 27 |
+
import jax.numpy as jp
|
| 28 |
+
import mujoco
|
| 29 |
+
import numpy as np
|
| 30 |
+
from ml_collections import config_dict
|
| 31 |
+
from mujoco import mjx
|
| 32 |
+
|
| 33 |
+
from mujoco_playground._src import mjx_env
|
| 34 |
+
from mujoco_playground._src.locomotion.g1 import base as g1_base
|
| 35 |
+
|
| 36 |
+
from g1_getup_model import build_scene
|
| 37 |
+
|
| 38 |
+
# Torso-site height standing in the "knees_bent" keyframe is 0.949 m; ask for a
|
| 39 |
+
# little less so the target is comfortably reachable.
|
| 40 |
+
STANDING_TORSO_HEIGHT = 0.90
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def default_config() -> config_dict.ConfigDict:
|
| 44 |
+
return config_dict.create(
|
| 45 |
+
ctrl_dt=0.02,
|
| 46 |
+
sim_dt=0.002,
|
| 47 |
+
episode_length=400, # 8 s -- getting a humanoid up takes longer than a quadruped
|
| 48 |
+
drop_from_height_prob=0.6,
|
| 49 |
+
settle_time=0.5,
|
| 50 |
+
action_repeat=1,
|
| 51 |
+
action_scale=0.5,
|
| 52 |
+
restricted_joint_range=False, # recovery needs the full range of motion
|
| 53 |
+
soft_joint_pos_limit_factor=0.95,
|
| 54 |
+
energy_termination_threshold=np.inf,
|
| 55 |
+
noise_config=config_dict.create(
|
| 56 |
+
level=1.0,
|
| 57 |
+
scales=config_dict.create(
|
| 58 |
+
joint_pos=0.03,
|
| 59 |
+
joint_vel=1.5,
|
| 60 |
+
gyro=0.2,
|
| 61 |
+
gravity=0.05,
|
| 62 |
+
),
|
| 63 |
+
),
|
| 64 |
+
reward_config=config_dict.create(
|
| 65 |
+
scales=config_dict.create(
|
| 66 |
+
orientation=1.0,
|
| 67 |
+
torso_height=1.0,
|
| 68 |
+
posture=1.0,
|
| 69 |
+
stand_still=1.0,
|
| 70 |
+
action_rate=-0.001,
|
| 71 |
+
dof_pos_limits=-0.1,
|
| 72 |
+
torques=-1e-5,
|
| 73 |
+
dof_acc=-2.5e-7,
|
| 74 |
+
dof_vel=-0.1,
|
| 75 |
+
),
|
| 76 |
+
),
|
| 77 |
+
impl="warp",
|
| 78 |
+
naconmax=80 * 8192, # a fallen humanoid makes far more contacts than a walking one
|
| 79 |
+
njmax=500,
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class G1Getup(g1_base.G1Env):
|
| 84 |
+
"""Recover from a fall and stand up.
|
| 85 |
+
|
| 86 |
+
Observation (state, 93): gyro (3), torso up-vector (3), joint angles minus
|
| 87 |
+
the nominal pose (29), joint velocities (29), last action (29).
|
| 88 |
+
|
| 89 |
+
Action (29): joint targets, scaled and added to the *current* joint angles
|
| 90 |
+
rather than to the nominal pose -- as in Go1Getup, this gives a policy that
|
| 91 |
+
starts in an arbitrary sprawl a much wider initial range of motion.
|
| 92 |
+
|
| 93 |
+
Reward: upright torso, torso at standing height, and -- gated on both of
|
| 94 |
+
those already holding -- the nominal posture and zero action, plus the usual
|
| 95 |
+
torque / action-rate / joint-limit regularizers.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
def __init__(
|
| 99 |
+
self,
|
| 100 |
+
config: config_dict.ConfigDict = default_config(),
|
| 101 |
+
config_overrides: Optional[Dict[str, Union[str, int, list[Any]]]] = None,
|
| 102 |
+
) -> None:
|
| 103 |
+
# G1Env.__init__ compiles from an XML path; this task needs the generated
|
| 104 |
+
# full-collision model instead, so set the model up here and skip it.
|
| 105 |
+
mjx_env.MjxEnv.__init__(self, config, config_overrides)
|
| 106 |
+
scene, assets = build_scene()
|
| 107 |
+
self._model_assets = assets
|
| 108 |
+
self._mj_model = mujoco.MjModel.from_xml_string(scene, assets=assets)
|
| 109 |
+
self._mj_model.opt.timestep = self.sim_dt
|
| 110 |
+
self._mj_model.vis.global_.offwidth = 3840
|
| 111 |
+
self._mj_model.vis.global_.offheight = 2160
|
| 112 |
+
self._mjx_model = mjx.put_model(self._mj_model, impl=self._config.impl)
|
| 113 |
+
self._xml_path = "<generated by g1_getup_model.build_scene>"
|
| 114 |
+
self._post_init()
|
| 115 |
+
|
| 116 |
+
def _post_init(self) -> None:
|
| 117 |
+
self._init_q = jp.array(self._mj_model.keyframe("knees_bent").qpos)
|
| 118 |
+
self._default_pose = jp.array(self._mj_model.keyframe("knees_bent").qpos[7:])
|
| 119 |
+
|
| 120 |
+
# First joint is the freejoint.
|
| 121 |
+
self._lowers, self._uppers = self.mj_model.jnt_range[1:].T
|
| 122 |
+
c = (self._lowers + self._uppers) / 2
|
| 123 |
+
r = self._uppers - self._lowers
|
| 124 |
+
self._soft_lowers = c - 0.5 * r * self._config.soft_joint_pos_limit_factor
|
| 125 |
+
self._soft_uppers = c + 0.5 * r * self._config.soft_joint_pos_limit_factor
|
| 126 |
+
|
| 127 |
+
self._settle_steps = int(self._config.settle_time / self.sim_dt)
|
| 128 |
+
self._z_des = STANDING_TORSO_HEIGHT
|
| 129 |
+
# The G1's "gravity" sensor is an up-vector: +z when upright (the joystick
|
| 130 |
+
# task calls it fallen at < 0), the opposite sign to Go1's convention.
|
| 131 |
+
self._up_vec = jp.array([0.0, 0.0, 1.0])
|
| 132 |
+
self._torso_site_id = self._mj_model.site("imu_in_torso").id
|
| 133 |
+
|
| 134 |
+
# -- episode ------------------------------------------------------------
|
| 135 |
+
|
| 136 |
+
def _get_random_qpos(self, rng: jax.Array) -> jax.Array:
|
| 137 |
+
"""A sprawl: 0.5 m up, random orientation, random joint angles."""
|
| 138 |
+
rng, orientation_rng, qpos_rng = jax.random.split(rng, 3)
|
| 139 |
+
|
| 140 |
+
qpos = jp.zeros(self.mjx_model.nq)
|
| 141 |
+
qpos = qpos.at[2].set(0.5)
|
| 142 |
+
quat = jax.random.normal(orientation_rng, (4,))
|
| 143 |
+
quat /= jp.linalg.norm(quat) + 1e-6
|
| 144 |
+
qpos = qpos.at[3:7].set(quat)
|
| 145 |
+
qpos = qpos.at[7:].set(
|
| 146 |
+
jax.random.uniform(qpos_rng, (self.mjx_model.nu,),
|
| 147 |
+
minval=self._lowers, maxval=self._uppers)
|
| 148 |
+
)
|
| 149 |
+
return qpos
|
| 150 |
+
|
| 151 |
+
def reset(self, rng: jax.Array) -> mjx_env.State:
|
| 152 |
+
rng, key1, key2 = jax.random.split(rng, 3)
|
| 153 |
+
qpos = jp.where(
|
| 154 |
+
jax.random.bernoulli(key1, self._config.drop_from_height_prob),
|
| 155 |
+
self._get_random_qpos(key2),
|
| 156 |
+
self._init_q,
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
rng, key = jax.random.split(rng)
|
| 160 |
+
qvel = jp.zeros(self.mjx_model.nv)
|
| 161 |
+
qvel = qvel.at[0:6].set(jax.random.uniform(key, (6,), minval=-0.5, maxval=0.5))
|
| 162 |
+
|
| 163 |
+
data = mjx_env.make_data(
|
| 164 |
+
self.mj_model, qpos=qpos, qvel=qvel, ctrl=qpos[7:],
|
| 165 |
+
impl=self.mjx_model.impl.value,
|
| 166 |
+
naconmax=self._config.naconmax, njmax=self._config.njmax,
|
| 167 |
+
)
|
| 168 |
+
data = mjx.forward(self.mjx_model, data)
|
| 169 |
+
# Let it flop and come to rest before the episode starts, so the policy
|
| 170 |
+
# is asked to recover from a settled pose rather than mid-air.
|
| 171 |
+
data = mjx_env.step(self.mjx_model, data, qpos[7:], self._settle_steps)
|
| 172 |
+
data = data.replace(time=0.0)
|
| 173 |
+
|
| 174 |
+
info = {
|
| 175 |
+
"rng": rng,
|
| 176 |
+
"last_act": jp.zeros(self.mjx_model.nu),
|
| 177 |
+
"last_last_act": jp.zeros(self.mjx_model.nu),
|
| 178 |
+
}
|
| 179 |
+
metrics = {f"reward/{k}": jp.zeros(())
|
| 180 |
+
for k in self._config.reward_config.scales.keys()}
|
| 181 |
+
metrics["torso_height"] = jp.zeros(())
|
| 182 |
+
|
| 183 |
+
obs = self._get_obs(data, info)
|
| 184 |
+
reward, done = jp.zeros(2)
|
| 185 |
+
return mjx_env.State(data, obs, reward, done, metrics, info)
|
| 186 |
+
|
| 187 |
+
def step(self, state: mjx_env.State, action: jax.Array) -> mjx_env.State:
|
| 188 |
+
motor_targets = state.data.qpos[7:] + action * self._config.action_scale
|
| 189 |
+
data = mjx_env.step(self.mjx_model, state.data, motor_targets, self.n_substeps)
|
| 190 |
+
|
| 191 |
+
obs = self._get_obs(data, state.info)
|
| 192 |
+
done = self._get_termination(data)
|
| 193 |
+
|
| 194 |
+
rewards = self._get_reward(data, action, state.info)
|
| 195 |
+
rewards = {k: v * self._config.reward_config.scales[k]
|
| 196 |
+
for k, v in rewards.items()}
|
| 197 |
+
reward = jp.clip(sum(rewards.values()) * self.dt, 0.0, 10000.0)
|
| 198 |
+
|
| 199 |
+
state.info["last_last_act"] = state.info["last_act"]
|
| 200 |
+
state.info["last_act"] = action
|
| 201 |
+
for k, v in rewards.items():
|
| 202 |
+
state.metrics[f"reward/{k}"] = v
|
| 203 |
+
state.metrics["torso_height"] = data.site_xpos[self._torso_site_id][2]
|
| 204 |
+
|
| 205 |
+
return state.replace(data=data, obs=obs, reward=reward, done=jp.float32(done))
|
| 206 |
+
|
| 207 |
+
def _get_termination(self, data: mjx.Data) -> jax.Array:
|
| 208 |
+
# Deliberately no fall termination: being down is the starting state.
|
| 209 |
+
energy = jp.sum(jp.abs(data.actuator_force * data.qvel[6:]))
|
| 210 |
+
return energy > self._config.energy_termination_threshold
|
| 211 |
+
|
| 212 |
+
# -- observation --------------------------------------------------------
|
| 213 |
+
|
| 214 |
+
def _noisy(self, info: dict[str, Any], value: jax.Array, scale: float) -> jax.Array:
|
| 215 |
+
info["rng"], noise_rng = jax.random.split(info["rng"])
|
| 216 |
+
noise = (2 * jax.random.uniform(noise_rng, shape=value.shape) - 1)
|
| 217 |
+
return value + noise * self._config.noise_config.level * scale
|
| 218 |
+
|
| 219 |
+
def _get_obs(self, data: mjx.Data, info: dict[str, Any]) -> Dict[str, jax.Array]:
|
| 220 |
+
scales = self._config.noise_config.scales
|
| 221 |
+
gyro = self.get_gyro(data, "torso")
|
| 222 |
+
gravity = self.get_gravity(data, "torso")
|
| 223 |
+
joint_angles = data.qpos[7:]
|
| 224 |
+
joint_vel = data.qvel[6:]
|
| 225 |
+
|
| 226 |
+
state = jp.concatenate([
|
| 227 |
+
self._noisy(info, gyro, scales.gyro), # 3
|
| 228 |
+
self._noisy(info, gravity, scales.gravity), # 3
|
| 229 |
+
self._noisy(info, joint_angles, scales.joint_pos) - self._default_pose, # 29
|
| 230 |
+
self._noisy(info, joint_vel, scales.joint_vel), # 29
|
| 231 |
+
info["last_act"], # 29
|
| 232 |
+
])
|
| 233 |
+
|
| 234 |
+
privileged_state = jp.hstack([
|
| 235 |
+
state,
|
| 236 |
+
gyro,
|
| 237 |
+
self.get_accelerometer(data, "torso"),
|
| 238 |
+
self.get_local_linvel(data, "torso"),
|
| 239 |
+
self.get_global_angvel(data, "torso"),
|
| 240 |
+
joint_angles,
|
| 241 |
+
joint_vel,
|
| 242 |
+
data.actuator_force,
|
| 243 |
+
data.site_xpos[self._torso_site_id][2],
|
| 244 |
+
])
|
| 245 |
+
|
| 246 |
+
return {"state": state, "privileged_state": privileged_state}
|
| 247 |
+
|
| 248 |
+
# -- reward -------------------------------------------------------------
|
| 249 |
+
|
| 250 |
+
def _get_reward(self, data: mjx.Data, action: jax.Array,
|
| 251 |
+
info: dict[str, Any]) -> dict[str, jax.Array]:
|
| 252 |
+
torso_height = data.site_xpos[self._torso_site_id][2]
|
| 253 |
+
joint_angles = data.qpos[7:]
|
| 254 |
+
gravity = self.get_gravity(data, "torso")
|
| 255 |
+
|
| 256 |
+
gate = self._is_upright(gravity) * self._is_at_desired_height(torso_height)
|
| 257 |
+
|
| 258 |
+
return {
|
| 259 |
+
"orientation": self._reward_orientation(gravity),
|
| 260 |
+
"torso_height": self._reward_height(torso_height),
|
| 261 |
+
"posture": self._reward_posture(joint_angles, self._is_upright(gravity)),
|
| 262 |
+
"stand_still": self._reward_stand_still(action, gate),
|
| 263 |
+
"action_rate": self._cost_action_rate(action, info),
|
| 264 |
+
"torques": self._cost_torques(data.actuator_force),
|
| 265 |
+
"dof_pos_limits": self._cost_joint_pos_limits(joint_angles),
|
| 266 |
+
"dof_acc": self._cost_dof_acc(data.qacc[6:]),
|
| 267 |
+
"dof_vel": self._cost_dof_vel(data.qvel[6:]),
|
| 268 |
+
}
|
| 269 |
+
|
| 270 |
+
def _is_upright(self, up_vec: jax.Array, ori_tol: float = 0.05) -> jax.Array:
|
| 271 |
+
return jp.sum(jp.square(self._up_vec - up_vec)) < ori_tol
|
| 272 |
+
|
| 273 |
+
def _is_at_desired_height(self, torso_height: jax.Array,
|
| 274 |
+
pos_tol: float = 0.02) -> jax.Array:
|
| 275 |
+
height = jp.minimum(torso_height, self._z_des)
|
| 276 |
+
return (self._z_des - height) < pos_tol
|
| 277 |
+
|
| 278 |
+
def _reward_orientation(self, up_vec: jax.Array) -> jax.Array:
|
| 279 |
+
return jp.exp(-2.0 * jp.sum(jp.square(self._up_vec - up_vec)))
|
| 280 |
+
|
| 281 |
+
def _reward_height(self, torso_height: jax.Array) -> jax.Array:
|
| 282 |
+
return jp.exp(jp.minimum(torso_height, self._z_des)) - 1.0
|
| 283 |
+
|
| 284 |
+
def _reward_posture(self, joint_angles: jax.Array, gate: jax.Array) -> jax.Array:
|
| 285 |
+
return gate * jp.exp(-0.5 * jp.sum(jp.square(joint_angles - self._default_pose)))
|
| 286 |
+
|
| 287 |
+
def _reward_stand_still(self, act: jax.Array, gate: jax.Array) -> jax.Array:
|
| 288 |
+
return gate * jp.exp(-0.5 * jp.sum(jp.square(act)))
|
| 289 |
+
|
| 290 |
+
def _cost_torques(self, torques: jax.Array) -> jax.Array:
|
| 291 |
+
return jp.sqrt(jp.sum(jp.square(torques))) + jp.sum(jp.abs(torques))
|
| 292 |
+
|
| 293 |
+
def _cost_action_rate(self, act: jax.Array, info: dict[str, Any]) -> jax.Array:
|
| 294 |
+
c1 = jp.sum(jp.square(act - info["last_act"]))
|
| 295 |
+
c2 = jp.sum(jp.square(act - 2 * info["last_act"] + info["last_last_act"]))
|
| 296 |
+
return c1 + c2
|
| 297 |
+
|
| 298 |
+
def _cost_joint_pos_limits(self, qpos: jax.Array) -> jax.Array:
|
| 299 |
+
out_of_limits = -jp.clip(qpos - self._soft_lowers, None, 0.0)
|
| 300 |
+
out_of_limits += jp.clip(qpos - self._soft_uppers, 0.0, None)
|
| 301 |
+
return jp.sum(out_of_limits)
|
| 302 |
+
|
| 303 |
+
def _cost_dof_vel(self, qvel: jax.Array) -> jax.Array:
|
| 304 |
+
return jp.sum(jp.square(jp.maximum(jp.abs(qvel) - 2.0 * jp.pi, 0.0)))
|
| 305 |
+
|
| 306 |
+
def _cost_dof_acc(self, qacc: jax.Array) -> jax.Array:
|
| 307 |
+
return jp.sum(jp.square(qacc))
|
| 308 |
+
|
| 309 |
+
|
| 310 |
+
def brax_ppo_config(num_timesteps: int = 100_000_000) -> config_dict.ConfigDict:
|
| 311 |
+
"""PPO config for the get-up task, following Playground's Go1Getup recipe
|
| 312 |
+
(short episodes, more parallel envs than the joystick task needs)."""
|
| 313 |
+
return config_dict.create(
|
| 314 |
+
num_timesteps=num_timesteps,
|
| 315 |
+
num_evals=40,
|
| 316 |
+
reward_scaling=1.0,
|
| 317 |
+
episode_length=default_config().episode_length,
|
| 318 |
+
normalize_observations=True,
|
| 319 |
+
action_repeat=1,
|
| 320 |
+
unroll_length=20,
|
| 321 |
+
num_minibatches=32,
|
| 322 |
+
num_updates_per_batch=4,
|
| 323 |
+
discounting=0.97,
|
| 324 |
+
learning_rate=3e-4,
|
| 325 |
+
entropy_cost=0.005,
|
| 326 |
+
num_envs=8192,
|
| 327 |
+
batch_size=256,
|
| 328 |
+
max_grad_norm=1.0,
|
| 329 |
+
network_factory=config_dict.create(
|
| 330 |
+
policy_hidden_layer_sizes=(512, 256, 128),
|
| 331 |
+
value_hidden_layer_sizes=(512, 256, 128),
|
| 332 |
+
policy_obs_key="state",
|
| 333 |
+
value_obs_key="privileged_state",
|
| 334 |
+
),
|
| 335 |
+
)
|
g1_getup_model.py
ADDED
|
@@ -0,0 +1,100 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""A G1 model that can lie on the ground.
|
| 2 |
+
|
| 3 |
+
Playground's `G1JoystickRoughTerrain` is a *feet-only* collision model: the two
|
| 4 |
+
foot boxes touch the floor through explicit `<pair>`s and every other geom has
|
| 5 |
+
`contype=0` from the `g1` default class. That is right for walking (it is much
|
| 6 |
+
cheaper) and useless for fall recovery -- a fallen torso passes straight through
|
| 7 |
+
the floor, so there is nothing to push off.
|
| 8 |
+
|
| 9 |
+
This module rewrites Playground's robot XML into a get-up variant:
|
| 10 |
+
|
| 11 |
+
* turns on the collision geoms the model already carries but leaves disabled
|
| 12 |
+
(thighs, shins, hands), with condim=3 so they can push rather than slide;
|
| 13 |
+
* adds the collision bodies it does not carry at all -- a torso capsule, a
|
| 14 |
+
pelvis capsule and a head sphere, sized from the visual meshes.
|
| 15 |
+
|
| 16 |
+
Everything else -- actuators, sensors, keyframes, contact pairs -- is inherited
|
| 17 |
+
unchanged, so observations and the action space stay identical to the joystick
|
| 18 |
+
task and a walking policy remains loadable against this model.
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
from __future__ import annotations
|
| 22 |
+
|
| 23 |
+
import re
|
| 24 |
+
|
| 25 |
+
from mujoco_playground._src.locomotion.g1 import base as g1_base
|
| 26 |
+
from mujoco_playground._src.locomotion.g1 import g1_constants as consts
|
| 27 |
+
|
| 28 |
+
ROBOT_XML = consts.ROOT_PATH / "xmls" / "g1_mjx_feetonly.xml"
|
| 29 |
+
SCENE_XML = consts.FEET_ONLY_FLAT_TERRAIN_XML
|
| 30 |
+
GETUP_ROBOT_NAME = "g1_mjx_getup.xml"
|
| 31 |
+
|
| 32 |
+
# Existing collision geoms that the g1 default class disables.
|
| 33 |
+
ENABLE_COLLISION = (
|
| 34 |
+
"left_thigh", "right_thigh",
|
| 35 |
+
"left_shin", "right_shin",
|
| 36 |
+
"left_hand_collision", "right_hand_collision",
|
| 37 |
+
)
|
| 38 |
+
# contype=2 / conaffinity=1 against a floor of contype=1 / conaffinity=1 means
|
| 39 |
+
# "collide with the ground, never with each other": (2 & 1) == 0 for two body
|
| 40 |
+
# geoms, while (floor.contype & body.conaffinity) == 1. Without this the pelvis
|
| 41 |
+
# capsule overlaps the thigh capsules at the standing pose and the robot is
|
| 42 |
+
# blown over by its own self-contacts. Self-collision is out of scope here, as
|
| 43 |
+
# it is for the walking task.
|
| 44 |
+
CONTACT_ATTRS = 'contype="2" conaffinity="1" condim="3" priority="1" friction="0.6"'
|
| 45 |
+
|
| 46 |
+
# Collision bodies the model lacks, sized from the visual mesh AABBs:
|
| 47 |
+
# pelvis mesh spans z in [-0.14, 0.0] and is ~0.14 wide; the torso mesh spans
|
| 48 |
+
# z in [-0.01, 0.31] with the head above it at 0.385.
|
| 49 |
+
PELVIS_GEOM = (
|
| 50 |
+
f'<geom name="pelvis_collision" type="capsule" group="3" '
|
| 51 |
+
f'fromto="0 -0.045 -0.075 0 0.045 -0.075" size="0.085" {CONTACT_ATTRS}/>'
|
| 52 |
+
)
|
| 53 |
+
TORSO_GEOM = (
|
| 54 |
+
f'<geom name="torso_collision" type="capsule" group="3" '
|
| 55 |
+
f'fromto="0 0 0.03 0 0 0.30" size="0.11" {CONTACT_ATTRS}/>'
|
| 56 |
+
)
|
| 57 |
+
HEAD_GEOM = (
|
| 58 |
+
f'<geom name="head_collision" type="sphere" group="3" '
|
| 59 |
+
f'pos="0.008 0 0.385" size="0.09" {CONTACT_ATTRS}/>'
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
# Anchor on the body open tags: the visual geoms are duplicated in the XML.
|
| 63 |
+
PELVIS_ANCHOR = re.compile(r'(<body\s+name="pelvis"[^>]*>)')
|
| 64 |
+
TORSO_ANCHOR = re.compile(r'(<body\s+name="torso_link"[^>]*>)')
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def _enable(xml: str, name: str) -> str:
|
| 68 |
+
"""Give the named geom real contact parameters."""
|
| 69 |
+
pat = re.compile(rf'(<geom\s+name="{re.escape(name)}"\s+class="collision")')
|
| 70 |
+
xml, n = pat.subn(rf'\1 {CONTACT_ATTRS}', xml)
|
| 71 |
+
if n != 1:
|
| 72 |
+
raise RuntimeError(f"collision geom {name!r} not found in {ROBOT_XML.name} "
|
| 73 |
+
f"({n} matches) -- Playground's G1 XML has changed")
|
| 74 |
+
return xml
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def build_robot_xml() -> str:
|
| 78 |
+
# Playground's XML keeps alternative collision shapes commented out, and a
|
| 79 |
+
# commented `<geom name="left_shin" ...>` is indistinguishable from a live
|
| 80 |
+
# one to a regex -- drop comments first so the anchors are unambiguous.
|
| 81 |
+
xml = re.sub(r"<!--.*?-->", "", ROBOT_XML.read_text(), flags=re.S)
|
| 82 |
+
for name in ENABLE_COLLISION:
|
| 83 |
+
xml = _enable(xml, name)
|
| 84 |
+
for anchor, added in ((PELVIS_ANCHOR, PELVIS_GEOM),
|
| 85 |
+
(TORSO_ANCHOR, TORSO_GEOM + "\n " + HEAD_GEOM)):
|
| 86 |
+
xml, n = anchor.subn(rf"\1\n {added}", xml)
|
| 87 |
+
if n != 1:
|
| 88 |
+
raise RuntimeError(f"anchor {anchor.pattern} matched {n} times, expected 1 -- "
|
| 89 |
+
"Playground's G1 XML has changed")
|
| 90 |
+
return xml
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def build_scene() -> tuple[str, dict[str, bytes]]:
|
| 94 |
+
"""(scene XML string, assets) for a G1 that collides with the ground."""
|
| 95 |
+
scene = SCENE_XML.read_text().replace(ROBOT_XML.name, GETUP_ROBOT_NAME)
|
| 96 |
+
if GETUP_ROBOT_NAME not in scene:
|
| 97 |
+
raise RuntimeError("scene does not include the robot XML by name")
|
| 98 |
+
assets = g1_base.get_assets()
|
| 99 |
+
assets[GETUP_ROBOT_NAME] = build_robot_xml().encode()
|
| 100 |
+
return scene, assets
|
rollout.py
CHANGED
|
@@ -72,8 +72,13 @@ def rollout(env, inference_fn, seconds: float = 8.0, command=(0.5, 0.0, 0.0), se
|
|
| 72 |
|
| 73 |
rng = jax.random.PRNGKey(seed)
|
| 74 |
state = jit_reset(rng)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 75 |
cmd = jnp.asarray(command, dtype=jnp.float32)
|
| 76 |
-
|
|
|
|
| 77 |
|
| 78 |
n_steps = int(seconds / env.dt)
|
| 79 |
qpos = [np.asarray(state.data.qpos)]
|
|
@@ -82,7 +87,8 @@ def rollout(env, inference_fn, seconds: float = 8.0, command=(0.5, 0.0, 0.0), se
|
|
| 82 |
rng, key = jax.random.split(rng)
|
| 83 |
act, _ = jit_policy(state.obs, key)
|
| 84 |
state = jit_step(state, act)
|
| 85 |
-
|
|
|
|
| 86 |
qpos.append(np.asarray(state.data.qpos))
|
| 87 |
if fell_at is None and float(state.done) > 0.5:
|
| 88 |
fell_at = (i + 1) * env.dt
|
|
@@ -91,6 +97,9 @@ def rollout(env, inference_fn, seconds: float = 8.0, command=(0.5, 0.0, 0.0), se
|
|
| 91 |
qpos = np.stack(qpos)
|
| 92 |
info = {"seconds": len(qpos) * env.dt,
|
| 93 |
"distance_m": float(np.linalg.norm((qpos[-1, :2] - qpos[0, :2]))),
|
|
|
|
|
|
|
|
|
|
| 94 |
"fell_at": fell_at}
|
| 95 |
return qpos, info
|
| 96 |
|
|
|
|
| 72 |
|
| 73 |
rng = jax.random.PRNGKey(seed)
|
| 74 |
state = jit_reset(rng)
|
| 75 |
+
# The joystick task steers by a "command" in info; the get-up task has no
|
| 76 |
+
# such key, and adding one would change the State pytree the step function
|
| 77 |
+
# was traced against.
|
| 78 |
+
steerable = "command" in state.info
|
| 79 |
cmd = jnp.asarray(command, dtype=jnp.float32)
|
| 80 |
+
if steerable:
|
| 81 |
+
state.info["command"] = cmd
|
| 82 |
|
| 83 |
n_steps = int(seconds / env.dt)
|
| 84 |
qpos = [np.asarray(state.data.qpos)]
|
|
|
|
| 87 |
rng, key = jax.random.split(rng)
|
| 88 |
act, _ = jit_policy(state.obs, key)
|
| 89 |
state = jit_step(state, act)
|
| 90 |
+
if steerable:
|
| 91 |
+
state.info["command"] = cmd # joystick envs resample on reset only
|
| 92 |
qpos.append(np.asarray(state.data.qpos))
|
| 93 |
if fell_at is None and float(state.done) > 0.5:
|
| 94 |
fell_at = (i + 1) * env.dt
|
|
|
|
| 97 |
qpos = np.stack(qpos)
|
| 98 |
info = {"seconds": len(qpos) * env.dt,
|
| 99 |
"distance_m": float(np.linalg.norm((qpos[-1, :2] - qpos[0, :2]))),
|
| 100 |
+
"start_height_m": float(qpos[0, 2]),
|
| 101 |
+
"end_height_m": float(qpos[-1, 2]),
|
| 102 |
+
"peak_height_m": float(qpos[:, 2].max()),
|
| 103 |
"fell_at": fell_at}
|
| 104 |
return qpos, info
|
| 105 |
|