add modified sru-navigation-sim (added go2 code)

This commit is contained in:
MattMa
2026-07-13 15:13:55 +08:00
parent 9e8f17bab0
commit 58b25cb40a
86 changed files with 10524 additions and 0 deletions
@@ -0,0 +1,221 @@
#!/usr/bin/env python3
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Depth-ablation diagnostic for a trained navigation policy.
Question this answers: *does the policy actually use the depth-camera input,
or has it learned to ignore it (perception-blind)?*
Method
------
1. Load the trained actor-critic exactly like ``play.py``.
2. Locate the ``depth_image`` slice inside the concatenated *policy* observation.
3. Roll the env out with the REAL on-policy actions, and at every step also
compute a counterfactual action where the depth slice is zeroed. Compare.
4. Also track the depth-feature statistics (std over envs/time) so we can tell
a *dead sensor* (constant features) apart from a policy that *ignores*
informative features.
Verdict logic (printed at the end)
----------------------------------
* depth features ~constant (std ~ 0) -> SENSOR/ENCODER dead (no signal)
* features vary, zeroing barely changes action -> LEARNED-BLIND (ignores depth)
* features vary, zeroing changes action a lot -> policy DOES use depth
Usage (inside container, mirrors play.py):
./isaaclab.sh -p source/isaaclab_nav_task/scripts/ablate_depth.py \
--task Isaac-Nav-PPO-Go2-Play-v0 --num_envs 16 \
--checkpoint <path/model_6998.pt> --steps 300 --headless
"""
from __future__ import annotations
import argparse
import sys
from isaaclab.app import AppLauncher
parser = argparse.ArgumentParser(description="Depth-ablation diagnostic for a navigation policy.")
parser.add_argument("--num_envs", type=int, default=16, help="Number of environments to simulate.")
parser.add_argument("--task", type=str, default=None, help="Name of the task (use a *-Play-v0 variant).")
parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint (.pt).")
parser.add_argument("--steps", type=int, default=300, help="Number of env steps to roll out.")
parser.add_argument("--warmup", type=int, default=20, help="Steps to skip before collecting stats (let resets settle).")
parser.add_argument("--seed", type=int, default=42, help="Seed.")
AppLauncher.add_app_launcher_args(parser)
args_cli, hydra_args = parser.parse_known_args()
# Cameras are mandatory for the depth observation.
args_cli.enable_cameras = True
app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app
import gymnasium as gym
import torch
from rsl_rl.runners import OnPolicyRunner
import isaaclab_tasks # noqa: F401
import isaaclab_nav_task # noqa: F401
from isaaclab.envs import ManagerBasedRLEnvCfg
from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper
def _find_depth_slice(env) -> tuple[int, int, list[tuple[str, int]]]:
"""Return (start, end, layout) of the ``depth_image`` term in the policy obs.
layout is a list of (term_name, flat_dim) in concatenation order, for printing.
"""
om = env.unwrapped.observation_manager
names = om.active_terms["policy"]
dims = om.group_obs_term_dim["policy"] # list of shape-tuples per term
layout: list[tuple[str, int]] = []
offset = 0
depth_start = depth_end = -1
for name, shape in zip(names, dims):
flat = 1
for s in shape:
flat *= s
layout.append((name, flat))
if name == "depth_image":
depth_start, depth_end = offset, offset + flat
offset += flat
if depth_start < 0:
raise RuntimeError(
f"No 'depth_image' term found in policy obs group. Terms = {names}"
)
return depth_start, depth_end, layout
def main():
spec = gym.spec(args_cli.task)
env_cfg_class = spec.kwargs.get("env_cfg_entry_point")
agent_cfg_class = spec.kwargs.get("rsl_rl_cfg_entry_point")
env_cfg: ManagerBasedRLEnvCfg = env_cfg_class()
agent_cfg: RslRlOnPolicyRunnerCfg = agent_cfg_class()
if args_cli.num_envs is not None:
env_cfg.scene.num_envs = args_cli.num_envs
env = gym.make(args_cli.task, cfg=env_cfg, render_mode=None)
env = RslRlVecEnvWrapper(env)
runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device)
# --- load checkpoint (same logic as play.py) ---
resume_path = args_cli.checkpoint
if not resume_path:
raise SystemExit("[ablate] --checkpoint is required for the diagnostic.")
print(f"[ablate] loading checkpoint: {resume_path}")
loaded = torch.load(resume_path, map_location="cpu", weights_only=False)
runner.alg.actor_critic.load_state_dict(loaded["model_state_dict"], strict=True)
if runner.empirical_normalization:
runner.obs_normalizer.load_state_dict(loaded["obs_norm_state_dict"])
runner.critic_obs_normalizer.load_state_dict(loaded["critic_obs_norm_state_dict"])
print(f"[ablate] checkpoint iter = {loaded.get('iter', '?')}")
policy = runner.get_inference_policy(device=env.unwrapped.device)
depth_start, depth_end, layout = _find_depth_slice(env)
print("=" * 78)
print("[ablate] policy observation layout (term : flat_dim):")
for name, flat in layout:
marker = " <-- DEPTH" if name == "depth_image" else ""
print(f" {name:<28} {flat:>5}{marker}")
print(f"[ablate] depth slice = [{depth_start}:{depth_end}] ({depth_end - depth_start} dims)")
print("=" * 78)
obs, _ = env.get_observations()
# accumulators
n = 0
act_norm_sum = 0.0 # ||a_real||
diff_norm_sum = 0.0 # ||a_real - a_zero||
per_dim_abs_diff = None # mean |a_real - a_zero| per action dim
per_dim_abs_act = None # mean |a_real| per action dim
depth_feat_chunks = [] # collect depth slices to measure variability
device = env.unwrapped.device
step = 0
while simulation_app.is_running() and step < args_cli.steps:
with torch.inference_mode():
a_real = policy(obs)
obs_zero = obs.clone()
obs_zero[:, depth_start:depth_end] = 0.0
a_zero = policy(obs_zero)
if step >= args_cli.warmup:
d = (a_real - a_zero)
diff_norm_sum += torch.linalg.vector_norm(d, dim=-1).mean().item()
act_norm_sum += torch.linalg.vector_norm(a_real, dim=-1).mean().item()
ad = d.abs().mean(dim=0)
aa = a_real.abs().mean(dim=0)
per_dim_abs_diff = ad if per_dim_abs_diff is None else per_dim_abs_diff + ad
per_dim_abs_act = aa if per_dim_abs_act is None else per_dim_abs_act + aa
depth_feat_chunks.append(obs[:, depth_start:depth_end].detach().clone())
n += 1
with torch.inference_mode():
obs, _, _, _ = env.step(a_real)
step += 1
# --- summarise ---
print("\n" + "=" * 78)
print(f"[ablate] collected {n} steps (after {args_cli.warmup} warmup), {args_cli.num_envs} envs")
if n == 0:
print("[ablate] no samples collected; increase --steps.")
else:
mean_act = act_norm_sum / n
mean_diff = diff_norm_sum / n
rel = (mean_diff / mean_act) if mean_act > 0 else float("nan")
per_dim_abs_diff = (per_dim_abs_diff / n).tolist()
per_dim_abs_act = (per_dim_abs_act / n).tolist()
feats = torch.cat(depth_feat_chunks, dim=0) # (n*envs, depth_dim)
feat_std_over_samples = feats.std(dim=0).mean().item() # variability across time/envs
feat_abs_mean = feats.abs().mean().item()
names_se2 = ["vx", "vy", "omega"]
print("\n-- ACTION SENSITIVITY TO DEPTH (real vs depth-zeroed) --")
print(f" mean ||a_real|| = {mean_act:.4f}")
print(f" mean ||a_real - a_zero|| = {mean_diff:.4f}")
print(f" RELATIVE action change = {rel*100:.2f}%")
print(" per-action-dim |diff| / |act|:")
for i, v in enumerate(per_dim_abs_diff):
nm = names_se2[i] if i < len(names_se2) else f"a{i}"
denom = per_dim_abs_act[i] if per_dim_abs_act[i] > 0 else float("nan")
print(f" {nm:<6} |diff|={v:.4f} |act|={per_dim_abs_act[i]:.4f} ratio={v/denom*100:.1f}%")
print("\n-- DEPTH FEATURE SIGNAL (is the camera/encoder alive?) --")
print(f" feature |mean| = {feat_abs_mean:.4f}")
print(f" feature std over time/envs = {feat_std_over_samples:.4f}")
print("\n-- VERDICT --")
if feat_std_over_samples < 1e-3:
print(" >> DEAD SIGNAL: depth features are ~constant. Camera/encoder is")
print(" not producing a varying signal (sensor/render/orientation bug).")
elif rel < 0.02:
print(" >> LEARNED-BLIND: features vary but zeroing them changes the action")
print(f" by only {rel*100:.2f}%. The policy effectively IGNORES depth.")
elif rel < 0.10:
print(f" >> WEAK USE: depth changes the action by {rel*100:.2f}% (marginal).")
else:
print(f" >> DEPTH IS USED: zeroing depth changes the action by {rel*100:.2f}%.")
print(" Perception is wired in; the failure is likely a difficulty/")
print(" generalisation gap, not blindness.")
print("=" * 78)
env.close()
if __name__ == "__main__":
main()
simulation_app.close()
@@ -0,0 +1,325 @@
#!/usr/bin/env python3
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Instrumented collision analysis for a trained navigation policy.
For every env-step, this script records:
* base_lin_vel_b[:, 0] -- forward velocity in body frame (m/s)
* max contact-force magnitude over the *termination sensor body subset*
(whatever ``terminations.base_contact.params['sensor_cfg'].body_ids`` is)
* the per-term ``base_contact`` done flag
It maintains a per-env rolling buffer of the last K=16 steps so that, when a
collision fires for env i, we can dump the *pre-impact trajectory* (velocity +
peak force) for that env. The aggregated data is saved as a single .npz which
the companion script ``plot_collisions.py`` turns into figures.
Outputs (under --out-dir, default ``logs/collisions/<task>__<ckpt>``):
* collisions.npz full dump (see save_data())
* summary.txt human-readable numbers
"""
from __future__ import annotations
import argparse
import os
from isaaclab.app import AppLauncher
parser = argparse.ArgumentParser()
parser.add_argument("--num_envs", type=int, default=32)
parser.add_argument("--task", type=str, required=True)
parser.add_argument("--checkpoint", type=str, required=True)
parser.add_argument("--steps", type=int, default=4000)
parser.add_argument("--warmup", type=int, default=20)
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--lookback", type=int, default=16,
help="How many pre-impact steps to capture per collision.")
parser.add_argument("--out-dir", type=str, default=None)
AppLauncher.add_app_launcher_args(parser)
args_cli, _ = parser.parse_known_args()
args_cli.enable_cameras = True
app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app
import gymnasium as gym
import numpy as np
import torch
from rsl_rl.runners import OnPolicyRunner
import isaaclab_tasks # noqa: F401
import isaaclab_nav_task # noqa: F401
from isaaclab.envs import ManagerBasedRLEnvCfg
from isaaclab.managers import SceneEntityCfg
from isaaclab.sensors import ContactSensor
from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper
def main():
spec = gym.spec(args_cli.task)
env_cfg: ManagerBasedRLEnvCfg = spec.kwargs["env_cfg_entry_point"]()
agent_cfg: RslRlOnPolicyRunnerCfg = spec.kwargs["rsl_rl_cfg_entry_point"]()
env_cfg.scene.num_envs = args_cli.num_envs
env = gym.make(args_cli.task, cfg=env_cfg, render_mode=None)
env = RslRlVecEnvWrapper(env)
device = env.unwrapped.device
N = args_cli.num_envs
# ---- load policy ----
runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device)
loaded = torch.load(args_cli.checkpoint, map_location="cpu", weights_only=False)
runner.alg.actor_critic.load_state_dict(loaded["model_state_dict"], strict=True)
if runner.empirical_normalization:
runner.obs_normalizer.load_state_dict(loaded["obs_norm_state_dict"])
runner.critic_obs_normalizer.load_state_dict(loaded["critic_obs_norm_state_dict"])
print(f"[collisions] checkpoint iter = {loaded.get('iter', '?')}")
policy = runner.get_inference_policy(device=device)
# ---- resolve the *exact* body subset used by the base_contact termination ----
tm = env.unwrapped.termination_manager
tf = tm.get_term_cfg("base_contact")
sensor_cfg: SceneEntityCfg = tf.params["sensor_cfg"]
threshold = float(tf.params["threshold"])
print(f"[collisions] base_contact threshold = {threshold} N")
print(f"[collisions] base_contact body_names spec = {sensor_cfg.body_names}")
# NOTE: TerminationManager already resolved this SceneEntityCfg at env init,
# so body_ids is already populated; calling .resolve() again would raise.
body_ids = sensor_cfg.body_ids
contact_sensor: ContactSensor = env.unwrapped.scene.sensors[sensor_cfg.name]
print(f"[collisions] resolved body_ids = {list(body_ids) if not isinstance(body_ids, slice) else body_ids}")
# episode_termination reward weight (for context in summary)
try:
ep_term_w = float(env.unwrapped.reward_manager.get_term_cfg("episode_termination").weight)
except Exception:
ep_term_w = float("nan")
robot = env.unwrapped.scene["robot"]
# ---- rolling buffers (K x N) for pre-impact dumps ----
K = args_cli.lookback
vel_buf = torch.zeros(K, N, device=device) # base lin vel x (body frame)
speed_buf = torch.zeros(K, N, device=device) # |v_xy| (body frame)
force_buf = torch.zeros(K, N, device=device) # max contact force on subset
head = 0 # circular index
# ---- collected data ----
coll_traj_vel = [] # list of (K,) numpy arrays at the impact moment
coll_traj_speed = []
coll_traj_force = []
coll_impact_vel = [] # scalar at the IMPACT step (after termination flag flips)
coll_impact_speed = []
coll_impact_force = []
# global histograms over all NON-terminating steps (for context)
all_vel_chunks = []
all_force_chunks = []
n_steps_counted = 0
n_collisions = 0
n_success = 0
n_timeout = 0
obs, _ = env.get_observations()
step = 0
while simulation_app.is_running() and step < args_cli.steps:
# -------------------------------------------------------------
# CRITICAL: measure state BEFORE env.step(), because IsaacLab
# auto-resets terminated envs INSIDE env.step() and that wipes
# both robot.data and contact_sensor.data for the dying envs.
# We do NOT lose the impact data: the contact force history
# buffer (decimation samples) accumulates within env.step(),
# so reading it on the *next* iteration's pre-step pass would
# be the natural way -- but at that point reset has zeroed it
# for dying envs. Compromise: at pre-step iter t+1, read
# sensor history (last decimation_count physics steps from
# iter t) for the envs that just died -- still works for envs
# whose sensor history isn't fully cleared by reset (depends
# on IsaacLab version). Velocity, on the other hand, must
# be sampled BEFORE the impact step; using buffer[head-1]
# (the prior iteration's measurement) gives us exactly that.
# -------------------------------------------------------------
v_b = robot.data.root_lin_vel_b # (N, 3) -- state at start of iter t
v_fwd = v_b[:, 0]
v_xy = torch.norm(v_b[:, :2], dim=-1)
net_force_hist = contact_sensor.data.net_forces_w_history # (N, H, B_total, 3)
f_mags = torch.norm(net_force_hist[:, :, body_ids, :], dim=-1)
peak_force, _ = f_mags.reshape(N, -1).max(dim=-1) # (N,)
# Save what we *had* in the buffer before overwriting, in case
# we need to look at "1 step ago" specifically.
prev_head = (head - 1) % K
prev_vel = vel_buf[prev_head].clone()
prev_speed = speed_buf[prev_head].clone()
prev_force = force_buf[prev_head].clone()
# Push into rolling buffer (newest at index `head`, then advance).
vel_buf[head] = v_fwd
speed_buf[head] = v_xy
force_buf[head] = peak_force
new_head = head
head = (head + 1) % K
# ---- step the env (terminations + auto-reset happen in here) ----
with torch.inference_mode():
actions = policy(obs)
obs, _, _, _ = env.step(actions)
# ---- post-step: read sensor history AGAIN for envs that just died;
# this captures the *peak* contact force during the impact step
# if the reset hasn't yet zeroed the history buffer.
post_force_hist = contact_sensor.data.net_forces_w_history
post_f_mags = torch.norm(post_force_hist[:, :, body_ids, :], dim=-1)
post_peak_force, _ = post_f_mags.reshape(N, -1).max(dim=-1)
if step >= args_cli.warmup:
n_steps_counted += 1
done_bc = tm.get_term("base_contact").to(torch.bool)
done_to = tm.get_term("time_out").to(torch.bool)
done_succ = tm.get_term("early_termination").to(torch.bool)
n_collisions += int(done_bc.sum().item())
n_success += int(done_succ.sum().item())
n_timeout += int(done_to.sum().item())
if done_bc.any():
idxs = torch.where(done_bc)[0].cpu().tolist()
# Buffer order: oldest -> newest. Newest = just pushed at
# `new_head`. For envs that died THIS env.step(), the
# `new_head` sample is the pre-impact state at iter start.
order = [(head + i) % K for i in range(K)]
for i in idxs:
vt = vel_buf[order, i].cpu().numpy()
st = speed_buf[order, i].cpu().numpy()
ft = force_buf[order, i].cpu().numpy()
coll_traj_vel.append(vt)
coll_traj_speed.append(st)
coll_traj_force.append(ft)
# Pre-impact velocity = the value we measured BEFORE
# this env.step() (which contained the actual impact).
coll_impact_vel.append(float(v_fwd[i].item()))
coll_impact_speed.append(float(v_xy[i].item()))
# Impact force: take max of (a) pre-step reading, (b) post-step
# reading, (c) buffer max over the window -- whichever is
# largest is the best estimate of true peak force.
win_peak = float(force_buf[:, i].max().item())
impact_f = max(
float(peak_force[i].item()),
float(post_peak_force[i].item()),
win_peak,
)
coll_impact_force.append(impact_f)
# Global samples (alive envs only).
alive = ~tm.dones.to(torch.bool)
if alive.any():
all_vel_chunks.append(v_fwd[alive].cpu().numpy())
# use post-step force for non-dying envs -- it includes
# in-step contacts the policy then recovers from.
all_force_chunks.append(post_peak_force[alive].cpu().numpy())
step += 1
# ---- save ----
out_dir = args_cli.out_dir
if out_dir is None:
tag = os.path.splitext(os.path.basename(args_cli.checkpoint))[0]
out_dir = os.path.join("logs", "collisions", f"{args_cli.task}__{tag}")
os.makedirs(out_dir, exist_ok=True)
impact_vel_arr = np.array(coll_impact_vel)
impact_speed_arr = np.array(coll_impact_speed)
impact_force_arr = np.array(coll_impact_force)
traj_vel_arr = np.stack(coll_traj_vel) if coll_traj_vel else np.zeros((0, K))
traj_speed_arr = np.stack(coll_traj_speed) if coll_traj_speed else np.zeros((0, K))
traj_force_arr = np.stack(coll_traj_force) if coll_traj_force else np.zeros((0, K))
all_vel_arr = np.concatenate(all_vel_chunks) if all_vel_chunks else np.zeros((0,))
all_force_arr = np.concatenate(all_force_chunks) if all_force_chunks else np.zeros((0,))
np.savez_compressed(
os.path.join(out_dir, "collisions.npz"),
impact_vel=impact_vel_arr,
impact_speed=impact_speed_arr,
impact_force=impact_force_arr,
traj_vel=traj_vel_arr,
traj_speed=traj_speed_arr,
traj_force=traj_force_arr,
all_vel=all_vel_arr,
all_force=all_force_arr,
threshold=np.array(threshold, dtype=np.float32),
ep_term_weight=np.array(ep_term_w, dtype=np.float32),
K=np.array(K),
num_envs=np.array(N),
steps=np.array(n_steps_counted),
n_collisions=np.array(n_collisions),
n_success=np.array(n_success),
n_timeout=np.array(n_timeout),
)
# ---- human summary ----
def pct(x, total):
return 100.0 * x / max(total, 1)
total_term = n_collisions + n_success + n_timeout
summary = []
summary.append(f"task : {args_cli.task}")
summary.append(f"checkpoint : {args_cli.checkpoint}")
summary.append(f"steps counted : {n_steps_counted} (warmup={args_cli.warmup})")
summary.append(f"num envs : {N}")
summary.append(f"")
summary.append(f"base_contact threshold (training) : {threshold} N")
summary.append(f"episode_termination reward weight : {ep_term_w}")
summary.append(f"")
summary.append(f"terminations : success={n_success} collision={n_collisions} timeout={n_timeout}")
summary.append(f" success % : {pct(n_success, total_term):.1f}")
summary.append(f" collision % : {pct(n_collisions, total_term):.1f}")
summary.append(f" timeout % : {pct(n_timeout, total_term):.1f}")
summary.append(f"")
if impact_vel_arr.size > 0:
summary.append(f"AT IMPACT (n={impact_vel_arr.size})")
summary.append(f" v_fwd (body x) : mean={impact_vel_arr.mean():+.3f} median={np.median(impact_vel_arr):+.3f} "
f"p10={np.percentile(impact_vel_arr,10):+.3f} p90={np.percentile(impact_vel_arr,90):+.3f} "
f"std={impact_vel_arr.std():.3f} (m/s)")
summary.append(f" |v_xy| : mean={impact_speed_arr.mean():.3f} median={np.median(impact_speed_arr):.3f} "
f"p10={np.percentile(impact_speed_arr,10):.3f} p90={np.percentile(impact_speed_arr,90):.3f} (m/s)")
summary.append(f" peak force : mean={impact_force_arr.mean():.1f} median={np.median(impact_force_arr):.1f} "
f"p10={np.percentile(impact_force_arr,10):.1f} p90={np.percentile(impact_force_arr,90):.1f} "
f"max={impact_force_arr.max():.1f} (N)")
summary.append(f" force / threshold ratio : median {np.median(impact_force_arr)/threshold:.1f}x, "
f"max {impact_force_arr.max()/threshold:.1f}x")
n_slow = int((impact_speed_arr < 0.2).sum())
n_fast = int((impact_speed_arr > 0.8).sum())
summary.append(f" slow impacts (|v_xy|<0.2 m/s) : {n_slow} ({pct(n_slow, impact_speed_arr.size):.1f}%)")
summary.append(f" fast impacts (|v_xy|>0.8 m/s) : {n_fast} ({pct(n_fast, impact_speed_arr.size):.1f}%)")
else:
summary.append("NO COLLISIONS in this run.")
if all_vel_arr.size > 0:
summary.append(f"")
summary.append(f"GLOBAL (alive-step samples, n={all_vel_arr.size})")
summary.append(f" v_fwd : mean={all_vel_arr.mean():+.3f} median={np.median(all_vel_arr):+.3f} "
f"std={all_vel_arr.std():.3f} (m/s)")
summary.append(f" peak F : mean={all_force_arr.mean():.2f} median={np.median(all_force_arr):.2f} "
f"p99={np.percentile(all_force_arr,99):.2f} (N)")
txt = "\n".join(summary)
with open(os.path.join(out_dir, "summary.txt"), "w") as f:
f.write(txt + "\n")
print("\n" + "=" * 78)
print(txt)
print("=" * 78)
print(f"\n[collisions] saved to: {out_dir}")
env.close()
if __name__ == "__main__":
main()
simulation_app.close()
@@ -0,0 +1,246 @@
#!/usr/bin/env python3
"""Convert old policy checkpoints to the new positional encoding structure.
The old checkpoint uses:
attn_*_net.position_embedding.penc.inv_freq
The new checkpoint uses:
attn_*_net.pos_encoding
This script converts old checkpoints to the new format by:
1. Removing the old position_embedding.penc.inv_freq keys
2. Computing and adding the new pos_encoding tensors
Usage:
./isaaclab.sh -p scripts/convert_checkpoint.py --input <old_checkpoint.pt> --output <new_checkpoint.pt>
# Or convert in-place:
./isaaclab.sh -p scripts/convert_checkpoint.py --input <checkpoint.pt> --inplace
"""
import argparse
import math
from pathlib import Path
import torch
def _compute_positional_encoding_3d(
channels: int, D: int, H: int, W: int, device: torch.device, dtype: torch.dtype
) -> torch.Tensor:
"""Compute 3D positional encoding for given spatial dimensions.
This code is adapted from: https://github.com/tatp22/multidim-positional-encoding
Args:
channels: Number of channels for the encoding.
D, H, W: Spatial dimensions (depth, height, width).
device: Device to create tensor on.
dtype: Data type for the encoding tensor.
Returns:
Positional encoding tensor of shape (1, channels, D, H, W).
"""
org_channels = channels
channels = int(math.ceil(channels / 6) * 2)
if channels % 2:
channels += 1
inv_freq = 1.0 / (10000 ** (torch.arange(0, channels, 2, device=device).float() / channels))
def get_emb(sin_inp: torch.Tensor) -> torch.Tensor:
emb = torch.stack((sin_inp.sin(), sin_inp.cos()), dim=-1)
return torch.flatten(emb, -2, -1)
pos_x = torch.arange(D, device=device, dtype=inv_freq.dtype)
pos_y = torch.arange(H, device=device, dtype=inv_freq.dtype)
pos_z = torch.arange(W, device=device, dtype=inv_freq.dtype)
sin_inp_x = torch.einsum("i,j->ij", pos_x, inv_freq)
sin_inp_y = torch.einsum("i,j->ij", pos_y, inv_freq)
sin_inp_z = torch.einsum("i,j->ij", pos_z, inv_freq)
emb_x = get_emb(sin_inp_x).unsqueeze(1).unsqueeze(1)
emb_y = get_emb(sin_inp_y).unsqueeze(1)
emb_z = get_emb(sin_inp_z)
emb = torch.zeros((D, H, W, channels * 3), device=device, dtype=dtype)
emb[:, :, :, :channels] = emb_x
emb[:, :, :, channels : 2 * channels] = emb_y
emb[:, :, :, 2 * channels :] = emb_z
# Convert from (D, H, W, ch) to (1, ch, D, H, W) format (channel-first with batch dim)
enc = emb[None, :, :, :, :org_channels] # (1, D, H, W, org_channels)
enc = enc.permute(0, 4, 1, 2, 3) # (1, org_channels, D, H, W)
return enc
def convert_checkpoint(
input_path: str,
output_path: str,
image_input_dims: tuple = (64, 5, 8),
height_input_dims: tuple = (64, 7, 7),
num_cameras: int = 1,
force: bool = False,
) -> None:
"""Convert old checkpoint to new format.
Args:
input_path: Path to the old checkpoint.
output_path: Path to save the converted checkpoint.
image_input_dims: Tuple of (C, H, W) for image input.
height_input_dims: Tuple of (C, H, W) for height map input.
num_cameras: Number of cameras (1 or 2).
force: Force re-compute pos_encoding even if already in new format.
"""
print(f"Loading checkpoint from: {input_path}")
checkpoint = torch.load(input_path, map_location="cpu", weights_only=False)
state_dict = checkpoint["model_state_dict"]
# Find old position_embedding keys to remove
old_keys = [k for k in state_dict.keys() if "position_embedding.penc.inv_freq" in k]
# Check if new keys exist
new_keys = [k for k in state_dict.keys() if ".pos_encoding" in k]
if not old_keys and not force:
print("No old position_embedding keys found. Checkpoint may already be in new format.")
if new_keys:
print(f"Found new pos_encoding keys: {new_keys}")
for k in new_keys:
print(f" {k}: {state_dict[k].shape}")
print("Checkpoint is already in new format. Use --force to re-compute pos_encoding.")
return
else:
print("Warning: Neither old nor new positional encoding keys found!")
return
if old_keys:
print(f"Found {len(old_keys)} old position_embedding keys to convert:")
for k in old_keys:
print(f" - {k}")
# Remove old keys
for k in old_keys:
del state_dict[k]
if new_keys and force:
print(f"Force mode: Replacing {len(new_keys)} existing pos_encoding keys:")
for k in new_keys:
print(f" - {k}: {state_dict[k].shape}")
# Remove existing pos_encoding keys to replace them
for k in new_keys:
del state_dict[k]
# Compute and add new positional encodings
# For attn_image_net and attn_critic_image_net: spatial_dims = (num_cameras, H, W)
# For attn_height_net: spatial_dims = (1, H, W)
image_channels = image_input_dims[0]
height_channels = height_input_dims[0]
image_spatial_dims = (num_cameras, image_input_dims[1], image_input_dims[2])
height_spatial_dims = (1, height_input_dims[1], height_input_dims[2])
print(f"\nComputing new positional encodings:")
print(f" - image_input_dims: {image_input_dims}, num_cameras: {num_cameras}")
print(f" - height_input_dims: {height_input_dims}")
print(f" - image spatial_dims (D, H, W): {image_spatial_dims}")
print(f" - height spatial_dims (D, H, W): {height_spatial_dims}")
# Compute positional encodings
image_pos_enc = _compute_positional_encoding_3d(
image_channels, *image_spatial_dims, torch.device("cpu"), torch.float32
)
height_pos_enc = _compute_positional_encoding_3d(
height_channels, *height_spatial_dims, torch.device("cpu"), torch.float32
)
print(f"\nNew positional encoding shapes:")
print(f" - attn_image_net.pos_encoding: {image_pos_enc.shape}")
print(f" - attn_height_net.pos_encoding: {height_pos_enc.shape}")
print(f" - attn_critic_image_net.pos_encoding: {image_pos_enc.shape}")
# Add new keys
state_dict["attn_image_net.pos_encoding"] = image_pos_enc
state_dict["attn_height_net.pos_encoding"] = height_pos_enc
state_dict["attn_critic_image_net.pos_encoding"] = image_pos_enc.clone()
# Save converted checkpoint
print(f"\nSaving converted checkpoint to: {output_path}")
torch.save(checkpoint, output_path)
print("Conversion complete!")
def main():
parser = argparse.ArgumentParser(
description="Convert old policy checkpoints to new positional encoding structure."
)
parser.add_argument(
"--input", "-i",
type=str,
required=True,
help="Path to the old checkpoint file."
)
parser.add_argument(
"--output", "-o",
type=str,
default=None,
help="Path to save the converted checkpoint. If not specified, uses --inplace."
)
parser.add_argument(
"--inplace",
action="store_true",
help="Convert the checkpoint in-place (overwrite the input file)."
)
parser.add_argument(
"--image-dims",
type=str,
default="64,5,8",
help="Image input dimensions as C,H,W (default: 64,5,8)."
)
parser.add_argument(
"--height-dims",
type=str,
default="64,7,7",
help="Height input dimensions as C,H,W (default: 64,7,7)."
)
parser.add_argument(
"--num-cameras",
type=int,
default=1,
help="Number of cameras (default: 1)."
)
parser.add_argument(
"--force",
action="store_true",
help="Force re-compute pos_encoding even if already in new format."
)
args = parser.parse_args()
# Determine output path
if args.output:
output_path = args.output
elif args.inplace:
output_path = args.input
else:
# Default: add _converted suffix
input_path = Path(args.input)
output_path = str(input_path.parent / f"{input_path.stem}_converted{input_path.suffix}")
# Parse dimensions
image_dims = tuple(int(x) for x in args.image_dims.split(","))
height_dims = tuple(int(x) for x in args.height_dims.split(","))
if len(image_dims) != 3 or len(height_dims) != 3:
raise ValueError("Dimensions must be specified as C,H,W (3 values)")
convert_checkpoint(
input_path=args.input,
output_path=output_path,
image_input_dims=image_dims,
height_input_dims=height_dims,
num_cameras=args.num_cameras,
force=args.force,
)
if __name__ == "__main__":
main()
+140
View File
@@ -0,0 +1,140 @@
#!/usr/bin/env python3
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Headless evaluator for a *TorchScript JIT* navigation policy.
Mirrors ``eval_terminations.py`` but instead of building an rsl_rl Runner and
loading a ``model_*.pt`` checkpoint, it directly loads a JIT-scripted
``ActorCriticSRU`` policy (e.g. the official upstream deployment policy
``nav_policy_new.pt``) and rolls it out in the IsaacLab navigation env.
The JIT module exposes:
forward(observations: Tensor, reset: bool=False) -> actions: Tensor
with internal ``hidden_state`` / ``cell_state`` buffers sized
``(num_layers, 1, hidden_size)``. We resize those buffers to
``(num_layers, num_envs, hidden_size)`` after load so a single forward call
handles all envs in parallel, and we per-env zero them on episode reset.
"""
from __future__ import annotations
import argparse
from isaaclab.app import AppLauncher
parser = argparse.ArgumentParser(description="Evaluate a JIT navigation policy.")
parser.add_argument("--num_envs", type=int, default=32)
parser.add_argument("--task", type=str, required=True, help="Gym task id (use a *-Play-v0 variant).")
parser.add_argument("--jit_policy", type=str, required=True, help="In-container path to TorchScript .pt.")
parser.add_argument("--steps", type=int, default=2000)
parser.add_argument("--warmup", type=int, default=20)
parser.add_argument("--seed", type=int, default=42)
AppLauncher.add_app_launcher_args(parser)
args_cli, _ = parser.parse_known_args()
args_cli.enable_cameras = True
app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app
import gymnasium as gym
import torch
import isaaclab_tasks # noqa: F401
import isaaclab_nav_task # noqa: F401
from isaaclab.envs import ManagerBasedRLEnvCfg
from isaaclab_rl.rsl_rl import RslRlVecEnvWrapper
def main():
# ---- env setup ----
spec = gym.spec(args_cli.task)
env_cfg_class = spec.kwargs.get("env_cfg_entry_point")
env_cfg: ManagerBasedRLEnvCfg = env_cfg_class()
env_cfg.scene.num_envs = args_cli.num_envs
env = gym.make(args_cli.task, cfg=env_cfg, render_mode=None)
env = RslRlVecEnvWrapper(env)
device = env.unwrapped.device
num_envs = args_cli.num_envs
# ---- policy load ----
print(f"[eval-jit] loading JIT policy: {args_cli.jit_policy}")
model = torch.jit.load(args_cli.jit_policy, map_location=device)
model.eval()
print(f"[eval-jit] model loaded; type={type(model).__name__}")
# Resize hidden state buffers from (num_layers, 1, hidden_size) to
# (num_layers, num_envs, hidden_size). Works because ``rnn`` is a generic
# LSTM-style cell that accepts any batch dim.
h = model.hidden_state
c = model.cell_state
print(f"[eval-jit] original hidden_state shape: {tuple(h.shape)}")
model.hidden_state = torch.zeros(h.shape[0], num_envs, h.shape[2], device=device, dtype=h.dtype)
model.cell_state = torch.zeros(c.shape[0], num_envs, c.shape[2], device=device, dtype=c.dtype)
print(f"[eval-jit] resized hidden_state shape: {tuple(model.hidden_state.shape)}")
# ---- termination accounting ----
tm = env.unwrapped.termination_manager
term_names = list(tm.active_terms)
print(f"[eval-jit] active termination terms: {term_names}")
counts = {name: 0 for name in term_names}
counts["__any__"] = 0
# ---- rollout ----
obs, _ = env.get_observations()
prev_dones = torch.zeros(num_envs, dtype=torch.bool, device=device)
step = 0
while simulation_app.is_running() and step < args_cli.steps:
# Zero hidden state for envs that just terminated (got reset internally
# by IsaacLab at the start of this step's env.step()).
if prev_dones.any():
mask = prev_dones.to(torch.bool)
# buffer shape: (num_layers, num_envs, hidden_size)
model.hidden_state[:, mask, :] = 0
model.cell_state[:, mask, :] = 0
with torch.inference_mode():
actions = model(obs, False)
obs, _, dones, _ = env.step(actions)
prev_dones = dones.to(torch.bool)
if step >= args_cli.warmup:
for name in term_names:
counts[name] += int(tm.get_term(name).sum().item())
counts["__any__"] += int(env.unwrapped.termination_manager.dones.sum().item())
step += 1
# ---- report ----
total = counts["__any__"] if counts["__any__"] > 0 else 1
print("\n" + "=" * 78)
print(f"[eval-jit] steps counted = {args_cli.steps - args_cli.warmup}, num_envs = {num_envs}")
print(f"[eval-jit] total terminations observed = {counts['__any__']}")
print("\n TERM COUNT %-of-terms")
print(" " + "-" * 50)
for name in term_names:
c_n = counts[name]
pct = 100.0 * c_n / total
marker = ""
if name == "early_termination":
marker = " <- success"
elif name in ("base_contact", "large_pitch_angle"):
marker = " <- collision/tipover"
elif name == "terrain_fall":
marker = " <- PIT FALL"
elif name == "time_out":
marker = " <- ran out of time"
print(f" {name:<28} {c_n:>6} {pct:>5.1f}%{marker}")
print("=" * 78)
env.close()
if __name__ == "__main__":
main()
simulation_app.close()
@@ -0,0 +1,138 @@
#!/usr/bin/env python3
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Headless termination-breakdown evaluator for a trained navigation policy.
Question this answers: *for a given checkpoint on a given task/difficulty,
what fraction of episodes end via each termination reason* -- including the
re-thresholded ``terrain_fall`` (now -0.3m for Go2) which is the only way to
distinguish *fell into a pit* from *bumped a wall*.
The script mirrors ``play.py`` for env/policy setup, then counts the
TerminationManager's per-term done flags across a fixed number of env steps.
"""
from __future__ import annotations
import argparse
from isaaclab.app import AppLauncher
parser = argparse.ArgumentParser(description="Evaluate termination breakdown for a navigation policy.")
parser.add_argument("--num_envs", type=int, default=64, help="Number of parallel environments.")
parser.add_argument("--task", type=str, default=None, help="Gym task id (use a *-Play-v0 variant).")
parser.add_argument("--checkpoint", type=str, default=None, help="In-container path to model_*.pt.")
parser.add_argument("--steps", type=int, default=2000, help="Number of env.step() calls.")
parser.add_argument("--warmup", type=int, default=20, help="Steps to skip before counting (let resets settle).")
parser.add_argument("--seed", type=int, default=42, help="Seed.")
AppLauncher.add_app_launcher_args(parser)
args_cli, _ = parser.parse_known_args()
args_cli.enable_cameras = True
app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app
import gymnasium as gym
import torch
from rsl_rl.runners import OnPolicyRunner
import isaaclab_tasks # noqa: F401
import isaaclab_nav_task # noqa: F401
from isaaclab.envs import ManagerBasedRLEnvCfg
from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper
def main():
spec = gym.spec(args_cli.task)
env_cfg_class = spec.kwargs.get("env_cfg_entry_point")
agent_cfg_class = spec.kwargs.get("rsl_rl_cfg_entry_point")
env_cfg: ManagerBasedRLEnvCfg = env_cfg_class()
agent_cfg: RslRlOnPolicyRunnerCfg = agent_cfg_class()
env_cfg.scene.num_envs = args_cli.num_envs
env = gym.make(args_cli.task, cfg=env_cfg, render_mode=None)
env = RslRlVecEnvWrapper(env)
runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device)
if not args_cli.checkpoint:
raise SystemExit("[eval] --checkpoint is required.")
print(f"[eval] loading checkpoint: {args_cli.checkpoint}")
loaded = torch.load(args_cli.checkpoint, map_location="cpu", weights_only=False)
runner.alg.actor_critic.load_state_dict(loaded["model_state_dict"], strict=True)
if runner.empirical_normalization:
runner.obs_normalizer.load_state_dict(loaded["obs_norm_state_dict"])
runner.critic_obs_normalizer.load_state_dict(loaded["critic_obs_norm_state_dict"])
print(f"[eval] checkpoint iter = {loaded.get('iter', '?')}")
policy = runner.get_inference_policy(device=env.unwrapped.device)
# Termination manager exposes per-term done flags as torch tensors.
tm = env.unwrapped.termination_manager
term_names = list(tm.active_terms)
print(f"[eval] active termination terms: {term_names}")
# Per-term running counters (number of envs that ended via this reason).
counts = {name: 0 for name in term_names}
counts["__any__"] = 0 # any termination (sanity)
# Print the relevant cfg knobs so the run is self-documenting.
try:
tf_params = env_cfg.terminations.terrain_fall.params
print(f"[eval] terrain_fall.fall_height_threshold = "
f"{tf_params.get('fall_height_threshold', 'default')}")
except Exception:
pass
obs, _ = env.get_observations()
step = 0
while simulation_app.is_running() and step < args_cli.steps:
with torch.inference_mode():
actions = policy(obs)
obs, _, _, _ = env.step(actions)
if step >= args_cli.warmup:
# Each per-term tensor is bool[num_envs]; sum gives this-step count.
for name in term_names:
term_tensor = tm.get_term(name)
counts[name] += int(term_tensor.sum().item())
# Any-termination flag (rsl_rl wrapper resets on time_out OR done).
any_done = env.unwrapped.termination_manager.dones
counts["__any__"] += int(any_done.sum().item())
step += 1
# -------- summarise --------
total = counts["__any__"] if counts["__any__"] > 0 else 1
print("\n" + "=" * 78)
print(f"[eval] steps counted = {args_cli.steps - args_cli.warmup}, num_envs = {args_cli.num_envs}")
print(f"[eval] total terminations observed = {counts['__any__']}")
print("\n TERM COUNT %-of-terms")
print(" " + "-" * 50)
for name in term_names:
c = counts[name]
pct = 100.0 * c / total
marker = ""
if name == "early_termination":
marker = " <- success"
elif name in ("base_contact", "large_pitch_angle"):
marker = " <- collision/tipover"
elif name == "terrain_fall":
marker = " <- PIT FALL (with new threshold)"
elif name == "time_out":
marker = " <- ran out of time"
print(f" {name:<28} {c:>6} {pct:>5.1f}%{marker}")
print("=" * 78)
env.close()
if __name__ == "__main__":
main()
simulation_app.close()
@@ -0,0 +1,277 @@
#!/usr/bin/env python3
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Play a trained navigation policy (PPO/MDPO) with automatic checkpoint loading.
Usage:
python scripts/play.py --task <task_name> [options]
Arguments:
--task Task name (required, typically *-Play-v0 variant)
--checkpoint Path to model checkpoint (.pt file)
--use_last_checkpoint Use latest checkpoint from logs (default behavior)
--num_envs Number of parallel environments
--video Enable video recording
--video_length Video length in steps (default: 200)
Examples:
python scripts/play.py --task Isaac-Navigation-B2W-Play-v0
python scripts/play.py --task Isaac-Navigation-B2W-Play-v0 --checkpoint path/to/model.pt
python scripts/play.py --task Isaac-Navigation-B2W-Play-v0 --video --num_envs 16
Note: Automatically finds latest checkpoint if --checkpoint not specified.
"""
from __future__ import annotations
import argparse
import sys
from isaaclab.app import AppLauncher
# Add argparse arguments
parser = argparse.ArgumentParser(description="Play a trained navigation policy with RSL-RL.")
parser.add_argument("--video", action="store_true", default=False, help="Record videos during play.")
parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).")
parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.")
parser.add_argument("--task", type=str, default=None, help="Name of the task.")
parser.add_argument("--checkpoint", type=str, default=None, help="Path to model checkpoint.")
parser.add_argument("--use_last_checkpoint", action="store_true", help="Use last checkpoint from logs.")
parser.add_argument("--export_jit", action="store_true", default=False, help="Export policy as JIT module.")
parser.add_argument("--export_onnx", action="store_true", default=False, help="Export policy as ONNX model.")
# Append AppLauncher cli args
AppLauncher.add_app_launcher_args(parser)
args_cli, hydra_args = parser.parse_known_args()
# Always enable cameras
args_cli.enable_cameras = True
# Launch simulation
app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app
# Import after launching simulation
import gymnasium as gym
import os
import re
import torch
from rsl_rl.runners import OnPolicyRunner
# Import Isaac Lab extensions
import isaaclab_tasks # noqa: F401
import isaaclab_nav_task # noqa: F401
from isaaclab.envs import ManagerBasedRLEnvCfg
from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper, export_policy_as_onnx
def find_latest_checkpoint(log_path: str, checkpoint_pattern: str = "model_.*.pt") -> str:
"""Find the latest checkpoint file in the log directory.
Args:
log_path: Base log directory path
checkpoint_pattern: Regex pattern for checkpoint files
Returns:
Path to the latest checkpoint file
"""
# Find all run directories
if not os.path.exists(log_path):
raise ValueError(f"Log path does not exist: {log_path}")
run_dirs = []
for entry in os.scandir(log_path):
if entry.is_dir() and re.match(r"\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}", entry.name):
run_dirs.append(entry.name)
if not run_dirs:
raise ValueError(f"No run directories found in: {log_path}")
# Sort to get latest run
run_dirs.sort()
latest_run = run_dirs[-1]
run_path = os.path.join(log_path, latest_run)
# Find checkpoint files
checkpoint_files = []
for f in os.listdir(run_path):
if re.match(checkpoint_pattern, f):
checkpoint_files.append(f)
if not checkpoint_files:
raise ValueError(f"No checkpoint files matching '{checkpoint_pattern}' found in: {run_path}")
# Sort to get latest checkpoint
checkpoint_files.sort(key=lambda m: f"{m:0>15}")
latest_checkpoint = checkpoint_files[-1]
return os.path.join(run_path, latest_checkpoint)
def load_checkpoint_with_fallback(runner: OnPolicyRunner, checkpoint_path: str, load_optimizer: bool = True):
"""Load checkpoint with fallback for PyTorch compatibility issues.
Args:
runner: RSL-RL runner instance
checkpoint_path: Path to checkpoint file
load_optimizer: Whether to load optimizer state
"""
print(f"[INFO] Loading checkpoint from: {checkpoint_path}")
# Load checkpoint to CPU first for compatibility
loaded_dict = torch.load(checkpoint_path, map_location='cpu', weights_only=False)
# Load model state - handle both standard algorithms (PPO) and MDPO
if runner.is_mdpo:
# MDPO uses two actor-critics, load same state into both
runner.alg.actor_critic_1.load_state_dict(loaded_dict["model_state_dict"], strict=True)
runner.alg.actor_critic_2.load_state_dict(loaded_dict["model_state_dict"], strict=True)
else:
# Standard algorithms use one actor-critic
runner.alg.actor_critic.load_state_dict(loaded_dict["model_state_dict"], strict=True)
# Load normalizers if using empirical normalization
if runner.empirical_normalization:
runner.obs_normalizer.load_state_dict(loaded_dict["obs_norm_state_dict"])
runner.critic_obs_normalizer.load_state_dict(loaded_dict["critic_obs_norm_state_dict"])
# Load optimizer if requested
if load_optimizer:
if runner.is_mdpo:
runner.alg.optimizer_1.load_state_dict(loaded_dict["optimizer_state_dict"])
else:
runner.alg.optimizer.load_state_dict(loaded_dict["optimizer_state_dict"])
runner.current_learning_iteration = loaded_dict["iter"]
print(f"[INFO] Loaded checkpoint from iteration {loaded_dict['iter']}")
def export_policy_jit(runner: OnPolicyRunner, checkpoint_path: str):
"""Export policy as JIT module to an 'export' folder next to the checkpoint.
Args:
runner: RSL-RL runner instance with loaded policy
checkpoint_path: Path to the checkpoint file (used to determine export location)
"""
# Determine export directory (create 'export' folder in the same directory as checkpoint)
checkpoint_dir = os.path.dirname(checkpoint_path)
export_dir = os.path.join(checkpoint_dir, "export")
# Get the actor-critic module
if runner.is_mdpo:
actor_critic = runner.alg.actor_critic_1
else:
actor_critic = runner.alg.actor_critic
# Get normalizer if using empirical normalization
normalizer = runner.obs_normalizer if runner.empirical_normalization else None
# Export using the module's export_jit method
print(f"[INFO] Exporting JIT policy to: {export_dir}")
actor_critic.export_jit(path=export_dir, filename="policy.pt", normalizer=normalizer)
print(f"[INFO] JIT export complete!")
def export_policy_onnx(runner: OnPolicyRunner, checkpoint_path: str):
"""Export policy as ONNX model to an 'export' folder next to the checkpoint.
Args:
runner: RSL-RL runner instance with loaded policy
checkpoint_path: Path to the checkpoint file (used to determine export location)
"""
# Determine export directory (create 'export' folder in the same directory as checkpoint)
checkpoint_dir = os.path.dirname(checkpoint_path)
export_dir = os.path.join(checkpoint_dir, "export")
# Get the actor-critic module
if runner.is_mdpo:
actor_critic = runner.alg.actor_critic_1
else:
actor_critic = runner.alg.actor_critic
# Get normalizer if using empirical normalization
normalizer = runner.obs_normalizer if runner.empirical_normalization else None
# Check if the module has export_onnx method
if not hasattr(actor_critic, "export_onnx"):
raise NotImplementedError(
f"ONNX export not implemented for {type(actor_critic).__name__}. "
"Please add an export_onnx method to this module."
)
# Export using the module's export_onnx method
print(f"[INFO] Exporting ONNX policy to: {export_dir}")
actor_critic.export_onnx(path=export_dir, filename="policy.onnx", normalizer=normalizer)
print(f"[INFO] ONNX export complete!")
def main():
"""Play navigation policy with RSL-RL."""
# Parse command-line arguments
spec = gym.spec(args_cli.task)
env_cfg_class = spec.kwargs.get("env_cfg_entry_point")
agent_cfg_class = spec.kwargs.get("rsl_rl_cfg_entry_point")
# Instantiate the configs
env_cfg: ManagerBasedRLEnvCfg = env_cfg_class()
agent_cfg: RslRlOnPolicyRunnerCfg = agent_cfg_class()
# Override config from command line
if args_cli.num_envs is not None:
env_cfg.scene.num_envs = args_cli.num_envs
# Create the environment
env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None)
# Wrap the environment
env = RslRlVecEnvWrapper(env)
# Get checkpoint path
if args_cli.checkpoint:
resume_path = args_cli.checkpoint
else:
# Get last checkpoint from log directory
log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name)
resume_path = find_latest_checkpoint(log_root_path, checkpoint_pattern="model_.*.pt")
# Create runner
runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=None, device=agent_cfg.device)
# Load checkpoint with compatibility handling
load_checkpoint_with_fallback(runner, resume_path)
# Export JIT if requested
if args_cli.export_jit:
export_policy_jit(runner, resume_path)
# Export ONNX if requested
if args_cli.export_onnx:
export_policy_onnx(runner, resume_path)
# Obtain policy for inference
policy = runner.get_inference_policy(device=env.unwrapped.device)
# Reset environment
obs, _ = env.get_observations()
# Simulate environment
while simulation_app.is_running():
# Run policy
with torch.inference_mode():
actions = policy(obs)
# Step environment
obs, _, _, _ = env.step(actions)
# Close the environment
env.close()
if __name__ == "__main__":
# Run the main function
main()
# Close simulation
simulation_app.close()
+152
View File
@@ -0,0 +1,152 @@
#!/usr/bin/env python3
"""Render figures from a collisions.npz produced by analyze_collisions.py.
Run on the *host* (matplotlib only, no Isaac). Writes PNGs next to the .npz.
"""
from __future__ import annotations
import argparse, os
import numpy as np
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
def main():
ap = argparse.ArgumentParser()
ap.add_argument("npz", help="Path to collisions.npz")
args = ap.parse_args()
d = np.load(args.npz)
out_dir = os.path.dirname(os.path.abspath(args.npz))
thr = float(d["threshold"])
ep_w = float(d["ep_term_weight"])
K = int(d["K"])
n_coll = int(d["n_collisions"])
n_succ = int(d["n_success"])
n_to = int(d["n_timeout"])
impact_vel = d["impact_vel"]
impact_speed = d["impact_speed"]
impact_force = d["impact_force"]
traj_vel = d["traj_vel"]
traj_speed = d["traj_speed"]
traj_force = d["traj_force"]
all_vel = d["all_vel"]
all_force = d["all_force"]
# ===== Fig 1: impact velocity histogram =====
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5))
ax = axes[0]
if impact_vel.size > 0:
ax.hist(impact_vel, bins=40, color="#d9534f", alpha=0.85, edgecolor="white")
ax.axvline(impact_vel.mean(), color="black", ls="--", lw=1.5,
label=f"mean = {impact_vel.mean():+.2f} m/s")
ax.axvline(0.0, color="gray", ls=":", lw=1)
ax.set_xlabel("body-frame forward velocity at impact (m/s)")
ax.set_ylabel("# collisions")
ax.set_title(f"Velocity at collision (n={impact_vel.size})")
ax.legend()
ax.grid(alpha=0.3)
ax = axes[1]
if impact_speed.size > 0:
ax.hist(impact_speed, bins=40, color="#5bc0de", alpha=0.85, edgecolor="white")
ax.axvline(impact_speed.mean(), color="black", ls="--", lw=1.5,
label=f"mean = {impact_speed.mean():.2f} m/s")
ax.axvline(0.2, color="orange", ls=":", lw=1, label="0.2 m/s (slow-impact cutoff)")
ax.set_xlabel("planar speed |v_xy| at impact (m/s)")
ax.set_ylabel("# collisions")
ax.set_title("Planar speed at collision")
ax.legend()
ax.grid(alpha=0.3)
fig.tight_layout()
fig.savefig(os.path.join(out_dir, "fig1_impact_velocity.png"), dpi=130)
plt.close(fig)
# ===== Fig 2: contact force histogram (log scale) with threshold =====
fig, ax = plt.subplots(figsize=(8, 5))
if impact_force.size > 0:
bins = np.logspace(np.log10(max(thr * 0.5, 0.5)),
np.log10(max(impact_force.max() * 1.2, thr * 10)), 50)
ax.hist(impact_force, bins=bins, color="#f0ad4e", alpha=0.85, edgecolor="white",
label=f"impact peak force (n={impact_force.size})")
ax.axvline(thr, color="red", ls="--", lw=2, label=f"training threshold = {thr:.1f} N")
ax.axvline(np.median(impact_force), color="black", ls=":", lw=1.5,
label=f"median impact = {np.median(impact_force):.0f} N "
f"({np.median(impact_force)/thr:.0f}× thr)")
ax.set_xscale("log")
ax.set_xlabel("peak contact force on (base, hip, thigh) at impact (N, log)")
ax.set_ylabel("# collisions")
ax.set_title("Impact force vs training termination threshold")
ax.legend()
ax.grid(alpha=0.3, which="both")
fig.tight_layout()
fig.savefig(os.path.join(out_dir, "fig2_impact_force.png"), dpi=130)
plt.close(fig)
# ===== Fig 3: pre-impact trajectory (median + IQR) =====
if traj_vel.shape[0] > 0:
steps = np.arange(-K + 1, 1)
fig, axes = plt.subplots(1, 2, figsize=(12, 4.5), sharex=True)
for ax, data, ylabel, title, color in [
(axes[0], traj_speed, "planar speed |v_xy| (m/s)", "Speed leading up to collision", "#5bc0de"),
(axes[1], traj_force, "peak contact force (N)", "Force leading up to collision", "#f0ad4e"),
]:
med = np.median(data, axis=0)
p25 = np.percentile(data, 25, axis=0)
p75 = np.percentile(data, 75, axis=0)
ax.fill_between(steps, p25, p75, color=color, alpha=0.35, label="IQR (25-75%)")
ax.plot(steps, med, color=color, lw=2.2, label="median")
ax.axvline(0, color="red", ls="--", lw=1.5, label="impact step")
ax.set_xlabel("env-step relative to impact")
ax.set_ylabel(ylabel)
ax.set_title(f"{title} (n={data.shape[0]})")
ax.legend()
ax.grid(alpha=0.3)
if axes[1].get_ylim()[1] > 5 * thr:
axes[1].set_yscale("symlog", linthresh=max(thr, 1.0))
axes[1].axhline(thr, color="red", ls=":", lw=1)
fig.tight_layout()
fig.savefig(os.path.join(out_dir, "fig3_pre_impact.png"), dpi=130)
plt.close(fig)
# ===== Fig 4: global v_fwd distribution (alive steps) vs at-impact =====
fig, ax = plt.subplots(figsize=(8, 5))
if all_vel.size > 0:
ax.hist(all_vel, bins=60, density=True, color="#5cb85c", alpha=0.55,
edgecolor="white", label=f"alive steps (n={all_vel.size})")
if impact_vel.size > 0:
ax.hist(impact_vel, bins=40, density=True, color="#d9534f", alpha=0.55,
edgecolor="white", label=f"at impact (n={impact_vel.size})")
ax.axvline(0, color="gray", ls=":", lw=1)
ax.set_xlabel("body-frame forward velocity v_fwd (m/s)")
ax.set_ylabel("density")
ax.set_title("Forward velocity: normal navigation vs at collision")
ax.legend()
ax.grid(alpha=0.3)
fig.tight_layout()
fig.savefig(os.path.join(out_dir, "fig4_vfwd_normal_vs_impact.png"), dpi=130)
plt.close(fig)
# ===== short text summary =====
lines = []
lines.append(f"threshold = {thr} N ep_term_w = {ep_w}")
lines.append(f"terminations: success={n_succ} collision={n_coll} timeout={n_to}")
if impact_force.size > 0:
lines.append(f"impact force: median {np.median(impact_force):.1f} N "
f"({np.median(impact_force)/thr:.0f}x threshold), "
f"p90 {np.percentile(impact_force,90):.1f}, max {impact_force.max():.1f}")
if impact_speed.size > 0:
slow = (impact_speed < 0.2).mean() * 100
fast = (impact_speed > 0.8).mean() * 100
lines.append(f"impact |v_xy|: median {np.median(impact_speed):.2f} m/s "
f"slow<0.2: {slow:.0f}% fast>0.8: {fast:.0f}%")
print("\n".join(lines))
print(f"\nfigures saved into: {out_dir}")
if __name__ == "__main__":
main()
@@ -0,0 +1,150 @@
#!/usr/bin/env python3
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Train a navigation policy using RSL-RL (PPO/MDPO algorithms).
Usage:
python scripts/train.py --task <task_name> --num_envs <num> [options]
Arguments:
--task Task name (required)
--num_envs Number of parallel environments
--seed Random seed
--max_iterations Training iterations
--run_name Custom run name for logging
--video Enable video recording
--video_length Video length in steps (default: 200)
--video_interval Recording interval in steps (default: 2000)
Examples:
python scripts/train.py --task Isaac-Navigation-B2W-v0 --num_envs 2048
python scripts/train.py --task Isaac-Navigation-B2W-v0 --video --seed 42
Logs saved to: logs/rsl_rl/<experiment_name>/<timestamp>/
"""
from __future__ import annotations
import argparse
import sys
# Add the parent directory to the path so we can import from the extension
from isaaclab.app import AppLauncher
# Add argparse arguments
parser = argparse.ArgumentParser(description="Train a navigation policy with RSL-RL.")
parser.add_argument("--video", action="store_true", default=False, help="Record videos during training.")
parser.add_argument("--video_length", type=int, default=200, help="Length of the recorded video (in steps).")
parser.add_argument("--video_interval", type=int, default=2000, help="Interval between video recordings (in steps).")
parser.add_argument("--num_envs", type=int, default=None, help="Number of environments to simulate.")
parser.add_argument("--task", type=str, default=None, help="Name of the task.")
parser.add_argument("--seed", type=int, default=None, help="Seed used for the environment")
parser.add_argument("--max_iterations", type=int, default=None, help="RL Policy training iterations.")
parser.add_argument("--run_name", type=str, default=None, help="Name of the wandb run (appended to log directory).")
parser.add_argument("--checkpoint", type=str, default=None, help="Path to a checkpoint (.pt) to warm-start from before training begins.")
parser.add_argument("--load_optimizer", action="store_true", default=False, help="Also load the optimizer state from the checkpoint (default: only load model weights, recommended for cross-robot warm-start).")
# Append AppLauncher cli args
AppLauncher.add_app_launcher_args(parser)
args_cli, hydra_args = parser.parse_known_args()
# always enable cameras to record video
if args_cli.video:
args_cli.enable_cameras = True
# Launch simulation
app_launcher = AppLauncher(args_cli)
simulation_app = app_launcher.app
# Import after launching simulation
import gymnasium as gym
import os
import torch
from datetime import datetime
from rsl_rl.runners import OnPolicyRunner
# Import Isaac Lab extensions
import isaaclab_tasks # noqa: F401
import isaaclab_nav_task # noqa: F401
from isaaclab.envs import ManagerBasedRLEnvCfg
from isaaclab.utils.dict import print_dict
from isaaclab.utils.io import dump_pickle, dump_yaml
from isaaclab_tasks.utils import get_checkpoint_path
from isaaclab_tasks.utils.parse_cfg import load_cfg_from_registry
from isaaclab_rl.rsl_rl import RslRlOnPolicyRunnerCfg, RslRlVecEnvWrapper
# Set torch backends for better performance
torch.backends.cuda.matmul.allow_tf32 = True
torch.backends.cudnn.allow_tf32 = True
torch.backends.cudnn.deterministic = False
torch.backends.cudnn.benchmark = False
def main():
"""Train navigation policy with RSL-RL."""
# Load the configurations from the registry
env_cfg = load_cfg_from_registry(args_cli.task, "env_cfg_entry_point")
agent_cfg: RslRlOnPolicyRunnerCfg = load_cfg_from_registry(args_cli.task, "rsl_rl_cfg_entry_point")
# Override config from command line
if args_cli.num_envs is not None:
env_cfg.scene.num_envs = args_cli.num_envs
if args_cli.seed is not None:
agent_cfg.seed = args_cli.seed
if args_cli.max_iterations is not None:
agent_cfg.max_iterations = args_cli.max_iterations
if args_cli.run_name is not None:
agent_cfg.run_name = args_cli.run_name
# Create the environment
env = gym.make(args_cli.task, cfg=env_cfg, render_mode="rgb_array" if args_cli.video else None)
# Wrap the environment
env = RslRlVecEnvWrapper(env)
# Specify log directory
log_root_path = os.path.join("logs", "rsl_rl", agent_cfg.experiment_name)
log_root_path = os.path.abspath(log_root_path)
print(f"[INFO] Logging experiment in directory: {log_root_path}")
# Specify run directory based on timestamp
log_dir = datetime.now().strftime("%Y-%m-%d_%H-%M-%S")
if agent_cfg.run_name:
log_dir += f"_{agent_cfg.run_name}"
log_dir = os.path.join(log_root_path, log_dir)
# Create runner
runner = OnPolicyRunner(env, agent_cfg.to_dict(), log_dir=log_dir, device=agent_cfg.device)
# Optional: warm-start from an existing checkpoint (e.g. cross-robot fine-tuning).
if args_cli.checkpoint is not None:
ckpt_path = os.path.abspath(args_cli.checkpoint)
if not os.path.isfile(ckpt_path):
raise FileNotFoundError(f"Checkpoint not found: {ckpt_path}")
print(f"[INFO] Warm-starting from checkpoint: {ckpt_path}")
print(f"[INFO] load_optimizer = {args_cli.load_optimizer}")
runner.load(ckpt_path, load_optimizer=args_cli.load_optimizer)
# Write git state to log
runner.add_git_repo_to_log(__file__)
# Save configuration
dump_yaml(os.path.join(log_dir, "params", "env.yaml"), env_cfg)
dump_yaml(os.path.join(log_dir, "params", "agent.yaml"), agent_cfg)
dump_pickle(os.path.join(log_dir, "params", "env.pkl"), env_cfg)
dump_pickle(os.path.join(log_dir, "params", "agent.pkl"), agent_cfg)
# Run training
runner.learn(num_learning_iterations=agent_cfg.max_iterations, init_at_random_ep_len=True)
# Close the environment
env.close()
if __name__ == "__main__":
# Run the main function
main()
# Close simulation
simulation_app.close()