diff --git a/artifacts/go2-walk-flat.deploy/manifest.json b/artifacts/go2-walk-flat.deploy/manifest.json index 18b3d1d89..be830bc16 100644 --- a/artifacts/go2-walk-flat.deploy/manifest.json +++ b/artifacts/go2-walk-flat.deploy/manifest.json @@ -27,7 +27,7 @@ ] }, "payload_path": "policy/model.onnx", - "sha256": "b3d3aa61f2077502264163e16772d7883e115d949247a7a0ebe8f7fbcb7cdb19" + "sha256": "e7212d9500aa89a51c93031894901dee7a5b708017bdc167a9024a13b821efb7" }, "robot": { "base_link_name": "base", @@ -39,10 +39,10 @@ 0.800000011920929, -1.5, 0.0, - 1.0, + 0.800000011920929, -1.5, 0.0, - 1.0, + 0.800000011920929, -1.5 ], "joint_names": [ @@ -106,7 +106,7 @@ "source": { "checkpoint": "checkpoints/latest.pt", "framework": "rslrl.ppo/torch", - "run_id": "26-10-10_11-48-41-971323" + "run_id": "26-11-26_12-57-18-755832" }, "task": { "config": { @@ -118,10 +118,10 @@ -8.800000190734863, -4.490799903869629, -3.788800001144409, - -9.600000381469727, + -8.800000190734863, -4.490799903869629, -3.788800001144409, - -9.600000381469727, + -8.800000190734863, -4.490799903869629 ], "action_scale": [ @@ -146,16 +146,16 @@ 6.800000190734863, 2.608959913253784, 3.788800001144409, - 6.0, + 6.800000190734863, 2.608959913253784, 3.788800001144409, - 6.0, + 6.800000190734863, 2.608959913253784 ], "command_lower": [ -1.0, -0.5, - -0.5 + -1.0 ], "command_scale": [ 1.0, @@ -165,7 +165,7 @@ "command_upper": [ 1.0, 0.5, - 0.5 + 1.0 ], "feet_phase_offsets": [ 0.0, @@ -174,6 +174,16 @@ 0.0 ], "gait_frequency_hz": 2.0, + "gait_schedule_enabled": true, + "gait_schedule_frequency_high": 2.14, + "gait_schedule_frequency_low": 1.05, + "gait_schedule_lateral_weight": 1.0, + "gait_schedule_smoothing_time_s": 0.6, + "gait_schedule_speed_high": 0.8, + "gait_schedule_speed_low": 0.2, + "gait_schedule_swing_fraction_high": 0.5, + "gait_schedule_swing_fraction_low": 0.368, + "gait_schedule_yaw_weight": 0.8, "kd": [ 0.5, 0.5, diff --git a/artifacts/go2-walk-flat.deploy/policy/model.onnx b/artifacts/go2-walk-flat.deploy/policy/model.onnx index 789064c59..fccfcbf7c 100644 Binary files a/artifacts/go2-walk-flat.deploy/policy/model.onnx and b/artifacts/go2-walk-flat.deploy/policy/model.onnx differ diff --git a/configs/task/go2-walk-flat/rslrl.ppo.yaml b/configs/task/go2-walk-flat/rslrl.ppo.yaml index 921a14499..686b10775 100644 --- a/configs/task/go2-walk-flat/rslrl.ppo.yaml +++ b/configs/task/go2-walk-flat/rslrl.ppo.yaml @@ -14,7 +14,7 @@ seed: 1 checkpoint: interval: 100 algo: - max_iterations: 1000 + max_iterations: 2000 obs_groups: actor: - policy diff --git a/motrix_deploy_tasks/src/motrix_deploy_tasks/tasks/go2_walk.py b/motrix_deploy_tasks/src/motrix_deploy_tasks/tasks/go2_walk.py index 415ddcd58..19c36a3eb 100644 --- a/motrix_deploy_tasks/src/motrix_deploy_tasks/tasks/go2_walk.py +++ b/motrix_deploy_tasks/src/motrix_deploy_tasks/tasks/go2_walk.py @@ -73,6 +73,21 @@ class Go2WalkTaskSpec(TaskSpec): command_scale: CommandScale feet_phase_offsets: FeetPhaseOffsets gait_frequency_hz: PositiveFloat + # Older hand-built specs remain fixed-frequency unless the compiled + # environment profile explicitly opts into the measured schedule. + gait_schedule_enabled: bool = False + gait_schedule_speed_low: NonNegativeFloat = 0.2 + gait_schedule_speed_high: PositiveFloat = 0.8 + gait_schedule_frequency_low: PositiveFloat = 1.05 + gait_schedule_frequency_high: PositiveFloat = 2.14 + gait_schedule_swing_fraction_low: Annotated[FiniteFloat, Field(gt=0, lt=1)] = 0.368 + gait_schedule_swing_fraction_high: Annotated[FiniteFloat, Field(gt=0, lt=1)] = 0.536 + gait_schedule_smoothing_time_s: PositiveFloat = 0.35 + # Legacy artifacts did not serialize this field and were trained with 0.5. + gait_schedule_yaw_weight: NonNegativeFloat = 0.5 + # Legacy artifacts did not serialize this field and omit lateral speed + # from the schedule, matching their original fixed behavior. + gait_schedule_lateral_weight: NonNegativeFloat = 0.0 standing_threshold: NonNegativeFloat termination_min_up_z: Annotated[FiniteFloat, Field(ge=-1, le=1)] @@ -112,10 +127,21 @@ def __init__(self, spec: Go2WalkTaskSpec, robot: RobotSpec) -> None: self._command_scale = np.asarray(spec.command_scale, dtype=np.float32) self._feet_phase_offsets = np.asarray(spec.feet_phase_offsets, dtype=np.float32) self._gait_frequency_hz = spec.gait_frequency_hz + self._gait_schedule_enabled = spec.gait_schedule_enabled + self._gait_schedule_speed_low = spec.gait_schedule_speed_low + self._gait_schedule_speed_high = spec.gait_schedule_speed_high + self._gait_schedule_frequency_low = spec.gait_schedule_frequency_low + self._gait_schedule_frequency_high = spec.gait_schedule_frequency_high + self._gait_schedule_swing_fraction_low = spec.gait_schedule_swing_fraction_low + self._gait_schedule_swing_fraction_high = spec.gait_schedule_swing_fraction_high + self._gait_schedule_smoothing_time_s = spec.gait_schedule_smoothing_time_s + self._gait_schedule_yaw_weight = spec.gait_schedule_yaw_weight + self._gait_schedule_lateral_weight = spec.gait_schedule_lateral_weight self._standing_threshold = spec.standing_threshold self._termination_min_up_z = spec.termination_min_up_z self._previous_action: FloatArray = np.zeros(self.robot.joint_count, dtype=np.float32) self._phase = np.float32(0.0) + self._gait_schedule_alpha = np.float32(0.0) @property def command_lower(self) -> FloatArray: @@ -136,16 +162,46 @@ def reset(self, state: RobotState, context: ControlContext[PlanarVelocityCommand """Reset action and gait history; callers provide validated state and command.""" self._previous_action.fill(0) self._phase = np.float32(0.0) + self._gait_schedule_alpha = np.float32(0.0) def build_observation(self, state: RobotState, context: ControlContext[PlanarVelocityCommand]) -> FloatArray: """Consume runtime-validated state and PolicyController-validated input commands.""" velocity = context.command.values[0, :].numpy() phase = np.zeros(4, dtype=np.float32) - if np.linalg.norm(velocity) < self._standing_threshold: - self._phase = np.float32(0.0) - elif context.step > 0: - self._phase = np.float32((self._phase + context.dt_s * self._gait_frequency_hz) % 1.0) + if context.step > 0: + if self._gait_schedule_enabled: + # Match training: forward speed anchors the measured gait; + # lateral and yaw use artifact-specified equivalent speeds. + speed = max( + abs(float(velocity[0])), + self._gait_schedule_lateral_weight * abs(float(velocity[1])), + self._gait_schedule_yaw_weight * abs(float(velocity[2])), + ) + target_alpha = float( + np.clip( + (speed - self._gait_schedule_speed_low) + / (self._gait_schedule_speed_high - self._gait_schedule_speed_low), + 0.0, + 1.0, + ) + ) + alpha_rate = context.dt_s / self._gait_schedule_smoothing_time_s + delta = target_alpha - self._gait_schedule_alpha + self._gait_schedule_alpha = np.float32( + self._gait_schedule_alpha + np.sign(delta) * min(abs(delta), alpha_rate) + ) + frequency = self._gait_schedule_frequency_low + self._gait_schedule_alpha * ( + self._gait_schedule_frequency_high - self._gait_schedule_frequency_low + ) + else: + frequency = self._gait_frequency_hz + if np.linalg.norm(velocity) < self._standing_threshold: + self._phase = np.float32(0.0) + else: + self._phase = np.float32((self._phase + context.dt_s * frequency) % 1.0) phase = np.mod(self._phase + self._feet_phase_offsets, 1.0).astype(np.float32) + if np.linalg.norm(velocity) < self._standing_threshold: + phase[:] = 0.0 observation = np.concatenate( ( state.base_angular_velocity, diff --git a/motrix_deploy_tasks/tests/test_go2_walk.py b/motrix_deploy_tasks/tests/test_go2_walk.py index 24ebfa7d3..91e17f20f 100644 --- a/motrix_deploy_tasks/tests/test_go2_walk.py +++ b/motrix_deploy_tasks/tests/test_go2_walk.py @@ -599,7 +599,7 @@ def test_previous_action_and_trot_phase_advance_after_first_tick() -> None: np.testing.assert_allclose(observation[45:49], [0.04, 0.54, 0.54, 0.04]) -def test_gait_phase_restarts_after_standing_and_reset() -> None: +def test_gait_phase_starts_from_full_support_after_standing_and_reset() -> None: robot = _robot() state = _state(robot) task = Go2WalkPolicyProcessor(_task_spec(), robot) @@ -607,18 +607,19 @@ def test_gait_phase_restarts_after_standing_and_reset() -> None: standing = [0.0, 0.0, 0.0] task.reset(state, _context(0, 0.0, moving)) - phases = [ - task.build_observation(state, _context(step, step * 0.02, command))[45:49] - for step, command in enumerate((moving, moving, standing, standing, moving, moving)) - ] - np.testing.assert_allclose(phases[0], 0.0) - np.testing.assert_allclose(phases[1], [0.04, 0.54, 0.54, 0.04]) - np.testing.assert_allclose(phases[2:4], 0.0) - np.testing.assert_allclose(phases[4], phases[1]) - np.testing.assert_allclose(phases[5], [0.08, 0.58, 0.58, 0.08]) + first = task.build_observation(state, _context(0, 0.0, moving))[45:49] + second = task.build_observation(state, _context(1, 0.02, moving))[45:49] + stand = task.build_observation(state, _context(2, 0.04, standing))[45:49] + resumed = task.build_observation(state, _context(3, 0.06, moving))[45:49] + + np.testing.assert_allclose(first, 0.0) + np.testing.assert_allclose(second, [0.04, 0.54, 0.54, 0.04]) + np.testing.assert_allclose(stand, 0.0) + # Stand and walk share phase zero so startup begins from full support. + np.testing.assert_allclose(resumed, [0.04, 0.54, 0.54, 0.04]) task.reset(state, _context(0, 0.0, moving)) - np.testing.assert_allclose(task.build_observation(state, _context(1, 0.02, moving))[45:49], phases[1]) + np.testing.assert_allclose(task.build_observation(state, _context(1, 0.02, moving))[45:49], second) def test_standing_command_freezes_deployment_gait_phase() -> None: diff --git a/motrix_deploy_tasks/tests/test_training_parity.py b/motrix_deploy_tasks/tests/test_training_parity.py index 09e292d01..17edf22fd 100644 --- a/motrix_deploy_tasks/tests/test_training_parity.py +++ b/motrix_deploy_tasks/tests/test_training_parity.py @@ -7,6 +7,7 @@ import numpy as np import pytest +import torch import motrix_deploy_tasks from motrix_deploy.contracts import RobotState @@ -79,8 +80,8 @@ def test_go2_gait_phase_matches_training_across_standing_and_restart(env_name: s env.initialize() probe = _make_env_probe(env) task = Go2WalkPolicyProcessor(profile.task, profile.robot) - moving = np.array([[0.2, 0.0, 0.0]], dtype=np.float32) - standing = np.zeros((1, 3), dtype=np.float32) + moving = torch.tensor([[0.2, 0.0, 0.0]], dtype=torch.float32) + standing = torch.zeros((1, 3), dtype=torch.float32) env._commands[:] = moving task.reset( _robot_state_from_env(env, env.state, probe), @@ -150,9 +151,9 @@ def _robot_state_from_env(env, state, probe) -> RobotState: return RobotState( sample_time_ns=int(state.episode_steps[0]) * 20_000_000, receive_time_ns=0, - joint_position=env.get_dof_pos()[0], - joint_velocity=env.get_dof_vel()[0], - base_orientation_xyzw=imu_quat, - base_angular_velocity=env.get_gyro()[0], + joint_position=env.get_dof_pos()[0].numpy(), + joint_velocity=env.get_dof_vel()[0].numpy(), + base_orientation_xyzw=imu_quat.numpy(), + base_angular_velocity=env.get_gyro()[0].numpy(), base_linear_acceleration=np.zeros(3, dtype=np.float32), ) diff --git a/motrix_envs/src/motrix_envs/deploy/go2_walk.py b/motrix_envs/src/motrix_envs/deploy/go2_walk.py index 788a2ac69..8e44dbad3 100644 --- a/motrix_envs/src/motrix_envs/deploy/go2_walk.py +++ b/motrix_envs/src/motrix_envs/deploy/go2_walk.py @@ -58,6 +58,16 @@ def build_go2_walk_profile(env_name: str) -> DeploymentProfile: command_scale=GO2_COMMAND_SCALES[env_name].tolist(), feet_phase_offsets=feet_offsets.tolist(), gait_frequency_hz=env_cfg.gait_frequency, + gait_schedule_enabled=env_cfg.gait_schedule_enabled, + gait_schedule_speed_low=env_cfg.gait_schedule_speed_low, + gait_schedule_speed_high=env_cfg.gait_schedule_speed_high, + gait_schedule_frequency_low=env_cfg.gait_schedule_frequency_low, + gait_schedule_frequency_high=env_cfg.gait_schedule_frequency_high, + gait_schedule_swing_fraction_low=env_cfg.gait_schedule_swing_fraction_low, + gait_schedule_swing_fraction_high=env_cfg.gait_schedule_swing_fraction_high, + gait_schedule_smoothing_time_s=env_cfg.gait_schedule_smoothing_time_s, + gait_schedule_yaw_weight=env_cfg.gait_schedule_yaw_weight, + gait_schedule_lateral_weight=env_cfg.gait_schedule_lateral_weight, standing_threshold=env_cfg.commands.velocity.standing_threshold, # Match training's orientation-only fall termination. termination_min_up_z=env_cfg.termination_min_up_z, diff --git a/motrix_envs/src/motrix_envs/locomotion/quadruped/cfg.py b/motrix_envs/src/motrix_envs/locomotion/quadruped/cfg.py index ec2e825ea..7c888032d 100644 --- a/motrix_envs/src/motrix_envs/locomotion/quadruped/cfg.py +++ b/motrix_envs/src/motrix_envs/locomotion/quadruped/cfg.py @@ -103,6 +103,7 @@ class QuadrupedWalkRandomizationCfg: kp_scale_range: tuple[float, float] = (1.0, 1.0) damping_scale_range: tuple[float, float] = (1.0, 1.0) sliding_friction_range: tuple[float, float] | None = None + sliding_friction_high_traction_sampling: bool = False base_mass_scale_range: tuple[float, float] = (1.0, 1.0) base_com_offset_noise: tuple[float, float, float] = (0.0, 0.0, 0.0) @@ -160,10 +161,43 @@ class VelocityCommandCfg: lower: NDArray[np.float32] = np.array([0.5, 0.0, 0.0], dtype=np.float32) upper: NDArray[np.float32] = np.array([0.5, 0.0, 0.0], dtype=np.float32) standing_probability: float = 0.0 + hard_case_probability: float = 0.0 + hard_cases: tuple[tuple[float, float, float], ...] = () + # Optional linear curriculum for hard-case command sampling. Each point + # is ``(training_iteration, probability)``; probabilities are linearly + # interpolated between points and held at the nearest endpoint outside + # the specified range. + hard_case_curriculum: tuple[tuple[int, float], ...] = () + hard_case_curriculum_steps_per_iteration: int = 24 standing_threshold: float = 0.05 resampling_seconds_range: tuple[float, float] | None = None def validate(self) -> None: + for name in ("standing_probability", "hard_case_probability"): + probability = getattr(self, name) + if not np.isfinite(probability) or not 0.0 <= probability <= 1.0: + raise ValueError(f"{name} must be finite and inside [0, 1], got {probability}") + if self.hard_case_probability > 0.0 and not self.hard_cases: + raise ValueError("hard_case_probability requires at least one hard case") + for hard_case in self.hard_cases: + if len(hard_case) != 3 or not np.all(np.isfinite(hard_case)): + raise ValueError(f"hard case must contain three finite values, got {hard_case}") + if self.hard_case_curriculum_steps_per_iteration <= 0: + raise ValueError("hard_case_curriculum_steps_per_iteration must be positive") + previous_iteration = -1 + for point in self.hard_case_curriculum: + if len(point) != 2: + raise ValueError(f"hard-case curriculum point must be (iteration, probability), got {point}") + iteration, probability = point + if isinstance(iteration, bool) or not isinstance(iteration, int) or iteration < 0: + raise ValueError(f"hard-case curriculum iteration must be a non-negative integer, got {iteration}") + if iteration <= previous_iteration: + raise ValueError("hard-case curriculum iterations must be strictly increasing") + if not np.isfinite(probability) or not 0.0 <= probability <= 1.0: + raise ValueError(f"hard-case curriculum probability must be inside [0, 1], got {probability}") + previous_iteration = iteration + if self.hard_case_curriculum and not self.hard_cases: + raise ValueError("hard_case_curriculum requires at least one hard case") if self.resampling_seconds_range is not None: low, high = self.resampling_seconds_range if not np.isfinite(low) or not np.isfinite(high) or low <= 0.0 or low > high: @@ -196,18 +230,45 @@ class RewardScales: base_height: float = -100.0 action_rate: float = -0.1 similar_to_default: float = -0.1 + feet_spacing: float = 0.0 contact: float = 0.24 swing_feet_z: float = 2.0 swing_contact: float = -1.0 + touchdown_velocity: float = 0.0 + # Optional posture/smoothness terms. They remain disabled for the + # existing quadruped baselines unless a robot config opts in explicitly. + flat_orientation: float = 0.0 + dof_acc: float = 0.0 + hip_position: float = 0.0 + base_com_position: float = 0.0 @configclass class RewardConfig: scales: RewardScales = RewardScales() tracking_lin_vel_sigma: float = 0.25 + tracking_lin_vel_forward_sigma: float | None = None + tracking_lin_vel_lateral_sigma: float | None = None + standing_similar_to_default_gain: float = 1.0 + swing_contact_slip_penalty: bool = False + swing_contact_forward_scale: float | None = None tracking_ang_vel_sigma: float = 0.25 target_foot_height: float = 0.1 swing_feet_height_sigma: float = 0.05 + swing_fraction: float = 0.4 + swing_feet_z_sinusoidal: bool = False + swing_rise_fraction: float = 0.2 + swing_plateau_fraction: float = 0.2 + foot_height_reference_offset: float = 0.0 + touchdown_height_threshold: float = 0.03 + touchdown_speed_sigma: float = 0.5 + touchdown_speed_clip: float = 3.0 + feet_spacing_tolerance: float = 0.01 + feet_spacing_sigma: float = 0.03 + hip_position_tolerance: float = 0.05 + hip_position_sigma: float = 0.05 + base_com_position_tolerance: float = 0.02 + base_com_position_sigma: float = 0.05 base_height_target: float = 0.3 @@ -229,6 +290,19 @@ class QuadrupedWalkEnvCfg(DirectEnvCfg): spawn_xy_range: float = 0.0 trot_pairs: tuple[tuple[int, int], ...] = ((0, 3), (1, 2)) gait_frequency: float = 2.0 + # Measured Go2 gait anchors. The runtime interpolates between these + # points as planar command speed changes; ``gait_frequency`` remains the + # legacy fallback/default for callers that do not opt into scheduling. + gait_schedule_enabled: bool = False + gait_schedule_speed_low: float = 0.2 + gait_schedule_speed_high: float = 0.8 + gait_schedule_frequency_low: float = 1.05 + gait_schedule_frequency_high: float = 2.14 + gait_schedule_swing_fraction_low: float = 0.368 + gait_schedule_swing_fraction_high: float = 0.500 + gait_schedule_smoothing_time_s: float = 0.60 + gait_schedule_yaw_weight: float = 0.80 + gait_schedule_lateral_weight: float = 1.00 # Shared by training and the compiled deployment task, not backend recipes. termination_min_up_z: float = 0.5 sim: SimCfg = SimCfg(dt=0.01, solver_iterations=1) @@ -240,6 +314,12 @@ def validate(self) -> None: self.commands.velocity.validate() if not np.isfinite(self.termination_min_up_z) or not -1.0 <= self.termination_min_up_z <= 1.0: raise ValueError("termination_min_up_z must be finite and inside [-1, 1]") + if not np.isfinite(self.gait_schedule_smoothing_time_s) or self.gait_schedule_smoothing_time_s <= 0.0: + raise ValueError("gait_schedule_smoothing_time_s must be finite and positive") + if not np.isfinite(self.gait_schedule_yaw_weight) or self.gait_schedule_yaw_weight < 0.0: + raise ValueError("gait_schedule_yaw_weight must be finite and non-negative") + if not np.isfinite(self.gait_schedule_lateral_weight) or self.gait_schedule_lateral_weight < 0.0: + raise ValueError("gait_schedule_lateral_weight must be finite and non-negative") if ( self.randomization.enabled and any(self.randomization.action_delay_steps) @@ -255,7 +335,12 @@ def for_play(self) -> "QuadrupedWalkEnvCfg": randomization=replace(self.randomization, enabled=False), commands=replace( self.commands, - velocity=replace(self.commands.velocity, resampling_seconds_range=None), + velocity=replace( + self.commands.velocity, + resampling_seconds_range=None, + hard_case_probability=0.0, + hard_case_curriculum=(), + ), ), ) diff --git a/motrix_envs/src/motrix_envs/locomotion/quadruped/go2.py b/motrix_envs/src/motrix_envs/locomotion/quadruped/go2.py index 0d5c3ad4b..eec9e21e3 100644 --- a/motrix_envs/src/motrix_envs/locomotion/quadruped/go2.py +++ b/motrix_envs/src/motrix_envs/locomotion/quadruped/go2.py @@ -35,11 +35,45 @@ class Go2WalkDirectEnvCfg(QuadrupedWalkEnvCfg): render_spacing: float = 0.0 spawn_xy_range: float = 4.0 + gait_schedule_enabled: bool = True commands: Commands = Commands( velocity=VelocityCommandCfg( - lower=np.array([-1.0, -0.5, -0.5], dtype=np.float32), - upper=np.array([1.0, 0.5, 0.5], dtype=np.float32), - standing_probability=0.1, + lower=np.array([-1.0, -0.5, -1.0], dtype=np.float32), + upper=np.array([1.0, 0.5, 1.0], dtype=np.float32), + standing_probability=0.50, + hard_case_probability=0.20, + hard_cases=( + (0.0, 0.4, 0.0), + (0.0, -0.4, 0.0), + (0.0, 0.5, 0.0), + (0.0, -0.5, 0.0), + (0.8, 0.4, 0.0), + (0.8, -0.4, 0.0), + (-0.8, 0.4, 0.0), + (-0.8, -0.4, 0.0), + (1.0, 0.0, 0.0), + (1.0, 0.5, 0.0), + (1.0, -0.5, 0.0), + (-1.0, 0.0, 0.0), + (0.0, 0.0, 1.0), + (0.0, 0.0, -1.0), + (-1.0, 0.5, 0.0), + (-1.0, -0.5, 0.0), + (0.8, 0.4, 0.8), + (0.8, 0.4, -0.8), + (0.8, -0.4, 0.8), + (0.8, -0.4, -0.8), + (-0.8, 0.4, 0.8), + (-0.8, 0.4, -0.8), + (-0.8, -0.4, 0.8), + (-0.8, -0.4, -0.8), + (0.0, 0.0, 0.5), + (0.0, 0.0, -0.5), + (0.0, 0.0, 0.8), + (0.0, 0.0, -0.8), + ), + hard_case_curriculum=((0, 0.0), (200, 0.0), (450, 0.08), (700, 0.20), (900, 0.20), (2000, 0.20)), + hard_case_curriculum_steps_per_iteration=24, resampling_seconds_range=(5.0, 10.0), ) ) @@ -52,7 +86,8 @@ class Go2WalkDirectEnvCfg(QuadrupedWalkEnvCfg): action_delay_steps=(0, 1), kp_scale_range=(0.9, 1.1), damping_scale_range=(0.9, 1.1), - sliding_friction_range=(0.4, 0.9), + sliding_friction_range=(0.6, 1.4), + sliding_friction_high_traction_sampling=True, base_mass_scale_range=(0.9, 1.1), base_com_offset_noise=(0.01, 0.01, 0.005), ) @@ -68,11 +103,43 @@ class Go2WalkDirectEnvCfg(QuadrupedWalkEnvCfg): reward_config: RewardConfig = RewardConfig( scales=RewardScales( - similar_to_default=-1, + tracking_lin_vel=4.5, + feet_spacing=0.5, + tracking_ang_vel=1.6, + action_rate=-0.12, + dof_acc=-2e-5, + ang_vel_xy=-0.5, + flat_orientation=-4.0, + swing_feet_z=6.0, + swing_contact=-1.5, + touchdown_velocity=-0.8, + similar_to_default=-0.1, + hip_position=-1.0, + base_com_position=-0.5, + base_height=-300.0, ), + tracking_lin_vel_sigma=0.35, + tracking_lin_vel_forward_sigma=0.16, + tracking_lin_vel_lateral_sigma=0.25, + standing_similar_to_default_gain=5.0, + swing_contact_slip_penalty=True, + swing_contact_forward_scale=1.5, tracking_ang_vel_sigma=0.05, - target_foot_height=0.05, - base_height_target=0.35, + target_foot_height=0.09, + swing_fraction=0.45, + swing_feet_z_sinusoidal=True, + swing_feet_height_sigma=0.05, + foot_height_reference_offset=0.04232, + swing_rise_fraction=0.35, + swing_plateau_fraction=0.30, + touchdown_height_threshold=0.03, + touchdown_speed_sigma=0.35, + touchdown_speed_clip=3.0, + feet_spacing_tolerance=0.03, + feet_spacing_sigma=0.03, + hip_position_tolerance=0.08, + hip_position_sigma=0.08, + base_height_target=0.305, ) def for_play(self) -> "Go2WalkDirectEnvCfg": @@ -90,6 +157,23 @@ class Go2WalkRoughDirectEnvCfg(Go2WalkDirectEnvCfg): zh_CN: 控制 Unitree Go2 在程序化粗糙高度场上跟踪行走指令。 """ + # Keep rough on the upstream fixed-frequency gait and randomization while + # the flat task opts into the tuned schedule. + gait_schedule_enabled: bool = False + randomization: QuadrupedWalkRandomizationCfg = QuadrupedWalkRandomizationCfg( + enabled=True, + joint_pos_noise=0.03, + joint_vel_noise=0.1, + base_lin_vel_noise=(0.1, 0.1, 0.0), + base_ang_vel_noise=(0.1, 0.1, 0.1), + action_delay_steps=(0, 1), + kp_scale_range=(0.9, 1.1), + damping_scale_range=(0.9, 1.1), + sliding_friction_range=(0.4, 0.9), + base_mass_scale_range=(0.9, 1.1), + base_com_offset_noise=(0.01, 0.01, 0.005), + ) + commands: Commands = Commands( velocity=VelocityCommandCfg( lower=np.array([-0.5, -0.4, -1.0], dtype=np.float32), diff --git a/motrix_envs/src/motrix_envs/locomotion/quadruped/velocity_command.py b/motrix_envs/src/motrix_envs/locomotion/quadruped/velocity_command.py index 02e7ab5ba..d66602139 100644 --- a/motrix_envs/src/motrix_envs/locomotion/quadruped/velocity_command.py +++ b/motrix_envs/src/motrix_envs/locomotion/quadruped/velocity_command.py @@ -3,6 +3,7 @@ """Task-specific random planar-velocity command binding for quadruped training.""" +import numpy as np import torch from motrix_env_core.input import CommandBinding, PlanarVelocityCommand @@ -18,19 +19,44 @@ def __init__( *, rng: torch.Generator, standing_probability: float = 0.0, + hard_case_probability: float = 0.0, + hard_cases: tuple[tuple[float, float, float], ...] = (), ) -> None: self._lower = lower self._upper = upper self._standing_probability = standing_probability + self._hard_case_probability = hard_case_probability + self._hard_cases = torch.as_tensor(hard_cases, dtype=torch.float32) self._rng = rng + if hard_case_probability > 0.0 and not hard_cases: + raise ValueError("hard_case_probability requires at least one hard case") + if len(self._hard_cases) and (torch.any(self._hard_cases < lower) or torch.any(self._hard_cases > upper)): + raise ValueError("hard-case commands must lie inside the configured velocity bounds") + def read_command(self, *, batch_size: int = 1) -> PlanarVelocityCommand: u = torch.rand((batch_size, 3), generator=self._rng) values = self._lower + (self._upper - self._lower) * u + if self._hard_case_probability > 0.0: + hard = torch.rand((batch_size,), generator=self._rng) < self._hard_case_probability + choices = torch.randint(self._hard_cases.shape[0], (batch_size,), generator=self._rng) + values[hard] = self._hard_cases[choices[hard]] if self._standing_probability > 0.0: standing = torch.rand((batch_size,), generator=self._rng) < self._standing_probability values[standing] = 0.0 return PlanarVelocityCommand(values) + @property + def hard_case_probability(self) -> float: + return self._hard_case_probability + + def set_hard_case_probability(self, probability: float) -> None: + """Update the hard-case sampling probability for a training curriculum.""" + if not np.isfinite(probability) or not 0.0 <= probability <= 1.0: + raise ValueError(f"hard-case probability must be inside [0, 1], got {probability}") + if probability > 0.0 and not len(self._hard_cases): + raise ValueError("hard-case probability requires at least one hard case") + self._hard_case_probability = float(probability) + __all__ = ["RandomPlanarVelocityBinding"] diff --git a/motrix_envs/src/motrix_envs/locomotion/quadruped/walk_np.py b/motrix_envs/src/motrix_envs/locomotion/quadruped/walk_np.py index 2c478937b..ce97f9d38 100644 --- a/motrix_envs/src/motrix_envs/locomotion/quadruped/walk_np.py +++ b/motrix_envs/src/motrix_envs/locomotion/quadruped/walk_np.py @@ -27,6 +27,7 @@ BodyRotationWrite, DofVelocityQuery, GeomFrictionQuery, + GeomPositionQuery, LinkCenterOfMassQuery, LinkMassQuery, LinkPositionQuery, @@ -61,7 +62,7 @@ def _sim_data_queries(cfg: QuadrupedWalkEnvCfg): def resolve_sensor_name(name: str) -> str: return name if name in scene_sensor_names else robot.resolve_name(name) - return { + queries = { "joint_dof_pos": BodyJointPositionQuery(body=base_link_name), "joint_dof_vel": BodyJointVelocityQuery(body=base_link_name), "dof_vel": DofVelocityQuery(), @@ -79,6 +80,13 @@ def resolve_sensor_name(name: str) -> str: "RL_pos": SensorValuesQuery(sensors=(resolve_sensor_name(cfg.sensor.foot_positions[2]),)), "RR_pos": SensorValuesQuery(sensors=(resolve_sensor_name(cfg.sensor.foot_positions[3]),)), } + if isinstance(robot, QuadrupedRobotCfg): + foot_geom_names = robot.foot_contact_geom_names + for key, geom_name in zip(("FL_world_pos", "FR_world_pos", "RL_world_pos", "RR_world_pos"), foot_geom_names): + if geom_name is None: + raise ValueError("Quadruped walk requires a resolved foot contact geom name") + queries[key] = GeomPositionQuery(geom=geom_name) + return queries def _sim_model_queries(cfg: QuadrupedWalkEnvCfg): @@ -126,6 +134,33 @@ def _resolve_key_pose( class QuadrupedWalkTask(DirectEnv[QuadrupedWalkEnvCfg]): """Base quadruped walk task driven by a :class:`QuadrupedRobotCfg`.""" + # Keep the nominal posture constraints intact for standing and sagittal + # walking, while making them a soft constraint for lateral/yaw commands. + # These are implementation constants rather than user-facing reward + # hyperparameters: the command envelope is already part of the task + # contract and we do not want another tuning surface for this correction. + _POSTURE_GATE_START = 0.1 + _POSTURE_GATE_END = 0.5 + _POSTURE_GATE_FLOOR = 0.40 + + # Static-stance foot anchoring is deliberately kept as implementation + # policy rather than another public reward/configuration knob. The + # deadband filters simulator/contact noise; beyond it, 5 mm corresponds + # to a small but meaningful penalty. The rational barrier approaches the + # existing saturation value 4.0 without becoming flat at a finite error, + # so accumulated creep continues to receive a learning signal. + _STATIC_ANCHOR_DEADBAND = 0.001 + _STATIC_ANCHOR_SATURATION_SCALE = 0.02 + + # Dynamic COM envelope used by the existing base_com_position term. A + # moving quadruped needs a small forward COM shift to accelerate, but the + # allowed shift must remain bounded so the body cannot progressively + # pitch/translate ahead of the stance feet. + # Nominal dynamic-COM envelope used by the earlier regular recipe. Keep + # the default handoff COM as the target while allowing bounded motion. + _DYNAMIC_COM_FORWARD_ALLOWANCE = 0.02 + _DYNAMIC_COM_BACKWARD_ALLOWANCE = 0.025 + def __init__( self, cfg: QuadrupedWalkEnvCfg, @@ -195,6 +230,8 @@ def __init__( torch.as_tensor(velocity_cfg.upper, dtype=torch.float32), rng=self._command_rng, standing_probability=velocity_cfg.standing_probability, + hard_case_probability=velocity_cfg.hard_case_probability, + hard_cases=velocity_cfg.hard_cases, ) if not math.isfinite(velocity_cfg.standing_threshold) or velocity_cfg.standing_threshold < 0.0: raise ValueError( @@ -216,6 +253,10 @@ def __init__( self._init_base_pose = self.model.init_dof_pos[:7].clone() self._init_base_pose[:3] = torch.tensor(cfg.initial_base_position, dtype=torch.float32) self._init_joint_position = self.default_angles.clone() + self._hip_indices = torch.tensor( + [index for index, actuator in enumerate(self.model.actuators) if "hip" in actuator.target_name], + dtype=torch.int64, + ) has_non_position_actuator = any( spec.actuator_type is not ActuatorType.POSITION for spec in self.model.actuators @@ -245,17 +286,31 @@ def __init__( self._randomize_writes = self.sim.write_compiler.compile(randomize_writes) if randomize_writes else None self.feet_contact = torch.zeros((num_envs, self._num_feet), dtype=torch.bool) + self._last_feet_contact = torch.zeros((num_envs, self._num_feet), dtype=torch.bool) self.feet_pos = torch.zeros((num_envs, self._num_feet, 3), dtype=torch.float32) + self._last_feet_pos = torch.zeros_like(self.feet_pos) + self.feet_world_pos = torch.zeros_like(self.feet_pos) + self._last_feet_world_pos = torch.zeros_like(self.feet_world_pos) + self._static_anchor_pos = torch.zeros((num_envs, self._num_feet, 2), dtype=torch.float32) + self._static_anchor_valid = torch.zeros((num_envs, self._num_feet), dtype=torch.bool) + self._last_joint_vel = torch.zeros((num_envs, self._num_action), dtype=torch.float32) + self._default_feet_width: torch.Tensor | None = None + self._default_base_com_forward_offset: torch.Tensor | None = None # Episode-scoped task state: full-batch buffers, reset writes the done # rows in place. self._commands = torch.zeros((num_envs, 3), dtype=torch.float32) self._command_resampling_time = torch.full((num_envs,), torch.inf, dtype=torch.float32) + self._command_control_steps = 0 self._phase = torch.zeros(num_envs, dtype=torch.float32) self._feet_phase = torch.zeros((num_envs, self._num_feet), dtype=torch.float32) + self._gait_schedule_alpha = torch.zeros(num_envs, dtype=torch.float32) + self._gait_frequency = torch.full((num_envs,), float(cfg.gait_frequency), dtype=torch.float32) + self._swing_fraction = torch.full((num_envs,), float(cfg.reward_config.swing_fraction), dtype=torch.float32) self._current_actions = torch.zeros((num_envs, self._num_action), dtype=torch.float32) self._last_actions = torch.zeros((num_envs, self._num_action), dtype=torch.float32) self._action_delay_steps = torch.zeros(num_envs, dtype=torch.int64) + self._set_hard_case_probability(0) # ---- obs/action space plumbing ---------------------------------------- @@ -331,22 +386,57 @@ def _read_feet_contact(self, env_ids: torch.Tensor | None = None) -> torch.Tenso def _update_feet_buffers(self, env_ids: torch.Tensor | None = None) -> None: contacts = self._read_feet_contact(env_ids) rows = slice(None) if env_ids is None else env_ids + self._last_feet_contact[rows, :] = self.feet_contact[rows, :] self.feet_contact[rows, :] = contacts[rows, :] for i, name in enumerate(self._feet_position_sensors): self.feet_pos[rows, i, :] = self.sim_data[name][rows] + for i, name in enumerate(("FL_world_pos", "FR_world_pos", "RL_world_pos", "RR_world_pos")): + self.feet_world_pos[rows, i, :] = self.sim_data[name][rows] def _advance_phase(self): commands = self._commands + if self.cfg.gait_schedule_enabled: + # Anchor the schedule to the measured forward gaits. Lateral and + # yaw commands map to equivalent sagittal speeds so they do not + # remain trapped in the measured low-speed anchors. + speed = torch.maximum( + torch.maximum( + torch.abs(commands[:, 0]), + float(self.cfg.gait_schedule_lateral_weight) * torch.abs(commands[:, 1]), + ), + float(self.cfg.gait_schedule_yaw_weight) * torch.abs(commands[:, 2]), + ) + speed_low = float(self.cfg.gait_schedule_speed_low) + speed_high = float(self.cfg.gait_schedule_speed_high) + target_alpha = torch.clamp((speed - speed_low) / (speed_high - speed_low), 0.0, 1.0) + alpha_rate = self.cfg.ctrl_dt / float(self.cfg.gait_schedule_smoothing_time_s) + delta = target_alpha - self._gait_schedule_alpha + self._gait_schedule_alpha += torch.sign(delta) * torch.clamp(torch.abs(delta), max=alpha_rate) + self._gait_frequency[:] = float(self.cfg.gait_schedule_frequency_low) + self._gait_schedule_alpha * ( + float(self.cfg.gait_schedule_frequency_high) - float(self.cfg.gait_schedule_frequency_low) + ) + self._swing_fraction[:] = float(self.cfg.gait_schedule_swing_fraction_low) + self._gait_schedule_alpha * ( + float(self.cfg.gait_schedule_swing_fraction_high) - float(self.cfg.gait_schedule_swing_fraction_low) + ) + else: + self._gait_schedule_alpha.zero_() + self._gait_frequency.fill_(float(self.cfg.gait_frequency)) + self._swing_fraction.fill_(float(self.cfg.reward_config.swing_fraction)) + if bool(torch.any((self._swing_fraction <= 0.0) | (self._swing_fraction >= 1.0))): + raise ValueError("scheduled swing fraction must lie strictly inside (0, 1)") + standing = torch.linalg.vector_norm(commands, dim=1) < self.cfg.commands.velocity.standing_threshold phase = self._phase - phase[:] = torch.remainder(phase + self.cfg.ctrl_dt * self.cfg.gait_frequency, 1.0) + phase[:] = torch.remainder(phase + self.cfg.ctrl_dt * self._gait_frequency, 1.0) + # Stand and walk share phase zero. Advancing a hidden clock while the + # observed phase is masked makes the first moving observation jump to an + # arbitrary leg phase; freezing both keeps starts in full support. phase[standing] = 0.0 feet_phase = self._feet_phase # Each trot pair swings together; pair ``n`` is offset by half a cycle # relative to pair ``n-1``. for pair_idx, (i, j) in enumerate(self.cfg.trot_pairs): - offset = 0.5 * pair_idx - value = torch.remainder(phase + offset, 1.0) + value = torch.remainder(phase + 0.5 * pair_idx, 1.0) feet_phase[:, i] = value feet_phase[:, j] = value feet_phase[standing] = 0.0 @@ -405,12 +495,19 @@ def compute_observation(self, state: ArrayEnvState) -> None: def compute_transition(self, state: ArrayEnvState) -> None: self.sim_data.execute() + self._command_control_steps += 1 + self._set_hard_case_probability( + self._command_control_steps // self.cfg.commands.velocity.hard_case_curriculum_steps_per_iteration + ) self._update_commands() self._advance_phase() self._update_feet_buffers() terminated = self.get_gravity()[:, 2] <= self.cfg.termination_min_up_z reward = self._compute_reward(state, self.get_local_linvel(), self.get_gyro(), self.get_dof_pos()) + self._last_feet_pos.copy_(self.feet_pos) + self._last_feet_world_pos.copy_(self.feet_world_pos) + self._last_joint_vel.copy_(self.get_dof_vel()) state.reward.copy_(reward) state.terminated.copy_(terminated) @@ -427,9 +524,15 @@ def _compute_reward( "base_height": self._reward_base_height, "action_rate": self._reward_action_rate, "similar_to_default": self._reward_similar_to_default, + "feet_spacing": self._reward_feet_spacing, "contact": self._reward_contact, "swing_feet_z": self._reward_swing_feet_z, "swing_contact": self._reward_swing_contact, + "touchdown_velocity": self._reward_touchdown_velocity, + "flat_orientation": self._reward_flat_orientation, + "dof_acc": self._reward_dof_acc, + "hip_position": self._reward_hip_position, + "base_com_position": self._reward_base_com_position, } reward_items = {} for name, reward_fn in reward_fns.items(): @@ -446,6 +549,11 @@ def _compute_reward( def reset(self, env_ids: torch.Tensor) -> None: num_reset = env_ids.numel() + if self._default_feet_width is None and ( + self.cfg.reward_config.scales.feet_spacing != 0.0 or self.cfg.reward_config.scales.base_com_position != 0.0 + ): + self._capture_default_feet_width(env_ids) + base_pose = self._init_base_pose.repeat(num_reset, 1) base_linear_velocity = torch.zeros((num_reset, 3), dtype=torch.float32) base_angular_velocity = torch.zeros((num_reset, 3), dtype=torch.float32) @@ -475,15 +583,78 @@ def reset(self, env_ids: torch.Tensor) -> None: self._randomize_params(env_ids) self.sim_data.execute(env_ids) + self._last_feet_contact[env_ids] = False + self.feet_contact[env_ids] = False + self._static_anchor_valid[env_ids] = False self._update_feet_buffers(env_ids) + self._last_feet_pos[env_ids] = self.feet_pos[env_ids] + self._last_feet_world_pos[env_ids] = self.feet_world_pos[env_ids] + self._last_joint_vel[env_ids] = self.get_dof_vel()[env_ids] - self._commands[env_ids] = torch.as_tensor(self.resample_commands(num_reset)) + self._commands[env_ids] = torch.as_tensor(self.resample_commands(num_reset), dtype=torch.float32) self._command_resampling_time[env_ids] = self._sample_command_resampling_time(num_reset) self._phase[env_ids] = 0.0 self._feet_phase[env_ids] = 0.0 + self._gait_schedule_alpha[env_ids] = 0.0 + if self.cfg.gait_schedule_enabled: + self._gait_frequency[env_ids] = float(self.cfg.gait_schedule_frequency_low) + self._swing_fraction[env_ids] = float(self.cfg.gait_schedule_swing_fraction_low) + else: + self._gait_frequency[env_ids] = float(self.cfg.gait_frequency) + self._swing_fraction[env_ids] = float(self.cfg.reward_config.swing_fraction) self._current_actions[env_ids] = 0.0 self._last_actions[env_ids] = 0.0 + def _set_hard_case_probability(self, iteration: int) -> None: + """Apply the configured command curriculum for the current train step.""" + velocity_cfg = self.cfg.commands.velocity + curriculum = velocity_cfg.hard_case_curriculum + if not curriculum: + probability = velocity_cfg.hard_case_probability + elif iteration <= curriculum[0][0]: + probability = curriculum[0][1] + elif iteration >= curriculum[-1][0]: + probability = curriculum[-1][1] + else: + probability = curriculum[-1][1] + for (left_iteration, left_probability), (right_iteration, right_probability) in zip( + curriculum, curriculum[1:] + ): + if left_iteration <= iteration <= right_iteration: + fraction = (iteration - left_iteration) / (right_iteration - left_iteration) + probability = left_probability + fraction * (right_probability - left_probability) + break + self._velocity_command_binding.set_hard_case_probability(probability) + + def _capture_default_feet_width(self, env_ids: torch.Tensor) -> None: + """Read the nominal front and rear foot widths from the default pose.""" + num_reset = env_ids.numel() + base_pose = self._init_base_pose.repeat(num_reset, 1) + joint_position = self._init_joint_position.repeat(num_reset, 1) + joint_velocity = torch.zeros((num_reset, self._reset_joint_velocity.shape[1]), dtype=torch.float32) + + self._reset_position[env_ids] = base_pose[:, :3] + self._reset_rotation[env_ids] = base_pose[:, 3:7] + self._reset_linear_velocity[env_ids] = 0.0 + self._reset_angular_velocity[env_ids] = 0.0 + self._reset_joint_position[env_ids] = joint_position + self._reset_joint_velocity[env_ids] = joint_velocity + self._reset_program.execute(env_ids) + self.sim_data.execute(env_ids) + self._last_feet_contact[env_ids] = False + self.feet_contact[env_ids] = False + self._static_anchor_valid[env_ids] = False + self._update_feet_buffers(env_ids) + self._last_feet_world_pos[env_ids] = self.feet_world_pos[env_ids] + + front_width = self.feet_pos[env_ids, 0, 1] - self.feet_pos[env_ids, 1, 1] + rear_width = self.feet_pos[env_ids, 2, 1] - self.feet_pos[env_ids, 3, 1] + self._default_feet_width = torch.stack([front_width, rear_width], dim=1).mean(dim=0) + base_com_x = float(self.model.others["base_com"][0]) + self._default_base_com_forward_offset = float( + torch.mean(base_com_x - torch.mean(self.feet_pos[env_ids, :, 0], dim=1)) + ) + def resample_commands(self, num_envs: int) -> torch.Tensor: return self._velocity_command_binding.read_command(batch_size=num_envs).values @@ -492,7 +663,7 @@ def _sample_command_resampling_time(self, num_envs: int) -> torch.Tensor: if interval is None: return torch.full((num_envs,), torch.inf, dtype=torch.float32) low, high = interval - return low + torch.rand(num_envs, dtype=torch.float32) * (high - low) + return _torch_uniform(self._command_rng, low, high, (num_envs,)) def _update_commands(self) -> None: if self.cfg.commands.velocity.resampling_seconds_range is None: @@ -502,7 +673,7 @@ def _update_commands(self) -> None: due = remaining <= 0.0 num_due = int(due.sum()) if num_due: - self._commands[due] = torch.as_tensor(self.resample_commands(num_due)) + self._commands[due] = torch.as_tensor(self.resample_commands(num_due), dtype=torch.float32) remaining[due] = self._sample_command_resampling_time(num_due) def _randomize_dof_noise( @@ -571,7 +742,16 @@ def _randomize_params(self, env_ids: torch.Tensor) -> None: program.buffer("damping")[env_ids] = self.model.others["actuator_kd"][None, :] * damping_scale if self._randomize_friction: friction = self.model.others["ground_friction"].repeat(num_reset, 1) - friction[:, 0] = _torch_uniform(rng, *self.cfg.randomization.sliding_friction_range, (num_reset,)) + friction_low, friction_high = self.cfg.randomization.sliding_friction_range + # Keep the configured range unchanged while exposing the policy to + # the high-traction end more often. The square-root transform + # raises the probability of mu >= 1.2 from about 25% to about 45%, + # targeting the forward/reverse failures seen in the audit without + # adding a new reward or randomization field. + friction_u = _torch_uniform(rng, 0.0, 1.0, (num_reset,)) + if self.cfg.randomization.sliding_friction_high_traction_sampling: + friction_u = torch.sqrt(friction_u) + friction[:, 0] = friction_low + (friction_high - friction_low) * friction_u program.buffer("friction")[env_ids, 0] = friction if self._randomize_base_mass: base_mass_scale = _torch_uniform(rng, *self.cfg.randomization.base_mass_scale_range, (num_reset,)) @@ -586,9 +766,25 @@ def _randomize_params(self, env_ids: torch.Tensor) -> None: def _reward_tracking_lin_vel(self, linvel, gyro, dof_pos) -> torch.Tensor: del gyro, dof_pos + reward_cfg = self.cfg.reward_config commands = self._commands - error = torch.sum(torch.square(commands[:, :2] - linvel[:, :2]), dim=1) - return torch.exp(-error / self.cfg.reward_config.tracking_lin_vel_sigma) + error = torch.square(commands[:, :2] - linvel[:, :2]) + sigma = torch.full( + (self._num_envs, 2), + float(reward_cfg.tracking_lin_vel_sigma), + dtype=torch.float32, + ) + forward_sigma = reward_cfg.tracking_lin_vel_forward_sigma + if forward_sigma is not None: + sigma[:, 0] = torch.where( + commands[:, 0] > 0.0, + float(forward_sigma), + float(reward_cfg.tracking_lin_vel_sigma), + ) + lateral_sigma = reward_cfg.tracking_lin_vel_lateral_sigma + if lateral_sigma is not None: + sigma[:, 1] = float(lateral_sigma) + return torch.exp(-torch.sum(error / sigma, dim=1)) def _reward_tracking_ang_vel(self, linvel, gyro, dof_pos) -> torch.Tensor: del linvel, dof_pos @@ -609,7 +805,7 @@ def _reward_base_height(self, linvel, gyro, dof_pos) -> torch.Tensor: base_pos = self.sim_data["base_pos"] env_ids = torch.arange(self._num_envs, dtype=torch.int64) ground_height = self.sim.sample_terrain_height(self.cfg.ground_geom_name, env_ids, base_pos[:, None, :2])[:, 0] - base_height = base_pos[:, 2] - ground_height + base_height = base_pos[:, 2].to(torch.float32) - ground_height return torch.square(base_height - self.cfg.reward_config.base_height_target) def _reward_action_rate(self, linvel, gyro, dof_pos) -> torch.Tensor: @@ -620,39 +816,242 @@ def _reward_action_rate(self, linvel, gyro, dof_pos) -> torch.Tensor: def _reward_similar_to_default(self, linvel, gyro, dof_pos) -> torch.Tensor: del linvel, gyro - return torch.sum(torch.abs(dof_pos - self.default_angles), dim=1) + error = torch.sum(torch.abs(dof_pos - self.default_angles), dim=1) + standing = torch.linalg.vector_norm(self._commands, dim=1) < self.cfg.commands.velocity.standing_threshold + gain = 1.0 + (float(self.cfg.reward_config.standing_similar_to_default_gain) - 1.0) * standing + return error * gain + + def _posture_constraint_scale(self) -> torch.Tensor: + """Scale posture constraints down only for lateral/yaw commands. + + Standing and pure forward/backward commands retain full strength. A + smooth minimum of the lateral and yaw command magnitudes transitions + the scale from 1.0 to a non-zero floor, so the constraints remain + stabilizing during sidestepping and turning without dictating their + nominal leg geometry. + """ + activity = torch.maximum(torch.abs(self._commands[:, 1]), torch.abs(self._commands[:, 2])) + progress = torch.clamp( + (activity - self._POSTURE_GATE_START) / (self._POSTURE_GATE_END - self._POSTURE_GATE_START), + 0.0, + 1.0, + ) + smooth = torch.square(progress) * (3.0 - 2.0 * progress) + return 1.0 - (1.0 - self._POSTURE_GATE_FLOOR) * smooth + + def _reward_feet_spacing(self, linvel, gyro, dof_pos) -> torch.Tensor: + del linvel, gyro, dof_pos + if self._default_feet_width is None: + return torch.zeros((self._num_envs,), dtype=torch.float32) + + front_width = self.feet_pos[:, 0, 1] - self.feet_pos[:, 1, 1] + rear_width = self.feet_pos[:, 2, 1] - self.feet_pos[:, 3, 1] + target_width = self._default_feet_width.to(torch.float32) + reward_cfg = self.cfg.reward_config + pair_widths = torch.stack([front_width, rear_width], dim=1) + errors = torch.abs(pair_widths - target_width) + excess = torch.clamp(errors - reward_cfg.feet_spacing_tolerance, min=0.0) + pair_rewards = torch.exp(-torch.square(excess / reward_cfg.feet_spacing_sigma)) + return torch.mean(pair_rewards, dim=1) * self._posture_constraint_scale() def _reward_swing_feet_z(self, linvel, gyro, dof_pos) -> torch.Tensor: del linvel, gyro, dof_pos feet_phase = self._feet_phase contacts = self.feet_contact - valid_swing = (feet_phase >= 0.6) & ~contacts reward_cfg = self.cfg.reward_config # feet_pos is body-relative (framepos with ref=imu). The foot lifts - # `target_height` above its stance position, so the body-frame target is - # target_height - base_height_target (e.g. 0.1 - 0.3 = -0.2). This keeps - # the reward invariant to the body's world-frame vertical motion. - target_z = reward_cfg.target_foot_height - reward_cfg.base_height_target + # `target_height` above its stance position. Convert that world-frame + # lift into the sensor frame using the configured base-to-sensor offset. + swing_fraction = self._swing_fraction[:, None] + swing_start = 1.0 - swing_fraction + valid_swing = (feet_phase >= swing_start) & ~contacts + sensor_ground_z = -reward_cfg.base_height_target - reward_cfg.foot_height_reference_offset + target_z = sensor_ground_z + reward_cfg.target_foot_height + if reward_cfg.swing_feet_z_sinusoidal: + # Shape the vertical trajectory instead of holding the peak for the + # entire swing. The final part of the gait cycle is swing, so map + # it to a smooth lift-and-place arc. Rise and plateau fractions are + # normalized by swing duration and make velocity zero at endpoints. + swing_progress = torch.clamp((feet_phase - swing_start) / swing_fraction, 0.0, 1.0) + rise_fraction = float(reward_cfg.swing_rise_fraction) + plateau_fraction = float(reward_cfg.swing_plateau_fraction) + if not 0.0 < rise_fraction < 1.0 or plateau_fraction < 0.0 or rise_fraction + plateau_fraction >= 1.0: + raise ValueError("swing rise and plateau fractions must lie strictly inside the swing phase") + plateau_start = rise_fraction + descent_start = rise_fraction + plateau_fraction + target_profile = torch.empty_like(swing_progress) + rising = swing_progress < plateau_start + plateauing = (swing_progress >= plateau_start) & (swing_progress < descent_start) + descending = swing_progress >= descent_start + target_profile[rising] = 0.5 * (1.0 - torch.cos(math.pi * swing_progress[rising] / rise_fraction)) + target_profile[plateauing] = 1.0 + descent_progress = (swing_progress[descending] - descent_start) / (1.0 - descent_start) + target_profile[descending] = 0.5 * (1.0 + torch.cos(math.pi * descent_progress)) + target_z = sensor_ground_z + reward_cfg.target_foot_height * target_profile height_error = torch.square(self.feet_pos[:, :, 2] - target_z) sigma_sq = reward_cfg.swing_feet_height_sigma**2 swing_rew = torch.exp(-height_error / sigma_sq) * valid_swing return torch.sum(swing_rew, dim=1) / self._num_feet + def _reward_touchdown_velocity(self, linvel, gyro, dof_pos) -> torch.Tensor: + del linvel, gyro, dof_pos + reward_cfg = self.cfg.reward_config + current_height = self.feet_pos[:, :, 2] + previous_height = self._last_feet_pos[:, :, 2] + vertical_speed = (current_height - previous_height) / max(float(self.cfg.ctrl_dt), 1e-6) + sensor_ground_z = ( + reward_cfg.touchdown_height_threshold + - reward_cfg.base_height_target + - reward_cfg.foot_height_reference_offset + ) + near_ground = (current_height < sensor_ground_z) & (vertical_speed < 0.0) + normalized_speed = torch.clamp( + torch.abs(vertical_speed) / reward_cfg.touchdown_speed_sigma, + max=float(reward_cfg.touchdown_speed_clip), + ) + return torch.mean(torch.square(normalized_speed) * near_ground, dim=1) + def _reward_contact(self, linvel, gyro, dof_pos) -> torch.Tensor: del linvel, gyro, dof_pos res = torch.zeros((self._num_envs,), dtype=torch.float32) feet_phase = self._feet_phase contacts = self.feet_contact + swing_start = 1.0 - self._swing_fraction for i in range(self._num_feet): - target_contact = feet_phase[:, i] < 0.6 + target_contact = feet_phase[:, i] < swing_start res += (contacts[:, i] == target_contact).to(torch.float32) return res / self._num_feet def _reward_swing_contact(self, linvel, gyro, dof_pos) -> torch.Tensor: + """Penalize contact most strongly during the middle of swing. + + Brief contact at lift-off and touchdown is a normal transition in a + discrete-time simulator. Weighting the interior of swing more + strongly targets sustained dragging without adding another tuning + parameter or changing the average penalty for a foot that remains in + contact throughout swing. + """ del linvel, gyro, dof_pos - is_swing = self._feet_phase >= 0.6 + swing_fraction = self._swing_fraction[:, None] + swing_start = 1.0 - swing_fraction + is_swing = self._feet_phase >= swing_start swing_contacts = self.feet_contact & is_swing - return torch.sum(swing_contacts, dim=1) / self._num_feet + if not self.cfg.reward_config.swing_contact_slip_penalty: + return torch.sum(swing_contacts.to(torch.float32), dim=1) / self._num_feet + + swing_progress = torch.clamp( + (self._feet_phase - swing_start) / swing_fraction, + 0.0, + 1.0, + ) + phase_weight = 2.0 * torch.square(torch.sin(math.pi * swing_progress)) + weighted_contacts = swing_contacts.to(torch.float32) * phase_weight + + # Once a foot has remained in contact for two consecutive control + # ticks, its horizontal displacement is ground slip rather than a + # touchdown transition. Keep the existing linear velocity penalty + # for moving commands; static commands use the position anchor below + # so slow creep cannot accumulate for free. + consecutive_stance = self.feet_contact & self._last_feet_contact & ~is_swing + horizontal_displacement = torch.linalg.vector_norm( + self.feet_world_pos[:, :, :2] - self._last_feet_world_pos[:, :, :2], dim=2 + ) + horizontal_speed = horizontal_displacement / max(float(self.cfg.ctrl_dt), 1e-6) + standing = torch.linalg.vector_norm(self._commands, dim=1) < self.cfg.commands.velocity.standing_threshold + stance_motion = torch.clamp(6.0 * horizontal_speed, max=4.0) * consecutive_stance + + # In static stance, latch the world-frame contact point once contact + # is confirmed for two consecutive ticks. The latch is released on + # command motion or liftoff, so it cannot constrain walking, turning, + # or a normal swing/landing transition. + static_stance = consecutive_stance & standing[:, None] + self._static_anchor_valid &= standing[:, None] & self.feet_contact + new_anchors = static_stance & ~self._static_anchor_valid + self._static_anchor_pos[new_anchors] = self.feet_world_pos[:, :, :2][new_anchors] + self._static_anchor_valid[new_anchors] = True + anchor_error = torch.linalg.vector_norm( + self.feet_world_pos[:, :, :2] - self._static_anchor_pos, + dim=2, + ) + anchor_excess = torch.clamp(anchor_error - self._STATIC_ANCHOR_DEADBAND, min=0.0) + anchor_penalty = 4.0 * anchor_excess / (anchor_excess + self._STATIC_ANCHOR_SATURATION_SCALE) + anchor_motion = anchor_penalty * self._static_anchor_valid * standing[:, None] * self.feet_contact + stance_motion = torch.maximum(stance_motion, anchor_motion) + raw_penalty = torch.sum(weighted_contacts + stance_motion, dim=1) / self._num_feet + forward_scale = self.cfg.reward_config.swing_contact_forward_scale + if forward_scale is None: + return raw_penalty + # The low-damping policy can evade speed tracking by keeping feet on + # the ground and dragging. Low-speed forward gait is especially prone + # to that shortcut, so ramp this existing penalty with forward command + # magnitude only. Reverse, lateral, yaw, and standing commands retain + # the nominal scale until they receive dedicated diagnostic evidence. + direction_scale = 1.0 + (float(forward_scale) - 1.0) * torch.clamp(self._commands[:, 0], 0.0, 1.0) + return raw_penalty * direction_scale + + def _reward_flat_orientation(self, linvel, gyro, dof_pos) -> torch.Tensor: + """Penalize roll/pitch tilt while leaving yaw unconstrained.""" + del linvel, gyro, dof_pos + upvector = self.get_gravity() + return torch.sum(torch.square(upvector[:, :2]), dim=1) + + def _reward_dof_acc(self, linvel, gyro, dof_pos) -> torch.Tensor: + """Penalize the largest joint acceleration estimated from velocity changes.""" + del linvel, gyro, dof_pos + joint_vel = self.get_dof_vel() + acceleration = (joint_vel - self._last_joint_vel) / max(float(self.cfg.ctrl_dt), 1e-6) + return torch.amax(torch.square(acceleration), dim=1) + + def _reward_hip_position(self, linvel, gyro, dof_pos) -> torch.Tensor: + del linvel, gyro + if self._hip_indices.size == 0: + return torch.zeros((self._num_envs,), dtype=torch.float32) + + reward_cfg = self.cfg.reward_config + hip_error = torch.abs(dof_pos[:, self._hip_indices] - self.default_angles[self._hip_indices]) + excess = torch.clamp(hip_error - reward_cfg.hip_position_tolerance, min=0.0) + normalized = torch.clamp(excess / reward_cfg.hip_position_sigma, max=3.0) + return torch.mean(torch.square(normalized), dim=1) * self._posture_constraint_scale() + + def _reward_base_com_position(self, linvel, gyro, dof_pos) -> torch.Tensor: + """Keep COM inside the standing or motion-specific envelope. + + Zero command retains the nominal handoff posture. During motion the + target remains the nominal handoff COM relative to the mean of all + four feet, with a bounded command-dependent envelope. + """ + del linvel, gyro, dof_pos + reward_cfg = self.cfg.reward_config + if self._default_base_com_forward_offset is None: + return torch.zeros((self._num_envs,), dtype=torch.float32) + + base_com_x = float(self.model.others["base_com"][0]) + # Keep the training reference identical to the audit metric: + # COM x relative to the mean x of all four feet. Using only the + # currently contacting feet makes the reference jump every half gait + # cycle and lets the policy evade the dynamic COM constraint while + # still showing a large measured forward extension. + all_feet_center = torch.mean(self.feet_pos[:, :, 0], dim=1) + current_offset = base_com_x - all_feet_center + + commands = self._commands + standing = torch.linalg.vector_norm(commands, dim=1) < self.cfg.commands.velocity.standing_threshold + forward_speed = torch.clamp(commands[:, 0], 0.0, 1.0) + backward_speed = torch.clamp(-commands[:, 0], 0.0, 1.0) + upper_allowance = self._DYNAMIC_COM_FORWARD_ALLOWANCE * forward_speed + lower_allowance = self._DYNAMIC_COM_BACKWARD_ALLOWANCE * backward_speed + target = self._default_base_com_forward_offset + upper = target + upper_allowance + lower = target - lower_allowance + excess = torch.clamp(torch.maximum(current_offset - upper, lower - current_offset), min=0.0) + # Standing remains a symmetric nominal-position constraint; movement + # uses the one-sided dynamic envelope above. + standing_error = torch.abs(current_offset - self._default_base_com_forward_offset) + excess = torch.where(standing, standing_error, excess) + excess = torch.clamp(excess - reward_cfg.base_com_position_tolerance, min=0.0) + normalized = excess / reward_cfg.base_com_position_sigma + dynamic_scale = self._posture_constraint_scale() + return torch.square(normalized) * torch.where(standing, 1.0, dynamic_scale) __all__ = ["QuadrupedWalkTask"] diff --git a/motrix_envs/tests/test_quadruped_walk.py b/motrix_envs/tests/test_quadruped_walk.py index 4c80f9946..7e7235346 100644 --- a/motrix_envs/tests/test_quadruped_walk.py +++ b/motrix_envs/tests/test_quadruped_walk.py @@ -90,6 +90,92 @@ def test_quadruped_reward_scales_are_structured_and_not_shared(): assert go1 is not go2 +def test_go2_uses_locomotion_first_reward_set(): + env = registry.make("go2-walk-flat", num_envs=1, mode="train") + env.initialize() + env.step(np.zeros((env.num_envs, *env.action_space.shape), dtype=np.float32)) + + assert "similar_to_default" in env.state.reward_terms + assert "dof_acc" in env.state.reward_terms + assert "hip_position" in env.state.reward_terms + assert "base_com_position" in env.state.reward_terms + + baseline = registry.make("go1-walk-flat", num_envs=1, mode="train") + baseline.initialize() + baseline.step(np.zeros((baseline.num_envs, *baseline.action_space.shape), dtype=np.float32)) + + assert "similar_to_default" in baseline.state.reward_terms + assert "dof_acc" not in baseline.state.reward_terms + assert "hip_position" not in baseline.state.reward_terms + + +def test_go2_velocity_command_range_matches_supported_envelope(): + velocity_cfg = registry.make_env_config("go2-walk-flat").commands.velocity + + np.testing.assert_allclose(velocity_cfg.lower, np.array([-1.0, -0.5, -1.0], dtype=np.float32)) + np.testing.assert_allclose(velocity_cfg.upper, np.array([1.0, 0.5, 1.0], dtype=np.float32)) + + +def test_tracking_lin_vel_reward_applies_directional_tracking_sigmas(): + env = registry.make("go2-walk-flat", num_envs=3, mode="train") + env.initialize() + env._commands.copy_( + torch.tensor( + [ + [1.0, 0.0, 0.0], + [-1.0, 0.0, 0.0], + [0.0, 0.5, 0.0], + ], + dtype=torch.float32, + ) + ) + linvel = torch.zeros((env.num_envs, 3), dtype=torch.float32) + + reward = env._reward_tracking_lin_vel(linvel, None, None) + + np.testing.assert_allclose( + reward, + np.array( + [ + np.exp(-1.0 / 0.16), + np.exp(-1.0 / 0.35), + np.exp(-0.25 / 0.25), + ], + dtype=np.float32, + ), + ) + + +def test_go2_hip_position_reward_only_penalizes_excess_abduction(): + env = registry.make("go2-walk-flat", num_envs=1, mode="train") + env.initialize() + + assert env._hip_indices.numel() == 4 + dof_pos = env.default_angles.repeat(1, 1).clone() + within_tolerance = env._reward_hip_position(None, None, dof_pos) + dof_pos[0, env._hip_indices[0]] += env.cfg.reward_config.hip_position_tolerance + at_tolerance = env._reward_hip_position(None, None, dof_pos) + dof_pos[0, env._hip_indices[0]] += env.cfg.reward_config.hip_position_sigma + excessive = env._reward_hip_position(None, None, dof_pos) + + np.testing.assert_allclose(within_tolerance, 0.0) + np.testing.assert_allclose(at_tolerance, 0.0) + assert excessive[0] > 0.0 + + +def test_go2_dof_acc_reward_uses_worst_joint_acceleration(quadruped_env): + env = quadruped_env + env._last_joint_vel[:] = 0.0 + joint_vel = torch.zeros_like(env._last_joint_vel) + joint_vel[0, 0] = float(env.cfg.ctrl_dt) + joint_vel[0, 1] = 2.0 * float(env.cfg.ctrl_dt) + env.get_dof_vel = lambda: joint_vel + + penalty = env._reward_dof_acc(None, None, None) + + np.testing.assert_allclose(penalty, [4.0]) + + def test_go2_velocity_commands_remain_constant_before_resampling_interval(): torch.manual_seed(7) env = registry.make("go2-walk-flat", num_envs=64, mode="train") @@ -107,6 +193,24 @@ def test_go2_velocity_commands_remain_constant_before_resampling_interval(): np.testing.assert_array_equal(env._commands, commands) +def test_go2_hard_case_curriculum_interpolates_by_training_iteration(): + env = registry.make("go2-walk-flat", num_envs=1, mode="train") + binding = env._velocity_command_binding + assert binding.hard_case_probability == pytest.approx(0.0) + env._set_hard_case_probability(600) + assert binding.hard_case_probability == pytest.approx(0.152) + env._set_hard_case_probability(1000) + assert binding.hard_case_probability == pytest.approx(0.20) + env._set_hard_case_probability(1500) + assert binding.hard_case_probability == pytest.approx(0.20) + + +def test_go2_play_disables_hard_case_curriculum(): + env = registry.make("go2-walk-flat", num_envs=1, mode="play") + assert env.cfg.commands.velocity.hard_case_curriculum == () + assert env._velocity_command_binding.hard_case_probability == pytest.approx(0.0) + + def test_go2_randomization_is_enabled_for_training_and_disabled_for_play(): flat_cfg = registry.make_env_config("go2-walk-flat") rough_cfg = registry.make_env_config("go2-walk-rough") @@ -359,17 +463,37 @@ def test_quadruped_randomization_config_rejects_invalid_ranges(update, message): cfg.validate() -def test_zero_velocity_command_freezes_gait_phase(): +def test_gait_schedule_and_stand_transition_are_continuous(): env = registry.make("go2-walk-flat", num_envs=2, mode="train") env.initialize() + cfg = env.cfg + env._commands[:] = torch.tensor([0.8, 0.0, 0.0], dtype=torch.float32) + env._gait_schedule_alpha[:] = 0.0 + + env._advance_phase() + + max_alpha_step = cfg.ctrl_dt / cfg.gait_schedule_smoothing_time_s + assert env._gait_schedule_alpha[0] == pytest.approx(max_alpha_step) + assert env._gait_frequency[0] < cfg.gait_schedule_frequency_high + assert env._swing_fraction[0] < cfg.gait_schedule_swing_fraction_high + env._commands[:] = 0.0 env._phase[:] = 0.5 env._feet_phase[:] = 0.5 - env._advance_phase() - np.testing.assert_array_equal(env._phase, np.zeros(2, dtype=np.float32)) + # Stand and walk share phase zero. Advancing a hidden clock while the + # observed phase is masked would make startup jump to an arbitrary swing. np.testing.assert_array_equal(env._feet_phase, np.zeros((2, env._num_feet), dtype=np.float32)) + np.testing.assert_array_equal(env._phase, np.zeros(2, dtype=np.float32)) + + env._commands.copy_(torch.tensor([0.0, 0.0, 1.0], dtype=torch.float32)) + env._advance_phase() + assert env._gait_frequency[0] > cfg.gait_schedule_frequency_low + + env._commands.copy_(torch.tensor([0.0, 0.5, 0.0], dtype=torch.float32)) + env._advance_phase() + assert env._gait_frequency[0] > cfg.gait_schedule_frequency_low @pytest.mark.parametrize( @@ -423,10 +547,8 @@ def test_foot_position_sensor_names_belong_to_walk_task_config(): @pytest.mark.parametrize("robot_name", ["go1", "go2", "anymalc"]) def test_walk_task_gyro_config_compiles_for_each_robot(robot_name): - cfg = registry.make_env_config(f"{robot_name}-walk-flat") - rough_cfg = registry.make_env_config(f"{robot_name}-walk-rough") - # Terrain variants use the same model-local gyro wiring; compile each robot only once. - assert _sim_data_queries(rough_cfg)["gyro"] == _sim_data_queries(cfg)["gyro"] + env_name = "go2-walk-flat" if robot_name == "go2" else f"{robot_name}-walk-flat" + cfg = registry.make_env_config(env_name) robot = cfg.scene.objs.robot backend = MotrixSimBackend(cfg.scene, cfg.sim, 1) reads = backend.compile_reads({"gyro": _sim_data_queries(cfg)["gyro"]}) @@ -498,7 +620,9 @@ def test_walk_task_selects_named_robot_key_pose(): def test_swing_height_reward_requires_feet_to_leave_ground(quadruped_env): reward_cfg = quadruped_env.cfg.reward_config - quadruped_env.feet_pos[:, :, 2] = reward_cfg.target_foot_height - reward_cfg.base_height_target + quadruped_env.feet_pos[:, :, 2] = ( + reward_cfg.target_foot_height - reward_cfg.base_height_target - reward_cfg.foot_height_reference_offset + ) reward = _swing_reward( quadruped_env, @@ -510,7 +634,7 @@ def test_swing_height_reward_requires_feet_to_leave_ground(quadruped_env): def test_swing_height_reward_prefers_target_height(quadruped_env): reward_cfg = quadruped_env.cfg.reward_config - target_z = reward_cfg.target_foot_height - reward_cfg.base_height_target + target_z = reward_cfg.target_foot_height - reward_cfg.base_height_target - reward_cfg.foot_height_reference_offset no_contacts = np.zeros((1, quadruped_env._num_feet), dtype=bool) quadruped_env.feet_pos[:, :, 2] = target_z @@ -524,24 +648,279 @@ def test_swing_height_reward_prefers_target_height(quadruped_env): assert bool((off_target_reward > 0.0).all()) +def test_go2_swing_height_reward_uses_lift_plateau_and_slow_place_profile(): + env = registry.make("go2-walk-flat", num_envs=1, mode="train") + env.initialize() + env.cfg.reward_config.swing_feet_z_sinusoidal = True + env._swing_fraction[:] = env.cfg.reward_config.swing_fraction + no_contacts = np.zeros((1, env._num_feet), dtype=bool) + ground_z = -env.cfg.reward_config.base_height_target - env.cfg.reward_config.foot_height_reference_offset + peak_z = ground_z + env.cfg.reward_config.target_foot_height + rewards = {} + + rise_fraction = env.cfg.reward_config.swing_rise_fraction + plateau_fraction = env.cfg.reward_config.swing_plateau_fraction + swing_start = 1.0 - env.cfg.reward_config.swing_fraction + swing_duration = env.cfg.reward_config.swing_fraction + plateau_phase = swing_start + swing_duration * (rise_fraction + 0.5 * plateau_fraction) + for phase, foot_z in ((swing_start, ground_z), (plateau_phase, peak_z), (1.0, ground_z)): + env._feet_phase[:] = phase + env.feet_contact.copy_(torch.as_tensor(no_contacts)) + env.feet_pos[:, :, 2] = foot_z + rewards[phase] = env._reward_swing_feet_z(None, None, None)[0] + + assert env.cfg.reward_config.swing_feet_z_sinusoidal is True + np.testing.assert_allclose(rewards[swing_start], 1.0) + np.testing.assert_allclose(rewards[plateau_phase], 1.0) + np.testing.assert_allclose(rewards[1.0], 1.0) + + env.feet_pos[:, :, 2] = peak_z + end_off_profile = env._reward_swing_feet_z(None, None, None)[0] + assert end_off_profile < rewards[1.0] + + +def test_go2_touchdown_velocity_penalty_only_applies_to_low_descending_feet(): + env = registry.make("go2-walk-flat", num_envs=1, mode="train") + env.initialize() + reward_cfg = env.cfg.reward_config + sensor_ground_z = -reward_cfg.base_height_target - reward_cfg.foot_height_reference_offset + + env._last_feet_pos[:, :, 2] = sensor_ground_z + env.feet_pos[:, :, 2] = sensor_ground_z - 0.01 + low_fast_touchdown = env._reward_touchdown_velocity(None, None, None) + + env.feet_pos[:, :, 2] = sensor_ground_z - 0.001 + low_slow_touchdown = env._reward_touchdown_velocity(None, None, None) + + env._last_feet_pos[:, :, 2] = sensor_ground_z + reward_cfg.target_foot_height + env.feet_pos[:, :, 2] = sensor_ground_z + reward_cfg.target_foot_height - 0.01 + high_start_touchdown = env._reward_touchdown_velocity(None, None, None) + + env._last_feet_pos[:, :, 2] = sensor_ground_z + env.feet_pos[:, :, 2] = sensor_ground_z + 0.01 + low_liftoff = env._reward_touchdown_velocity(None, None, None) + + assert low_slow_touchdown[0] > 0.0 + assert low_fast_touchdown[0] > low_slow_touchdown[0] + np.testing.assert_allclose(high_start_touchdown, np.zeros((1,), dtype=np.float32)) + np.testing.assert_allclose(low_liftoff, np.zeros((1,), dtype=np.float32)) + + def test_swing_contact_penalty_detects_dragging_feet(quadruped_env): + quadruped_env.cfg.reward_config.swing_contact_slip_penalty = True feet_phase = np.full((1, quadruped_env._num_feet), 0.75, dtype=np.float32) no_contacts = np.zeros((1, quadruped_env._num_feet), dtype=bool) all_contacts = np.ones((1, quadruped_env._num_feet), dtype=bool) quadruped_env._feet_phase.copy_(torch.as_tensor(feet_phase)) + quadruped_env._last_feet_contact.copy_(torch.as_tensor(no_contacts)) quadruped_env.feet_contact.copy_(torch.as_tensor(no_contacts)) no_drag = quadruped_env._reward_swing_contact(None, None, None) quadruped_env.feet_contact.copy_(torch.as_tensor(all_contacts)) all_drag = quadruped_env._reward_swing_contact(None, None, None) np.testing.assert_array_equal(no_drag, np.zeros((1,), dtype=np.float32)) - np.testing.assert_array_equal(all_drag, np.ones((1,), dtype=np.float32)) + progress = ( + 0.75 - (1.0 - quadruped_env.cfg.reward_config.swing_fraction) + ) / quadruped_env.cfg.reward_config.swing_fraction + expected = 2.0 * np.square(np.sin(np.pi * progress)) + np.testing.assert_allclose(all_drag, np.asarray([expected], dtype=np.float32)) + + quadruped_env._feet_phase[:] = 1.0 - quadruped_env.cfg.reward_config.swing_fraction + np.testing.assert_allclose( + quadruped_env._reward_swing_contact(None, None, None), + np.zeros((1,), dtype=np.float32), + ) + + # Consecutive stance contact is penalized by horizontal foot motion, while + # a first contact tick is excluded as a touchdown transition. + quadruped_env._commands.copy_(torch.tensor([[0.5, 0.0, 0.0]], dtype=torch.float32)) + quadruped_env._feet_phase[:] = 0.0 + quadruped_env._last_feet_contact.copy_(torch.as_tensor(all_contacts)) + quadruped_env.feet_contact.copy_(torch.as_tensor(all_contacts)) + quadruped_env._last_feet_world_pos[:] = quadruped_env.feet_world_pos + quadruped_env.feet_world_pos[:, :, 0] += 0.001 + stance_motion = quadruped_env._reward_swing_contact(None, None, None) + np.testing.assert_allclose(stance_motion, np.asarray([0.3], dtype=np.float32), rtol=1e-5) + + quadruped_env._last_feet_contact.copy_(torch.as_tensor(no_contacts)) + np.testing.assert_allclose( + quadruped_env._reward_swing_contact(None, None, None), + np.zeros((1,), dtype=np.float32), + ) + + +def test_swing_contact_penalty_scales_with_forward_command(quadruped_env): + quadruped_env.cfg.reward_config.swing_contact_slip_penalty = True + quadruped_env.cfg.reward_config.swing_contact_forward_scale = 1.5 + quadruped_env._feet_phase[:] = 0.75 + quadruped_env.feet_contact[:] = True + quadruped_env._last_feet_contact[:] = False + + commands = ( + (-0.5, 0.0, 0.0), + (0.5, 0.0, 0.0), + (1.0, 0.0, 0.0), + (0.0, 0.5, 0.0), + (0.0, 0.0, -1.0), + ) + penalties = [] + for command in commands: + quadruped_env._commands.copy_(torch.tensor([command], dtype=torch.float32)) + penalties.append(quadruped_env._reward_swing_contact(None, None, None)[0]) + + reverse, half_forward, full_forward, lateral, yaw = penalties + nominal = full_forward / 1.5 + np.testing.assert_allclose(reverse, nominal) + np.testing.assert_allclose(half_forward, 1.25 * nominal) + np.testing.assert_allclose(lateral, nominal) + np.testing.assert_allclose(yaw, nominal) + assert full_forward > half_forward > nominal + + +def test_static_stance_anchors_contact_points_without_affecting_motion(quadruped_env): + quadruped_env.cfg.reward_config.swing_contact_slip_penalty = True + all_contacts = np.ones((1, quadruped_env._num_feet), dtype=bool) + quadruped_env._commands[:] = 0.0 + quadruped_env._feet_phase[:] = 0.0 + quadruped_env._last_feet_contact.copy_(torch.as_tensor(all_contacts)) + quadruped_env.feet_contact.copy_(torch.as_tensor(all_contacts)) + quadruped_env._static_anchor_valid[:] = False + quadruped_env._last_feet_world_pos[:] = quadruped_env.feet_world_pos + + first = quadruped_env._reward_swing_contact(None, None, None) + np.testing.assert_allclose(first, np.zeros((1,), dtype=np.float32)) + assert bool(quadruped_env._static_anchor_valid.all()) + + # Move all feet by 6 mm without a one-step velocity contribution. The + # static anchor still sees the accumulated position error and penalizes it. + quadruped_env.feet_world_pos[:, :, 0] += 0.006 + quadruped_env._last_feet_world_pos[:] = quadruped_env.feet_world_pos + anchored = quadruped_env._reward_swing_contact(None, None, None) + np.testing.assert_allclose(anchored, np.asarray([0.8], dtype=np.float32), rtol=1e-5) + + # The bounded barrier keeps increasing for large accumulated drift rather + # than becoming exactly flat after a finite clipping threshold. + quadruped_env.feet_world_pos[:, :, 0] += 0.054 + quadruped_env._last_feet_world_pos[:] = quadruped_env.feet_world_pos + larger_drift = quadruped_env._reward_swing_contact(None, None, None) + assert larger_drift[0] > anchored[0] + assert larger_drift[0] < 4.0 + + # A moving command releases the anchor and leaves the walking penalty path + # active, so the position latch cannot constrain normal gait motion. + quadruped_env._commands.copy_(torch.tensor([[0.5, 0.0, 0.0]], dtype=torch.float32)) + quadruped_env._reward_swing_contact(None, None, None) + assert not bool(quadruped_env._static_anchor_valid.any()) + + +def test_swing_contact_penalty_keeps_legacy_quadruped_behavior(quadruped_env): + quadruped_env.cfg.reward_config.swing_contact_slip_penalty = False + quadruped_env.cfg.reward_config.swing_contact_forward_scale = 1.5 + quadruped_env._feet_phase[:] = 0.75 + quadruped_env._commands[:] = 0.8 + quadruped_env._last_feet_contact[:] = True + quadruped_env.feet_contact[:] = True + quadruped_env._last_feet_world_pos[:] = quadruped_env.feet_world_pos + quadruped_env.feet_world_pos[:, :, 0] += 0.01 + + reward = quadruped_env._reward_swing_contact(None, None, None) + + np.testing.assert_allclose(reward, np.ones((1,), dtype=np.float32)) + assert not bool(quadruped_env._static_anchor_valid.any()) + + +def test_feet_spacing_reward_is_symmetric_for_splay_and_pigeon_toes(quadruped_env): + quadruped_env._default_feet_width = torch.tensor([0.3, 0.3], dtype=torch.float32) + quadruped_env.feet_pos[:, :, :] = 0.0 + quadruped_env.feet_pos[:, 0, 1] = 0.15 + quadruped_env.feet_pos[:, 1, 1] = -0.15 + quadruped_env.feet_pos[:, 2, 1] = 0.15 + quadruped_env.feet_pos[:, 3, 1] = -0.15 + nominal = quadruped_env._reward_feet_spacing(None, None, None) + + quadruped_env.feet_pos[:, :, :] = 0.0 + quadruped_env.feet_pos[:, 0, 1] = 0.20 + quadruped_env.feet_pos[:, 1, 1] = -0.20 + quadruped_env.feet_pos[:, 2, 1] = 0.20 + quadruped_env.feet_pos[:, 3, 1] = -0.20 + splay = quadruped_env._reward_feet_spacing(None, None, None) + + quadruped_env.feet_pos[:, :, :] = 0.0 + quadruped_env.feet_pos[:, 0, 1] = 0.10 + quadruped_env.feet_pos[:, 1, 1] = -0.10 + quadruped_env.feet_pos[:, 2, 1] = 0.10 + quadruped_env.feet_pos[:, 3, 1] = -0.10 + pigeon = quadruped_env._reward_feet_spacing(None, None, None) + + np.testing.assert_allclose(nominal, np.ones((1,), dtype=np.float32)) + np.testing.assert_allclose(splay, pigeon, rtol=0.0, atol=1e-8) + assert bool((splay < nominal).all()) + + +def test_feet_spacing_reward_covers_front_and_rear_pairs(quadruped_env): + quadruped_env._default_feet_width = torch.tensor([0.3, 0.3], dtype=torch.float32) + quadruped_env.feet_pos[:, :, :] = 0.0 + quadruped_env.feet_pos[:, 0, 1] = 0.20 + quadruped_env.feet_pos[:, 1, 1] = -0.20 + quadruped_env.feet_pos[:, 2, 1] = 0.15 + quadruped_env.feet_pos[:, 3, 1] = -0.15 + front_bad = quadruped_env._reward_feet_spacing(None, None, None) + + quadruped_env.feet_pos[:, 0, 1] = 0.15 + quadruped_env.feet_pos[:, 1, 1] = -0.15 + quadruped_env.feet_pos[:, 2, 1] = 0.20 + quadruped_env.feet_pos[:, 3, 1] = -0.20 + rear_bad = quadruped_env._reward_feet_spacing(None, None, None) + + np.testing.assert_allclose(front_bad, rear_bad) + assert bool((front_bad < 1.0).all()) + + +def test_feet_spacing_reward_does_not_cancel_front_and_rear_errors(quadruped_env): + quadruped_env._default_feet_width = torch.tensor([0.3, 0.3], dtype=torch.float32) + quadruped_env.feet_pos[:, :, :] = 0.0 + quadruped_env.feet_pos[:, 0, 1] = 0.20 + quadruped_env.feet_pos[:, 1, 1] = -0.20 + quadruped_env.feet_pos[:, 2, 1] = 0.15 + quadruped_env.feet_pos[:, 3, 1] = -0.15 + one_pair_bad = quadruped_env._reward_feet_spacing(None, None, None) + + # The signed front/rear errors have opposite directions, but both pairs are + # outside tolerance. Their penalties must not cancel before shaping. + quadruped_env.feet_pos[:, 0, 1] = 0.20 + quadruped_env.feet_pos[:, 1, 1] = -0.20 + quadruped_env.feet_pos[:, 2, 1] = 0.10 + quadruped_env.feet_pos[:, 3, 1] = -0.10 + opposite_signed_bad = quadruped_env._reward_feet_spacing(None, None, None) + + assert bool((one_pair_bad < 1.0).all()) + assert bool((opposite_signed_bad < one_pair_bad).all()) + + +def test_posture_constraints_are_full_for_sagittal_and_soft_for_lateral_yaw(quadruped_env): + commands = ( + (0.0, 0.0, 0.0), + (0.8, 0.0, 0.0), + (-0.8, 0.0, 0.0), + (0.0, 0.3, 0.0), + (0.0, 0.0, 0.3), + (0.0, 0.8, 0.8), + ) + scales = [] + for command in commands: + quadruped_env._commands.copy_(torch.tensor([command], dtype=torch.float32)) + scales.append(quadruped_env._posture_constraint_scale()[0]) + + np.testing.assert_allclose(scales[:3], 1.0) + np.testing.assert_allclose(scales[3:5], 0.70, rtol=1e-6) + np.testing.assert_allclose(scales[5], quadruped_env._POSTURE_GATE_FLOOR) @pytest.mark.parametrize("robot_name", ["go1", "go2", "anymalc"]) def test_walk_state_sensor_queries_resolve_model_and_scene_names(robot_name): - cfg = registry.make_env_config(f"{robot_name}-walk-flat") + env_name = "go2-walk-flat" if robot_name == "go2" else f"{robot_name}-walk-flat" + cfg = registry.make_env_config(env_name) robot = cfg.scene.objs.robot robot.prefix = "robot_" robot.suffix = "_instance" @@ -567,3 +946,19 @@ def test_walk_state_sensor_queries_resolve_model_and_scene_names(robot_name): for name in names: assert reads[name].shape == (1, 3) assert torch.isfinite(reads[name]).all() + + +def test_go2_rough_does_not_inherit_flat_task_tuning(): + # Go2 rough inherits from the flat config class only to preserve upstream + # task registration. The flat-only gait schedule and domain-randomization + # changes must therefore remain explicitly reverted for rough. + env_cfg = registry.make_env_config("go2-walk-rough") + + assert env_cfg.gait_schedule_enabled is False + assert env_cfg.randomization.sliding_friction_range == (0.4, 0.9) + assert env_cfg.randomization.sliding_friction_high_traction_sampling is False + assert env_cfg.commands.velocity.standing_probability == pytest.approx(0.1) + assert env_cfg.reward_config.scales.similar_to_default == pytest.approx(-0.1) + assert env_cfg.reward_config.tracking_ang_vel_sigma == pytest.approx(0.25) + assert env_cfg.reward_config.standing_similar_to_default_gain == pytest.approx(1.0) + assert env_cfg.reward_config.swing_contact_slip_penalty is False diff --git a/motrix_robots/src/motrix_robots/assets/go2/go2_mjx.xml b/motrix_robots/src/motrix_robots/assets/go2/go2_mjx.xml index f227356b8..2953a940b 100644 --- a/motrix_robots/src/motrix_robots/assets/go2/go2_mjx.xml +++ b/motrix_robots/src/motrix_robots/assets/go2/go2_mjx.xml @@ -13,7 +13,7 @@ - + diff --git a/motrix_robots/src/motrix_robots/unitree.py b/motrix_robots/src/motrix_robots/unitree.py index f944c9a27..2b7c4738c 100644 --- a/motrix_robots/src/motrix_robots/unitree.py +++ b/motrix_robots/src/motrix_robots/unitree.py @@ -167,7 +167,7 @@ class UnitreeGo2Robot(QuadrupedRobotCfg): "RR_calf_joint", ], poses={ - "default": [0.0, 0.8, -1.5, 0.0, 0.8, -1.5, 0.0, 1.0, -1.5, 0.0, 1.0, -1.5], + "default": [0.0, 0.8, -1.5, 0.0, 0.8, -1.5, 0.0, 0.8, -1.5, 0.0, 0.8, -1.5], "lie_down": [ 0.05175, 1.238835,