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,10 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Robot-specific configuration modules for navigation tasks."""
from .b2w import *
from .aow_d import *
from .go2 import *
@@ -0,0 +1,78 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
import gymnasium as gym
from . import agents, navigation_env_cfg
##
# Register Gym environments.
##
##############################################################################################################
# MDPO
gym.register(
id="Isaac-Nav-MDPO-AoW-D-v0",
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavMDPORunnerCfg,
},
)
gym.register(
id="Isaac-Nav-MDPO-AoW-D-Play-v0",
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavMDPORunnerCfg,
},
)
gym.register(
id="Isaac-Nav-MDPO-AoW-D-Dev-v0",
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg_DEV,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavMDPORunnerDevCfg,
},
)
######################################################################################
# PPO
gym.register(
id="Isaac-Nav-PPO-AoW-D-v0",
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavPPORunnerCfg,
},
)
gym.register(
id="Isaac-Nav-PPO-AoW-D-Play-v0",
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavPPORunnerCfg,
},
)
gym.register(
id="Isaac-Nav-PPO-AoW-D-Dev-v0",
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": navigation_env_cfg.AowDNavigationEnvCfg_DEV,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.AowDNavPPORunnerDevCfg,
},
)
@@ -0,0 +1,8 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Agent configurations for AoW-D navigation tasks."""
from . import rsl_rl_cfg
@@ -0,0 +1,119 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""RSL-RL agent configurations for AoW-D navigation tasks."""
from isaaclab.utils import configclass
from isaaclab_nav_task.navigation.config.rl_cfg import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class AowDNavMDPORunnerCfg(RslRlOnPolicyRunnerCfg):
"""MDPO runner configuration for AoW-D navigation."""
num_steps_per_env = 16
max_iterations = 15000
save_interval = 500
logger = "wandb"
seed = 50
wandb_project = "isaaclab_nav_aow_d"
experiment_name = "aow_d_navigation_mdpo"
empirical_normalization = False
reward_shifting_value = 0.05
policy = RslRlPpoActorCriticCfg(
class_name="ActorCriticSRU",
init_noise_std=1.0,
actor_hidden_dims=[512, 256, 128],
critic_hidden_dims=[512, 256, 128],
activation="elu",
rnn_hidden_size=512,
rnn_type="lstm_sru",
rnn_num_layers=1,
dropout=0.2,
num_cameras=1,
image_input_dims=(64, 5, 8),
)
algorithm = RslRlPpoAlgorithmCfg(
class_name="MDPO",
value_loss_coef=0.02,
use_clipped_value_loss=True,
clip_param=0.2,
value_clip_param=0.2,
entropy_coef=0.00375,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=1.0e-3,
schedule="adaptive",
gamma=0.995,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
@configclass
class AowDNavMDPORunnerDevCfg(AowDNavMDPORunnerCfg):
"""Development configuration for MDPO with reduced iterations."""
def __post_init__(self):
super().__post_init__()
self.max_iterations = 300
self.experiment_name = "aow_d_navigation_mdpo_dev"
self.logger = "tensorboard"
@configclass
class AowDNavPPORunnerCfg(RslRlOnPolicyRunnerCfg):
"""PPO runner configuration for AoW-D navigation."""
num_steps_per_env = 24
max_iterations = 15000
save_interval = 500
logger = "wandb"
wandb_project = "isaaclab_nav_aow_d"
experiment_name = "aow_d_navigation_ppo"
empirical_normalization = False
policy = RslRlPpoActorCriticCfg(
class_name="ActorCriticSRU",
init_noise_std=1.0,
actor_hidden_dims=[512, 256, 128],
critic_hidden_dims=[512, 256, 128],
activation="elu",
rnn_hidden_size=256,
rnn_type="lstm_sru",
num_cameras=1,
image_input_dims=(64, 5, 8),
)
algorithm = RslRlPpoAlgorithmCfg(
class_name="PPO",
value_loss_coef=0.1,
use_clipped_value_loss=True,
clip_param=0.2,
entropy_coef=0.005,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=1.0e-3,
schedule="adaptive",
gamma=0.995,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
@configclass
class AowDNavPPORunnerDevCfg(AowDNavPPORunnerCfg):
"""Development configuration for PPO with reduced iterations."""
def __post_init__(self):
super().__post_init__()
self.max_iterations = 300
self.experiment_name = "aow_d_navigation_ppo_dev"
self.logger = "tensorboard"
@@ -0,0 +1,60 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""AoW-D (Anymal on Wheels) specific configuration for navigation environment."""
from isaaclab.utils import configclass
from isaaclab_nav_task.navigation.navigation_env_cfg import NavigationEnvCfg
import isaaclab_nav_task.navigation.mdp as mdp
from isaaclab_nav_task.navigation.assets import ANYMAL_D_ON_WHEELS_CFG # isort: skip
@configclass
class AowDNavigationEnvCfg(NavigationEnvCfg):
def __post_init__(self):
super().__post_init__()
from isaaclab_nav_task.navigation.mdp.observations import initialize_depth_noise_generator
from isaaclab_nav_task.navigation.mdp.depth_utils.camera_config import get_camera_config
initialize_depth_noise_generator(robot_name="aow_d", use_jit_precompiled=False)
camera_config = get_camera_config("aow_d")
CAMERA_RESOLUTION = camera_config.resolution
self.scene.robot = ANYMAL_D_ON_WHEELS_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
self.scene.terrain.max_init_terrain_level = 10
self.scene.terrain.terrain_generator.difficulty_range = [0.5, 1.0]
self.scene.terrain.terrain_generator.curriculum = False
@configclass
class AowDNavigationEnvCfg_DEV(AowDNavigationEnvCfg):
def __post_init__(self):
super().__post_init__()
self.scene.terrain.terrain_generator.num_rows = 1
self.scene.terrain.terrain_generator.num_cols = 30
self.scene.terrain.max_init_terrain_level = 10
self.scene.terrain.terrain_generator.difficulty_range = [0.4, 0.8]
self.scene.terrain.terrain_generator.curriculum = True
self.scene.num_envs = 1
@configclass
class AowDNavigationEnvCfg_PLAY(AowDNavigationEnvCfg):
def __post_init__(self):
super().__post_init__()
self.scene.num_envs = 20
self.scene.env_spacing = 2.5
self.scene.terrain.max_init_terrain_level = None
if self.scene.terrain.terrain_generator is not None:
self.scene.terrain.terrain_generator.num_rows = 2
self.scene.terrain.terrain_generator.num_cols = 2
self.observations.policy.enable_corruption = False
self.events.base_external_force_torque = None
self.events.push_robot = None
@@ -0,0 +1,78 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
import gymnasium as gym
from . import agents, navigation_env_cfg
##
# Register Gym environments.
##
##############################################################################################################
# MDPO
gym.register(
id="Isaac-Nav-MDPO-B2W-v0",
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavMDPORunnerCfg,
},
)
gym.register(
id="Isaac-Nav-MDPO-B2W-Play-v0",
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavMDPORunnerCfg,
},
)
gym.register(
id="Isaac-Nav-MDPO-B2W-Dev-v0",
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg_DEV,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavMDPORunnerDevCfg,
},
)
######################################################################################
# PPO
gym.register(
id="Isaac-Nav-PPO-B2W-v0",
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavPPORunnerCfg,
},
)
gym.register(
id="Isaac-Nav-PPO-B2W-Play-v0",
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavPPORunnerCfg,
},
)
gym.register(
id="Isaac-Nav-PPO-B2W-Dev-v0",
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": navigation_env_cfg.B2WNavigationEnvCfg_DEV,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.B2WNavPPORunnerDevCfg,
},
)
@@ -0,0 +1,8 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Agent configurations for B2W navigation tasks."""
from . import rsl_rl_cfg
@@ -0,0 +1,126 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""RSL-RL agent configurations for B2W navigation tasks."""
from isaaclab.utils import configclass
from isaaclab_nav_task.navigation.config.rl_cfg import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class B2WNavMDPORunnerCfg(RslRlOnPolicyRunnerCfg):
"""MDPO runner configuration for B2W navigation."""
num_steps_per_env = 16
max_iterations = 15000
save_interval = 500
logger = "wandb"
seed = 60
wandb_project = "isaaclab_nav_b2w"
experiment_name = "b2w_navigation_mdpo"
empirical_normalization = False
reward_shifting_value = 0.05
policy = RslRlPpoActorCriticCfg(
class_name="ActorCriticSRU",
init_noise_std=1.0,
actor_hidden_dims=[512, 256, 128],
critic_hidden_dims=[512, 256, 128],
activation="elu",
rnn_hidden_size=512,
rnn_type="lstm_sru",
rnn_num_layers=1,
dropout=0.2,
num_cameras=1,
image_input_dims=(64, 5, 8), # depth image: 64 channels * 5 * 8 = 2560
height_input_dims=(64, 7, 7), # encoded height_scan_critic: 64*7*7 = 3136
)
algorithm = RslRlPpoAlgorithmCfg(
class_name="MDPO",
value_loss_coef=0.02,
use_clipped_value_loss=True,
clip_param=0.2,
value_clip_param=0.2,
entropy_coef=0.00375,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=1.0e-3,
schedule="exponential",
gamma=0.999,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
@configclass
class B2WNavMDPORunnerDevCfg(B2WNavMDPORunnerCfg):
"""Development configuration for MDPO with reduced iterations."""
def __post_init__(self):
super().__post_init__()
self.max_iterations = 300
self.experiment_name = "b2w_navigation_mdpo_dev"
self.logger = "tensorboard"
@configclass
class B2WNavPPORunnerCfg(RslRlOnPolicyRunnerCfg):
"""PPO runner configuration for B2W navigation."""
num_steps_per_env = 16
max_iterations = 15000
save_interval = 500
logger = "wandb"
seed = 60
wandb_project = "isaaclab_nav_b2w"
experiment_name = "b2w_navigation_ppo"
empirical_normalization = False
reward_shifting_value = 0.05
policy = RslRlPpoActorCriticCfg(
class_name="ActorCriticSRU",
init_noise_std=1.0,
actor_hidden_dims=[512, 256, 128],
critic_hidden_dims=[512, 256, 128],
activation="elu",
rnn_hidden_size=512,
rnn_type="lstm_sru",
rnn_num_layers=1,
dropout=0.2,
num_cameras=1,
image_input_dims=(64, 5, 8), # depth image: 64 channels * 5 * 8 = 2560
height_input_dims=(64, 7, 7), # encoded height_scan_critic: 64*7*7 = 3136
)
algorithm = RslRlPpoAlgorithmCfg(
class_name="PPO",
value_loss_coef=0.02,
use_clipped_value_loss=True,
clip_param=0.2,
value_clip_param=0.2,
entropy_coef=0.00375,
num_learning_epochs=5,
num_mini_batches=4,
learning_rate=1.0e-3,
schedule="adaptive",
gamma=0.995,
lam=0.95,
desired_kl=0.01,
max_grad_norm=1.0,
)
@configclass
class B2WNavPPORunnerDevCfg(B2WNavPPORunnerCfg):
"""Development configuration for PPO with reduced iterations."""
def __post_init__(self):
super().__post_init__()
self.max_iterations = 300
self.experiment_name = "b2w_navigation_ppo_dev"
self.logger = "tensorboard"
@@ -0,0 +1,139 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""B2W specific configuration for navigation environment."""
import os
from isaaclab.utils import configclass
from isaaclab.managers import SceneEntityCfg
from isaaclab_nav_task.navigation.navigation_env_cfg import NavigationEnvCfg
import isaaclab_nav_task.navigation.mdp as mdp
from isaaclab_nav_task.navigation.assets import B2W_CFG, ISAACLAB_NAV_TASKS_ASSETS_DIR # isort: skip
LEG_JOINT_NAMES = [".*hip_joint", ".*thigh_joint", ".*calf_joint"]
WHEEL_JOINT_NAMES = [".*foot_joint"]
@configclass
class B2WNavigationEnvCfg(NavigationEnvCfg):
def __post_init__(self):
super().__post_init__()
from isaaclab_nav_task.navigation.mdp.observations import initialize_depth_noise_generator
from isaaclab_nav_task.navigation.mdp.depth_utils.camera_config import get_camera_config
initialize_depth_noise_generator(robot_name="b2w", use_jit_precompiled=False)
camera_config = get_camera_config("b2w")
CAMERA_RESOLUTION = camera_config.resolution
self.scene.robot = B2W_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
self.scene.raycast_camera.prim_path = "{ENV_REGEX_NS}/Robot/base_link"
self.scene.raycast_camera.offset.pos = (0.387, 0.0, 0.28)
self.scene.height_scanner_critic.prim_path = "{ENV_REGEX_NS}/Robot/base_link"
self.terminations.base_contact.params = {"sensor_cfg": SceneEntityCfg("contact_forces", body_names=["base_link", ".*hip", ".*thigh"]), "threshold": 1.0}
self.actions.velocity_command.low_level_position_action = mdp.JointPositionActionCfg(asset_name="robot", joint_names=[".*hip_joint", ".*thigh_joint", ".*calf_joint"], scale=0.5, use_default_offset=True)
self.actions.velocity_command.low_level_velocity_action = mdp.JointVelocityActionCfg(asset_name="robot", joint_names=[".*foot_joint"], scale=5.0, use_default_offset=True)
self.actions.velocity_command.low_level_policy_file = os.path.join(ISAACLAB_NAV_TASKS_ASSETS_DIR, "Policies", "locomotion", "b2w", "policy_b2w_new_2.pt")
self.rewards.joint_acc_l2_joint.params = {"asset_cfg": SceneEntityCfg("robot", joint_names=LEG_JOINT_NAMES+WHEEL_JOINT_NAMES)}
self.terminations.base_contact.params = {"sensor_cfg": SceneEntityCfg("contact_forces", body_names=["base_link", ".*hip", ".*thigh"]), "threshold": 1.0}
self.events.randomize_low_pass_filter_alpha.params = {
"alpha_range": (0.1, 0.6),
"action_term": "velocity_command",
"per_dimension": True,
"alpha_range_vx": (0.1, 0.6),
"alpha_range_vy": (0.1, 0.6),
"alpha_range_omega": (0.1, 0.6),
}
self.scene.terrain.max_init_terrain_level = 10
self.scene.terrain.terrain_generator.difficulty_range = [0.5, 1.0]
self.scene.terrain.terrain_generator.curriculum = False
@configclass
class B2WNavigationEnvCfg_DEV(B2WNavigationEnvCfg):
def __post_init__(self):
super().__post_init__()
self.scene.terrain.terrain_generator.num_rows = 2
self.scene.terrain.terrain_generator.num_cols = 30
self.scene.terrain.max_init_terrain_level = 10
self.scene.terrain.terrain_generator.difficulty_range = [0.5, 1.0]
self.scene.terrain.terrain_generator.curriculum = False
@configclass
class B2WNavigationEnvCfg_PLAY(B2WNavigationEnvCfg):
def __post_init__(self):
super().__post_init__()
self.scene.num_envs = 20
self.scene.env_spacing = 2.5
self.scene.terrain.max_init_terrain_level = None
if self.scene.terrain.terrain_generator is not None:
self.scene.terrain.terrain_generator.num_rows = 2
self.scene.terrain.terrain_generator.num_cols = 2
# ---- PLAY_DIFFICULTY="lo,hi": difficulty band ----
lo, hi = 0.5, 1.0
_play_diff = os.environ.get("PLAY_DIFFICULTY", "").strip()
if _play_diff:
_parts = _play_diff.replace(" ", "").split(",")
lo, hi = float(_parts[0]), float(_parts[1])
self.scene.terrain.terrain_generator.difficulty_range = [lo, hi]
self.scene.terrain.terrain_generator.curriculum = False
print(f"[B2W PLAY] terrain difficulty_range = [{lo}, {hi}] (curriculum off)")
sub_terrains = self.scene.terrain.terrain_generator.sub_terrains
# PLAY_MAZE_ONLY=1: 100% maze sub-terrain
_maze_only = os.environ.get("PLAY_MAZE_ONLY", "").strip().lower() in ("1", "true", "yes")
if _maze_only and "maze" in sub_terrains:
for name in list(sub_terrains.keys()):
sub_terrains[name].proportion = 1.0 if name == "maze" else 0.0
print(f"[B2W PLAY] PLAY_MAZE_ONLY=1 -> 100% maze sub-terrain")
# PLAY_SUBTERRAIN_MIX="maze=1,non_maze=0,pits=0"
_mix = os.environ.get("PLAY_SUBTERRAIN_MIX", "").strip()
if _mix:
overrides = {}
for part in _mix.split(","):
if "=" not in part:
continue
k, v = part.split("=", 1)
overrides[k.strip()] = float(v.strip())
for name, prop in overrides.items():
if name in sub_terrains:
sub_terrains[name].proportion = prop
final = {n: sub_terrains[n].proportion for n in sub_terrains}
print(f"[B2W PLAY] PLAY_SUBTERRAIN_MIX -> {final}")
# PLAY_CELL_SIZE: meters per maze cell
_play_cell = os.environ.get("PLAY_CELL_SIZE", "").strip()
if _play_cell:
new_cell = float(_play_cell)
for cfg_sub in sub_terrains.values():
cfg_sub.cell_size = new_cell
tile_m = 15 * new_cell
self.scene.terrain.terrain_generator.size = (tile_m, tile_m)
print(f"[B2W PLAY] PLAY_CELL_SIZE={new_cell}m -> tile={tile_m}m")
# PLAY_CLASSIC_MAZE=1: paper-style uniform walls
_classic = os.environ.get("PLAY_CLASSIC_MAZE", "").strip().lower() in ("1", "true", "yes")
if _classic and "maze" in sub_terrains:
sub_terrains["maze"].randomize_wall = False
sub_terrains["maze"].random_wall_ratio = 0.0
print(f"[B2W PLAY] PLAY_CLASSIC_MAZE=1 -> classic uniform walls in maze")
self.observations.policy.enable_corruption = False
self.events.base_external_force_torque = None
self.events.push_robot = None
@@ -0,0 +1,58 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
import gymnasium as gym
from . import agents, navigation_env_cfg
##
# Register Gym environments.
##
##############################################################################################################
# PPO
gym.register(
id="Isaac-Nav-PPO-Go2-v0",
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": navigation_env_cfg.Go2NavigationEnvCfg,
# MixedCfg is the cold-start tuned variant of the Dev hyperparams;
# the original B2W-FT ``Go2NavPPORunnerCfg`` collapses exploration on a
# from-scratch run (init_std=0.5, entropy=0.001, clip=0.1).
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.Go2NavPPORunnerMixedCfg,
},
)
gym.register(
id="Isaac-Nav-PPO-Go2-Play-v0",
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": navigation_env_cfg.Go2NavigationEnvCfg_PLAY,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.Go2NavPPORunnerCfg,
},
)
gym.register(
id="Isaac-Nav-PPO-Go2-Dev-v0",
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": navigation_env_cfg.Go2NavigationEnvCfg_DEV,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.Go2NavPPORunnerDevCfg,
},
)
gym.register(
id="Isaac-Nav-PPO-Go2-PureMaze-v0",
entry_point="isaaclab_nav_task.navigation:NavigationEnv",
disable_env_checker=True,
kwargs={
"env_cfg_entry_point": navigation_env_cfg.Go2NavigationEnvCfg_PureMaze,
"rsl_rl_cfg_entry_point": agents.rsl_rl_cfg.Go2NavPPORunnerPureMazeCfg,
},
)
@@ -0,0 +1,8 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Agent configurations for Go2 navigation tasks."""
from . import rsl_rl_cfg
@@ -0,0 +1,186 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""RSL-RL agent configurations for Unitree Go2 navigation tasks.
The policy block is intentionally identical to ``B2WNavPPORunnerCfg`` so that a
B2W checkpoint can be warm-started via ``--resume`` / ``--load_run`` with
``strict=True`` state-dict loading.
"""
from isaaclab.utils import configclass
from isaaclab_nav_task.navigation.config.rl_cfg import (
RslRlOnPolicyRunnerCfg,
RslRlPpoActorCriticCfg,
RslRlPpoAlgorithmCfg,
)
@configclass
class Go2NavPPORunnerCfg(RslRlOnPolicyRunnerCfg):
"""PPO runner configuration for Go2 navigation, tuned for fine-tuning from a B2W checkpoint."""
num_steps_per_env = 16
max_iterations = 5000
save_interval = 200
# Use TensorBoard by default; wandb requires WANDB_API_KEY and an interactive
# tty for first-time login, neither of which is available inside the headless
# docker container. All downstream cfgs (Dev / PureMaze) already override to
# tensorboard; the base now matches so the mixed-terrain task
# ``Isaac-Nav-PPO-Go2-v0`` no longer crashes on cold start.
logger = "tensorboard"
seed = 42
wandb_project = "isaaclab_nav_go2"
experiment_name = "go2_navigation_ppo_ft_from_b2w"
empirical_normalization = False
reward_shifting_value = 0.05
# IMPORTANT: must match the B2W policy block byte-for-byte so that
# ActorCriticSRU.load_state_dict(..., strict=True) succeeds.
policy = RslRlPpoActorCriticCfg(
class_name="ActorCriticSRU",
init_noise_std=0.5, # ↓ vs 1.0: warm-start, less exploration noise
actor_hidden_dims=[512, 256, 128],
critic_hidden_dims=[512, 256, 128],
activation="elu",
rnn_hidden_size=512,
rnn_type="lstm_sru",
rnn_num_layers=1,
dropout=0.2,
num_cameras=1,
image_input_dims=(64, 5, 8),
height_input_dims=(64, 7, 7),
)
# Conservative fine-tuning hyperparameters: smaller LR, tighter clip,
# smaller KL target, lower grad-norm cap.
algorithm = RslRlPpoAlgorithmCfg(
class_name="PPO",
value_loss_coef=0.05,
use_clipped_value_loss=True,
clip_param=0.1,
value_clip_param=0.1,
entropy_coef=0.001,
num_learning_epochs=3,
num_mini_batches=4,
learning_rate=3.0e-4,
schedule="adaptive",
gamma=0.995,
lam=0.95,
desired_kl=0.005,
max_grad_norm=0.5,
)
@configclass
class Go2NavPPORunnerDevCfg(Go2NavPPORunnerCfg):
"""Dev cfg used by the smoke-test task (Isaac-Nav-PPO-Go2-Dev-v0).
Unlike the production ``Go2NavPPORunnerCfg`` (whose hyperparameters are
deliberately conservative for warm-starting from a B2W checkpoint), the dev
cfg is meant for *from-scratch* Go2 training with the Odin1 camera. The
conservative FT settings (entropy_coef=0.001, desired_kl=0.005, clip=0.1,
lr=3e-4) caused exploration to collapse (noise_std plateaued at ~0.157) and
success to stall at ~0.5 by 23k iters. Here we re-open exploration and the
learning rate so the policy can escape that local optimum.
"""
def __post_init__(self):
super().__post_init__()
self.max_iterations = 300
self.experiment_name = "go2_navigation_ppo_dev"
self.logger = "tensorboard"
# ---- Phase 1 (from-scratch, 0->2000): re-open exploration ----
# init_noise_std only takes effect on a from-scratch run (a resumed
# run loads the std from the checkpoint, which was ~0.76 after Phase 1).
# Phase 1 broke the 0.5 plateau (success ~0.65, noise_std held at 0.76),
# but two issues appeared: (a) adaptive LR floored at 1e-5 because
# desired_kl=0.01 was too tight against clip=0.2/entropy=0.005, throttling
# late updates; (b) Loss/value_function spiked to ~127 around iter 1600.
#
# ---- Phase 2 (resume 2000->5000): refine & stabilise ----
# Relax desired_kl so adaptive LR can climb off the 1e-5 floor, anneal
# exploration down, and tighten clip to curb the value-loss instability.
#
# ---- Phase 3 (resume 7000->14000, difficulty [0.2, 0.6]): ----
# Kept Phase 2 hyperparams. Result: success 0.93, base_contact -71%,
# tip-over -76%. Confirmed depth is used and avoidance generalises when
# the task forces it.
#
# ---- Phase 4 (resume 14000->24000, difficulty [0.3, 0.8]): ----
# noise_std fell to ~0.20 in Phase 3 (close to collapse). The Phase 4
# difficulty jump (0.6 -> 0.8) demands fresh exploration on unseen
# terrain, so re-open entropy a notch. Result: success climbed 0 -> 0.88
# (peak 0.91 @ iter 20519). But noise_std overshot to 0.33 by iter 23999,
# LR hit 1e-5 floor again, and success retreated from 0.905 -> 0.876.
#
# ---- Phase 5 (resume 24000->?, difficulty [0.3, 0.8]): refine ----
# Anneal entropy back to let noise_std settle ~0.22-0.25 so the policy
# can stop trembling and finish the last refinement past 0.91 success.
self.policy.init_noise_std = 1.0 # only matters on a fresh run
self.algorithm.entropy_coef = 0.003 # 0.005 -> 0.003: anneal exploration for Phase 5 refinement
self.algorithm.desired_kl = 0.02 # 0.01 -> 0.02: let adaptive LR recover off the 1e-5 floor
self.algorithm.clip_param = 0.15 # 0.2 -> 0.15: smaller, more stable policy updates
self.algorithm.value_clip_param = 0.15 # 0.2 -> 0.15: match, curb value-loss spikes
self.algorithm.learning_rate = 1.0e-3 # adaptive ceiling reference
self.algorithm.num_learning_epochs = 5 # keep: more updates per batch
self.algorithm.max_grad_norm = 0.8 # 1.0 -> 0.8: tighten to damp the value-fn spike
@configclass
class Go2NavPPORunnerMixedCfg(Go2NavPPORunnerDevCfg):
"""Cold-start hyperparameters for mixed-terrain training (maze + non_maze
+ pits) on the full-size ``Isaac-Nav-PPO-Go2-v0`` task.
Inherits from the Dev cfg (which already overrides the B2W-FT defaults to
something usable from scratch), but rolls the *exploration-heavy* knobs
BACK to the Phase 1/2 values that were proven to break the 0.5 plateau in
the dev curriculum, rather than the Phase 5 refinement settings the Dev cfg
currently sits at.
Distilled lessons from the dev curriculum (see comments in
``Go2NavPPORunnerDevCfg``):
* Phase 1 (entropy=0.005, init_std=1.0): broke success 0.5 -> 0.65 plateau
but kl=0.01 was too tight (LR floored at 1e-5).
* Phase 2 (kl=0.02, clip=0.15, epochs=5): unflored the LR and tamed the
Loss/value_function spike.
* Phase 5 (entropy=0.003): refinement-only, kills exploration too early
for a from-scratch run.
Cold-start recipe = Phase 1 exploration + Phase 2 stability:
entropy=0.005, init_std=1.0, kl=0.02, clip=0.15, lr=1e-3, epochs=5,
grad_norm=0.8.
"""
def __post_init__(self):
super().__post_init__()
# Independent experiment dir keeps mixed runs out of the dev TB tree.
self.experiment_name = "go2_navigation_ppo_mixed"
# Override Dev's Phase 5 refinement back to cold-start values.
self.policy.init_noise_std = 1.0 # Phase 1: re-open exploration
self.algorithm.entropy_coef = 0.005 # Phase 1/4: cold-start exploration
self.algorithm.desired_kl = 0.02 # Phase 2: avoid 1e-5 LR floor
self.algorithm.clip_param = 0.15 # Phase 2: avoid value-loss spikes
self.algorithm.value_clip_param = 0.15
self.algorithm.learning_rate = 1.0e-3 # adaptive ceiling
self.algorithm.num_learning_epochs = 5
self.algorithm.max_grad_norm = 0.8
@configclass
class Go2NavPPORunnerPureMazeCfg(Go2NavPPORunnerDevCfg):
"""Hyperparameters for the pure-maze training task.
Inherits the Phase 5 dev hyperparams (they shipped a strong checkpoint at
iter 27800 on the mixed terrain). Only the log directory differs so
pure-maze runs don't mix with the dev curriculum's TensorBoard history.
"""
def __post_init__(self):
super().__post_init__()
self.experiment_name = "go2_navigation_ppo_puremaze"
@@ -0,0 +1,445 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Unitree Go2 specific configuration for navigation environment."""
import os
from isaaclab.utils import configclass
from isaaclab.managers import SceneEntityCfg
from isaaclab_nav_task.navigation.navigation_env_cfg import NavigationEnvCfg
import isaaclab_nav_task.navigation.mdp as mdp
from isaaclab_nav_task.navigation.assets import GO2_CFG, ISAACLAB_NAV_TASKS_ASSETS_DIR # isort: skip
# Go2 has 12 leg joints (no wheels). Joint names use the underscore convention
# from the IsaacLab Go2 USD: FL_hip_joint, FL_thigh_joint, FL_calf_joint, ...
LEG_JOINT_NAMES = [".*_hip_joint", ".*_thigh_joint", ".*_calf_joint"]
@configclass
class Go2NavigationEnvCfg(NavigationEnvCfg):
"""Navigation env for Unitree Go2 (legs-only quadruped).
The locomotion checkpoint expected at
``assets/data/Policies/locomotion/go2/policy_go2_jit.pt`` was converted from
a rsl_rl checkpoint trained on Isaac-Velocity-Flat-Unitree-Go2-v0:
- input : 48-dim observation (matches sru-navigation-sim's
LowLevelPolicyCfg)
- output : 12-dim joint position deltas (one per leg joint)
"""
def __post_init__(self):
super().__post_init__()
from isaaclab_nav_task.navigation.mdp.observations import initialize_depth_noise_generator
from isaaclab_nav_task.navigation.mdp.depth_utils.camera_config import get_camera_config
initialize_depth_noise_generator(robot_name="go2", use_jit_precompiled=False)
camera_config = get_camera_config("go2")
# Camera resolution is consumed implicitly through the encoder; sru-nav
# always feeds (64, 40) into the VAE regardless of robot.
_ = camera_config
# ---- Robot ----
self.scene.robot = GO2_CFG.replace(prim_path="{ENV_REGEX_NS}/Robot")
# Go2's body link is named "base" in the IsaacLab USD (not "base_link"
# like B2W).
self.scene.raycast_camera.prim_path = "{ENV_REGEX_NS}/Robot/base"
# Real-robot Odin1 mount on Go2: 25.8 cm forward, 15.4 cm above body
# center, camera looking straight ahead (no pitch).
# NOTE: The extrinsic Tcl from the Odin1 calibration is camera-from-lidar,
# not camera-from-base. Until we have T_base_lidar (lidar pose in Go2 base
# frame), keep this measured mount offset rather than chaining Tcl.
self.scene.raycast_camera.offset.pos = (0.258, 0.0, 0.154)
self.scene.raycast_camera.offset.rot = (1.0, 0.0, 0.0, 0.0)
self.scene.height_scanner_critic.prim_path = "{ENV_REGEX_NS}/Robot/base"
# ---- Camera intrinsics: Odin1 (LiDAR-aligned depth) ----
# Real Odin1 @ 1600x1296:
# fx = 737.357, fy = 737.292, cx = 794.372, cy = 666.259
# hFOV ~94.67 deg, vFOV ~82.65 deg
# To preserve the FOV while keeping the upstream downsample_factor=3
# (raycast at 192x120 then downsample to the VAE-required 64x40), we
# scale the intrinsics linearly:
# fx_192 = 737.357 * 192/1600 = 88.48 px
# fy_120 = 737.292 * 120/1296 = 68.27 px
# cx_192 = 794.372 * 192/1600 = 95.32 px
# cy_120 = 666.259 * 120/1296 = 61.69 px
# Distortion (k2..k7) is ignored: raycast uses an ideal pinhole. The
# real-side pipeline must undistort before feeding the network.
# max_distance raised slightly because Odin1's wider FOV picks up more
# nearby clutter; keep 11 m to match upstream.
from isaaclab.sensors import patterns
self.scene.raycast_camera.max_distance = 11.0
self.scene.raycast_camera.pattern_cfg = patterns.PinholeCameraPatternCfg.from_ros_camera_info(
fx=88.48,
fy=68.27,
cx=95.32,
cy=61.69,
width=192,
height=120,
downsample_factor=3, # 192x120 -> 64x40 to match VAE input
)
# ---- Goal placement ----
# The default goal height offset (0.2-0.8 m above ground) is tuned for
# B2W's body height (~0.5-0.6 m). Go2 stands at ~0.3 m, so lower the
# range to (0.1, 0.4) m to keep the goal marker near the Go2 body.
# NOTE: success/termination is purely horizontal (xy), so this is mostly
# a visual fix + removes the small constant z-error in the 3D
# reach_goal_xy_soft reward term.
self.commands.robot_goal.goal_height_offset_range = (0.1, 0.4)
# ---- Termination ----
# Penalize/terminate if the body, hips, thighs, or head links hit
# something. Go2's main body is "base"; the front "head" is split into
# two extra rigid links ("Head_upper" / "Head_lower" in the upstream
# Unitree Go2 USD) which stick forward ~10cm past the base. Without
# those head links in the watch-list, GUI playback shows the snout
# visually crashing into walls while the base contact sensor stays
# silent and the episode does not terminate. Including them closes
# that loophole.
self.terminations.base_contact.params = {
"sensor_cfg": SceneEntityCfg(
"contact_forces",
body_names=["base", ".*_hip", ".*_thigh", "Head_upper", "Head_lower"],
),
"threshold": 1.0,
}
# Diagnostic-only: tighten `terrain_fall` so it actually fires when the
# robot drops into the pit terrain. The base default of -2.0m never
# triggered for Go2 (standing base_z ~+0.4m, typical pit depth 0.75-2.25m
# -> body z bottoms out around -1.1m, well above -2.0m), making
# `Episode_Termination/terrain_fall` permanently 0 across phases 1-5.
# -0.3m means: body must be ~0.7m below normal standing height to fire,
# which cleanly captures real pit falls without flagging walking dips.
# NOTE: `terrain_fall` is `time_out=True`, so it does NOT trigger the
# -50 `episode_termination` penalty -- this is purely a metric fix.
self.terminations.terrain_fall.params = {"fall_height_threshold": -0.3}
# ---- Action interface (legs only, no wheels) ----
self.actions.velocity_command.low_level_position_action = mdp.JointPositionActionCfg(
asset_name="robot",
joint_names=LEG_JOINT_NAMES,
scale=0.25, # MUST match the scale used to train policy_go2_jit.pt
use_default_offset=True,
)
# Disable the velocity-action branch entirely (patched in
# navigation_se2_actions.py to be optional).
self.actions.velocity_command.low_level_velocity_action = None
self.actions.velocity_command.low_level_policy_file = os.path.join(
ISAACLAB_NAV_TASKS_ASSETS_DIR,
"Policies", "locomotion", "go2", "policy_go2_jit.pt",
)
# SE2 command space scale: Go2 cannot match B2W's wheeled top speed,
# so we shrink the SRU command range to what Go2 can actually track.
# The high-level SRU policy was trained on B2W with [1.0, 1.0, 1.0]; we
# shrink each axis so the same network output produces feasible Go2
# commands.
self.actions.velocity_command.scale = [0.6, 0.3, 0.7]
# ---- Reward shaping ----
self.rewards.joint_acc_l2_joint.params = {
"asset_cfg": SceneEntityCfg("robot", joint_names=LEG_JOINT_NAMES),
}
# Keep the B2W default termination penalty (-50.0). G0-G2 confirmed the
# Go2 locomotion JIT is stable enough that we do not need the relaxed
# -25 hedge anymore; restoring -50 makes wall hits / falls genuinely
# costly so the policy stops trading collisions for goal reward.
# (Only fires on `base_contact` + `large_pitch_angle`; `time_out`,
# `at_goal`, `terrain_fall` are all marked time_out=True and don't
# trigger this term.)
self.rewards.episode_termination.weight = -50.0
# Forward-facing depth camera only senses obstacles ahead of the robot.
# In G2.0 the agent learned to walk *backwards* (vx < 0) to hide obstacles
# from the camera and bypass forward-collision termination. Enable the
# backward-movement penalty (default weight is 0.0 in the base cfg).
# NOTE: the base CurriculumCfg disables this penalty after 500 global
# steps; if backward-walking re-emerges late in training, either delete
# ``curriculum.disable_backward_penalty`` or lift its ``disable_after_steps``.
self.rewards.backward_movement_penalty.weight = -1.0
# ---- Domain randomization ----
# Go2 responds slower than wheels; widen the low-pass filter range.
self.events.randomize_low_pass_filter_alpha.params = {
"alpha_range": (0.3, 0.7),
"action_term": "velocity_command",
"per_dimension": True,
"alpha_range_vx": (0.3, 0.7),
"alpha_range_vy": (0.3, 0.7),
"alpha_range_omega": (0.3, 0.7),
}
# ---- Terrain ----
# The Go2 locomotion .pt is flat-trained, so start with easier terrain.
# Defaults assume RESUMING a non-trivial ckpt (max_init level 5, band
# [0.3, 0.8]). For a COLD START set GO2_DIFFICULTY="0.0,0.4" (and the
# env var GO2_INIT_LEVEL=0 if you want everyone to start at the easiest
# row), otherwise the policy gets dropped into mid-difficulty terrain
# and stalls. Curriculum stays ON in both cases so envs auto-promote
# toward the high end as they succeed.
lo, hi = 0.3, 0.8
_diff = os.environ.get("GO2_DIFFICULTY", "").strip()
if _diff:
_parts = _diff.replace(" ", "").split(",")
lo, hi = float(_parts[0]), float(_parts[1])
init_level = 5
_lvl = os.environ.get("GO2_INIT_LEVEL", "").strip()
if _lvl:
init_level = int(_lvl)
self.scene.terrain.max_init_terrain_level = init_level
self.scene.terrain.terrain_generator.difficulty_range = [lo, hi]
self.scene.terrain.terrain_generator.curriculum = True
print(f"[Go2 Mixed] difficulty=[{lo}, {hi}], max_init_terrain_level={init_level} (curriculum on)")
# Drop the dedicated stairs sub-terrain for Go2: the locomotion JIT is
# trained on flat ground only, climbing stairs is unreliable, and the
# platform_mask on stair tops would otherwise bias goal sampling
# towards stair platforms (see PositionSampler.platform_repeat_count=10
# in mdp/navigation/goal_commands.py).
# NOTE: ``add_stairs_to_maze`` flag exists in HfMazeTerrainCfg but is
# never consumed by hf_terrains_maze.py, so the only real stair source
# is the ``"stairs"`` sub-terrain. We rebalance the remaining 3 to keep
# roughly the original maze:non_maze:pits ratio (3:2:2 -> ~0.43/0.29/0.29).
sub_terrains = self.scene.terrain.terrain_generator.sub_terrains
if "stairs" in sub_terrains:
del sub_terrains["stairs"]
if "maze" in sub_terrains:
sub_terrains["maze"].proportion = 0.43
if "non_maze" in sub_terrains:
sub_terrains["non_maze"].proportion = 0.29
if "pits" in sub_terrains:
sub_terrains["pits"].proportion = 0.28
# ---- Shrink tile size for 12 GB VRAM ----
# Defaults: 30m x 30m tiles with horizontal_scale=0.1 -> 300x300 cells
# per tile heightfield, x 6 rows x 30 cols x 3 sub-terrains = ~16M
# heightfield cells + 3 sub-terrain collision meshes. On a 12 GB 5070
# that OOMs above ~768 envs. Halve cell_size to 1.0m (matches what the
# PureMaze runs used, where 1024 envs ran stably): tile shrinks to
# 15m x 15m, heightfield drops 4x to ~4M cells. Override via env var
# GO2_CELL_SIZE if you want to go back to the paper-default 2.0m.
_cell = os.environ.get("GO2_CELL_SIZE", "1.0").strip()
if _cell:
new_cell = float(_cell)
for cfg_sub in sub_terrains.values():
cfg_sub.cell_size = new_cell
# grid_size stays (15, 15) -> tile_size = 15 * cell_size meters.
tile_m = 15 * new_cell
self.scene.terrain.terrain_generator.size = (tile_m, tile_m)
print(f"[Go2 Mixed] cell_size={new_cell}m -> tile={tile_m}m "
f"(set GO2_CELL_SIZE=2.0 to restore paper defaults)")
@configclass
class Go2NavigationEnvCfg_DEV(Go2NavigationEnvCfg):
"""Development configuration with smaller terrain and lower difficulty."""
def __post_init__(self):
super().__post_init__()
self.scene.terrain.terrain_generator.num_rows = 2
self.scene.terrain.terrain_generator.num_cols = 30
# The Go2 locomotion JIT is flat-trained. Starting at difficulty 0.3-0.8
# with no curriculum produced ~16% tip-overs (large_pitch_angle) and
# stalled success at ~0.5. Start from the easiest terrain and let the
# curriculum ramp difficulty up as the policy succeeds.
#
# Phase 1/2 trained on [0.0, 0.4] (success ~0.86, depth confirmed used
# via ablation). Phase 3 raises the band so the avoidance behaviour
# generalises to denser obstacles / deeper pits. Control the band per
# run with DEV_DIFFICULTY="lo,hi" (default stays [0.0, 0.4]); e.g.
# DEV_DIFFICULTY="0.2,0.6" (recommended Phase 3 bridge)
# DEV_DIFFICULTY="0.3,0.8" (Phase 4, near paper level)
# max_init_terrain_level stays 0 so a resumed policy re-enters at the
# easy end of the new band and the curriculum re-ramps from there.
lo, hi = 0.0, 0.4
_dev_diff = os.environ.get("DEV_DIFFICULTY", "").strip()
if _dev_diff:
_parts = _dev_diff.replace(" ", "").split(",")
lo, hi = float(_parts[0]), float(_parts[1])
self.scene.terrain.max_init_terrain_level = 0
self.scene.terrain.terrain_generator.difficulty_range = [lo, hi]
self.scene.terrain.terrain_generator.curriculum = True
print(f"[Go2 DEV] terrain difficulty_range = [{lo}, {hi}] (curriculum on)")
@configclass
class Go2NavigationEnvCfg_PureMaze(Go2NavigationEnvCfg):
"""Pure-maze training configuration.
All tiles are paper-style mazes:
* 100% ``maze`` sub-terrain (no ``non_maze`` / ``pits`` sub-terrains).
* Walls are uniform full-height rectangles (no randomized pillar/bar/cross
obstacles inserted into the maze pattern).
* Curriculum on, ramps difficulty from open to dense corridors.
Env-var overrides:
* ``PUREMAZE_DIFFICULTY="lo,hi"``: difficulty band (default ``"0.0,1.0"``;
higher band -> denser corridors / more dead-ends).
* ``PUREMAZE_CELL_SIZE``: meters per maze cell (default 2.0). Lowering
tightens corridors; tile size scales accordingly so total terrain area
stays the same per tile in cells.
"""
def __post_init__(self):
super().__post_init__()
sub_terrains = self.scene.terrain.terrain_generator.sub_terrains
# Lock to 100% maze, paper-style walls.
for name in list(sub_terrains.keys()):
sub_terrains[name].proportion = 1.0 if name == "maze" else 0.0
if "maze" in sub_terrains:
sub_terrains["maze"].randomize_wall = False
sub_terrains["maze"].random_wall_ratio = 0.0
# Difficulty range (curriculum on, ramps from easy to hard).
lo, hi = 0.0, 1.0
_diff = os.environ.get("PUREMAZE_DIFFICULTY", "").strip()
if _diff:
_parts = _diff.replace(" ", "").split(",")
lo, hi = float(_parts[0]), float(_parts[1])
self.scene.terrain.max_init_terrain_level = 0
self.scene.terrain.terrain_generator.difficulty_range = [lo, hi]
self.scene.terrain.terrain_generator.curriculum = True
# Cell size (corridor width).
_cell = os.environ.get("PUREMAZE_CELL_SIZE", "").strip()
if _cell:
new_cell = float(_cell)
for cfg_sub in sub_terrains.values():
cfg_sub.cell_size = new_cell
tile_m = 15 * new_cell
self.scene.terrain.terrain_generator.size = (tile_m, tile_m)
print(f"[Go2 PureMaze] cell_size={new_cell}m -> tile={tile_m}m, "
f"corridor ~{new_cell * 0.6:.2f}-{new_cell * 0.9:.2f}m")
# Terrain grid dimensions. Defaults are compact (3×10=30 tiles) to save
# VRAM; the original 6×30=180 tiles wasted mesh memory when most tiles
# were never visited (especially with few envs / play). Override via
# PUREMAZE_NUM_ROWS / PUREMAZE_NUM_COLS for large-scale training.
_rows = int(os.environ.get("PUREMAZE_NUM_ROWS", "3"))
_cols = int(os.environ.get("PUREMAZE_NUM_COLS", "10"))
self.scene.terrain.terrain_generator.num_rows = _rows
self.scene.terrain.terrain_generator.num_cols = _cols
print(f"[Go2 PureMaze] 100% maze sub-terrain, classic walls, "
f"difficulty=[{lo}, {hi}] (curriculum on), "
f"grid={_rows}x{_cols}={_rows*_cols} tiles")
@configclass
class Go2NavigationEnvCfg_PLAY(Go2NavigationEnvCfg):
"""Evaluation/visualization configuration."""
def __post_init__(self):
super().__post_init__()
self.scene.num_envs = 20
self.scene.env_spacing = 2.5
self.scene.terrain.max_init_terrain_level = None
if self.scene.terrain.terrain_generator is not None:
self.scene.terrain.terrain_generator.num_rows = 2
self.scene.terrain.terrain_generator.num_cols = 2
# ---- Evaluate on the SAME difficulty the policy was trained on ----
# The base Go2NavigationEnvCfg uses difficulty_range=[0.3, 0.8], but
# the Dev curriculum (what model_*.pt was actually trained on) ran on
# [0.0, 0.4]. Replaying on [0.3, 0.8] shows the policy unseen-hard
# terrain and makes it look like it "can't avoid" obstacles. Default
# the PLAY difficulty to the training band for an honest read; allow
# an explicit stress-test override via PLAY_DIFFICULTY="lo,hi".
lo, hi = 0.0, 0.4
_play_diff = os.environ.get("PLAY_DIFFICULTY", "").strip()
if _play_diff:
_parts = _play_diff.replace(" ", "").split(",")
lo, hi = float(_parts[0]), float(_parts[1])
self.scene.terrain.terrain_generator.difficulty_range = [lo, hi]
# Fixed difficulty band for evaluation (no curriculum ramping).
self.scene.terrain.terrain_generator.curriculum = False
print(f"[Go2 PLAY] terrain difficulty_range = [{lo}, {hi}] (curriculum off)")
# ---- Stress-test knobs for narrow-passage / dense-scene eval ----
# PLAY_CELL_SIZE: meters per maze cell (default 2.0). Lowering this
# tightens corridor width without changing tile size:
# 2.0m -> 1.7m-2.0m open corridors (default; very wide for Go2)
# 1.5m -> 1.0m-1.3m corridors (Go2 fits comfortably with margin)
# 1.2m -> 0.7m-0.9m corridors (tight, real perception test)
# 1.0m -> 0.5m-0.7m corridors (Go2 body width ~0.3m -> very tight)
# NOTE: grid_size stays (15,15) so tile size shrinks proportionally
# (30m -> 15m at cell_size=1.0). To preserve outer terrain footprint,
# the tile size is rescaled below.
_play_cell = os.environ.get("PLAY_CELL_SIZE", "").strip()
# PLAY_MAZE_ONLY=1: force 100% maze sub-terrain (drop pits/non_maze)
# so every tile is a corridor navigation challenge -- no easy open
# tiles diluting the sample.
_maze_only = os.environ.get("PLAY_MAZE_ONLY", "").strip().lower() in ("1", "true", "yes")
sub_terrains = self.scene.terrain.terrain_generator.sub_terrains
if _maze_only and "maze" in sub_terrains:
for name in list(sub_terrains.keys()):
sub_terrains[name].proportion = 1.0 if name == "maze" else 0.0
print(f"[Go2 PLAY] PLAY_MAZE_ONLY=1 -> 100% maze sub-terrain")
# PLAY_SUBTERRAIN_MIX="maze=0.5,non_maze=0.3,pits=0.2"
# Override any subset of sub-terrain proportions. Names not listed
# are left at their training-cfg default. Values do NOT need to sum
# to 1.0 (IsaacLab normalizes them internally before sampling).
# Setting a value to 0 effectively disables that sub-terrain.
_mix = os.environ.get("PLAY_SUBTERRAIN_MIX", "").strip()
if _mix:
overrides = {}
for part in _mix.split(","):
if "=" not in part:
continue
k, v = part.split("=", 1)
overrides[k.strip()] = float(v.strip())
for name, prop in overrides.items():
if name in sub_terrains:
sub_terrains[name].proportion = prop
else:
print(f"[Go2 PLAY] WARNING: unknown sub-terrain '{name}' "
f"(known: {list(sub_terrains.keys())})")
final = {n: sub_terrains[n].proportion for n in sub_terrains}
print(f"[Go2 PLAY] PLAY_SUBTERRAIN_MIX -> {final}")
if _play_cell:
new_cell = float(_play_cell)
for cfg_sub in sub_terrains.values():
cfg_sub.cell_size = new_cell
# Keep grid_size=(15,15) -> tile size = 15 * cell_size meters.
# Match outer tile size so the scene grid stays consistent.
tile_m = 15 * new_cell
self.scene.terrain.terrain_generator.size = (tile_m, tile_m)
print(f"[Go2 PLAY] PLAY_CELL_SIZE={new_cell}m -> tile={tile_m}m, "
f"corridor ~{new_cell * 0.6:.2f}-{new_cell * 0.9:.2f}m")
# PLAY_CLASSIC_MAZE=1: reproduce paper-style mazes with uniform
# rectangular walls and clear corridors (no randomized pillar / bar
# / cross obstacles inserted into the maze pattern). Affects only
# the `maze` sub-terrain since `non_maze` and `pits` rely on the
# randomized shapes for their gameplay.
_classic = os.environ.get("PLAY_CLASSIC_MAZE", "").strip().lower() in ("1", "true", "yes")
if _classic and "maze" in sub_terrains:
sub_terrains["maze"].randomize_wall = False
sub_terrains["maze"].random_wall_ratio = 0.0
print(f"[Go2 PLAY] PLAY_CLASSIC_MAZE=1 -> maze walls are full-height "
f"rectangles (no randomized obstacle shapes)")
self.observations.policy.enable_corruption = False
self.events.base_external_force_torque = None
self.events.push_robot = None
# Visualize the depth-camera ray hits + height scanner grid in the GUI.
# The RayCasterCamera draws a point per ray that hits geometry; the
# density / pattern of these points is the effective FOV / resolution.
self.scene.raycast_camera.debug_vis = True
if self.scene.height_scanner_critic is not None:
self.scene.height_scanner_critic.debug_vis = True
@@ -0,0 +1,172 @@
# Copyright (c) 2022-2025, Fan Yang and Per Frivik, ETH Zurich.
# All rights reserved.
#
# SPDX-License-Identifier: MIT
"""Custom RSL-RL configuration classes for navigation tasks.
These config classes replace the standard Isaac Lab RL configs to support
custom network architectures used in navigation tasks with depth camera inputs.
"""
from dataclasses import MISSING
from typing import Literal, Optional
from isaaclab.utils import configclass
@configclass
class RslRlPpoActorCriticCfg:
"""Configuration for the PPO actor-critic networks with navigation extensions."""
class_name: str = "ActorCritic"
"""The policy class name. Default is ActorCritic."""
init_noise_std: float = MISSING
"""The initial noise standard deviation for the policy."""
actor_hidden_dims: list[int] = MISSING
"""The hidden dimensions of the actor network."""
critic_hidden_dims: list[int] = MISSING
"""The hidden dimensions of the critic network."""
activation: str = MISSING
"""The activation function for the actor and critic networks."""
rnn_type: str = "lstm"
"""The type of RNN to use."""
rnn_hidden_size: int = 256
"""The hidden size of the RNN."""
rnn_num_layers: int = 1
"""The number of layers in the RNN."""
dropout: float = 0.0
"""The dropout rate for the first layer of the actor and critic networks."""
# Visual inputs
num_cameras: int = 1
"""Number of depth cameras encoded into the observation (1 or 2)."""
image_input_dims: tuple[int, int, int] = (64, 5, 8)
"""Encoded depth feature shape as (C, H, W)."""
height_input_dims: tuple[int, int, int] = (64, 7, 7)
"""Encoded height scan feature shape as (C, H, W). Default is (64, 7, 7) for 64*7*7=3136 features."""
@configclass
class RslRlPpoAlgorithmCfg:
"""Configuration for the PPO algorithm."""
class_name: str = MISSING
"""The algorithm class name. Default is PPO."""
value_loss_coef: float = MISSING
"""The coefficient for the value loss."""
use_clipped_value_loss: bool = MISSING
"""Whether to use clipped value loss."""
clip_param: float = MISSING
"""The clipping parameter for the policy."""
value_clip_param: float = 0.2
"""The value clipping parameter. Default is 0.2."""
entropy_coef: float = MISSING
"""The coefficient for the entropy loss."""
num_learning_epochs: int = MISSING
"""The number of learning epochs per update."""
num_mini_batches: int = MISSING
"""The number of mini-batches per update."""
learning_rate: float = MISSING
"""The learning rate for the policy."""
schedule: str = MISSING
"""The learning rate schedule."""
gamma: float = MISSING
"""The discount factor."""
lam: float = MISSING
"""The lambda parameter for Generalized Advantage Estimation (GAE)."""
desired_kl: float = MISSING
"""The desired KL divergence."""
max_grad_norm: float = MISSING
"""The maximum gradient norm."""
@configclass
class RslRlOnPolicyRunnerCfg:
"""Configuration of the runner for on-policy algorithms."""
seed: Optional[int] = 42
"""The seed for the experiment. Default is 42."""
device: str = "cuda:0"
"""The device for the rl-agent. Default is cuda:0."""
num_steps_per_env: int = MISSING
"""The number of steps per environment per update."""
max_iterations: int = MISSING
"""The maximum number of iterations."""
empirical_normalization: bool = MISSING
"""Whether to use empirical normalization."""
policy: RslRlPpoActorCriticCfg = MISSING
"""The policy configuration."""
algorithm: RslRlPpoAlgorithmCfg = MISSING
"""The algorithm configuration."""
reward_shifting_value: float = 0.0
"""The value to shift the reward by. Default is 0.0."""
##
# Checkpointing parameters
##
save_interval: int = MISSING
"""The number of iterations between saves."""
experiment_name: str = MISSING
"""The experiment name."""
run_name: str = ""
"""The run name. Default is empty string."""
##
# Logging parameters
##
logger: Literal["tensorboard", "neptune", "wandb"] = "tensorboard"
"""The logger to use. Default is tensorboard."""
neptune_project: str = "isaaclab"
"""The neptune project name. Default is "isaaclab"."""
wandb_project: str = "isaaclab"
"""The wandb project name. Default is "isaaclab"."""
##
# Loading parameters
##
resume: bool = False
"""Whether to resume. Default is False."""
load_run: str = ".*"
"""The run directory to load. Default is ".*" (all)."""
load_checkpoint: str = "model_.*.pt"
"""The checkpoint file to load. Default is "model_.*.pt" (all)."""