Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions docs/source/changelog.rst
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,12 @@ Changed
Fixed
^^^^^

- Motion tracking tasks now truncate episodes with ``motion_time_out``
(``time_out=True``) when the reference clip ends, instead of wrapping silently inside
``MotionCommand`` and bootstrapping value targets across teleported resets
:issue:`1106`.
- ``TerminationManager`` now clears ``time_outs`` on steps where a non-timeout
termination also fires, so failed terminal states are not bootstrapped as timeouts.
- YAM RGB and depth cube-lifting tasks now use separate experiment directories,
``yam_lift_cube_rgb`` and ``yam_lift_cube_depth``.
- ``EntityData.gravity_vec_w`` now initializes from normalized model gravity, so
Expand Down
1 change: 1 addition & 0 deletions src/mjlab/managers/termination_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ def compute(self) -> torch.Tensor:
else:
self._terminated_buf |= value
self._term_dones[name][:] = value
self._truncated_buf &= ~self._terminated_buf
return self._truncated_buf | self._terminated_buf

def get_term(self, name: str) -> torch.Tensor:
Expand Down
11 changes: 9 additions & 2 deletions src/mjlab/tasks/tracking/mdp/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -291,8 +291,9 @@ def _adaptive_sampling(self, env_ids: torch.Tensor):
self.metrics["sampling_top1_bin"][:] = imax.float() / self.bin_count

def _uniform_sampling(self, env_ids: torch.Tensor):
max_step = max(1, self.motion.time_step_total - 1)
self.time_steps[env_ids] = torch.randint(
0, self.motion.time_step_total, (len(env_ids),), device=self.device
0, max_step, (len(env_ids),), device=self.device
)
self.metrics["sampling_entropy"][:] = 1.0 # Maximum entropy for uniform.
self.metrics["sampling_top1_prob"][:] = 1.0 / self.bin_count
Expand Down Expand Up @@ -420,7 +421,13 @@ def _update_command(self, env_ids: torch.Tensor | None = None):
self.time_steps[env_ids] += 1
wrap_ids = torch.where(self.time_steps >= self.motion.time_step_total)[0]
if wrap_ids.numel() > 0:
self._resample_command(wrap_ids)
if env_ids is None and self._env.cfg.auto_reset is False:
done_mask = self._env.reset_buf[wrap_ids]
if torch.any(done_mask):
self.time_steps[wrap_ids[done_mask]] = self.motion.time_step_total - 1
wrap_ids = wrap_ids[~done_mask]
if wrap_ids.numel() > 0:
self._resample_command(wrap_ids)

# _resample_command writes qpos/qvel but does not refresh derived
# quantities; forward() so update_relative_body_poses reads the
Expand Down
6 changes: 6 additions & 0 deletions src/mjlab/tasks/tracking/mdp/terminations.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,12 @@
from mjlab.managers.scene_entity_config import SceneEntityCfg


def motion_time_out(env: ManagerBasedRlEnv, command_name: str) -> torch.Tensor:
"""Truncate when the reference motion reaches its final frame."""
command = cast(MotionCommand, env.command_manager.get_term(command_name))
return command.time_steps + 1 >= command.motion.time_step_total


def bad_anchor_pos(
env: ManagerBasedRlEnv, command_name: str, threshold: float
) -> torch.Tensor:
Expand Down
5 changes: 5 additions & 0 deletions src/mjlab/tasks/tracking/tracking_env_cfg.py
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,11 @@ def make_tracking_env_cfg() -> ManagerBasedRlEnvCfg:

terminations: dict[str, TerminationTermCfg] = {
"time_out": TerminationTermCfg(func=mdp.time_out, time_out=True),
"motion_time_out": TerminationTermCfg(
func=mdp.motion_time_out,
params={"command_name": "motion"},
time_out=True,
),
"anchor_pos": TerminationTermCfg(
func=mdp.bad_anchor_pos_z_only,
params={"command_name": "motion", "threshold": 0.25},
Expand Down
29 changes: 29 additions & 0 deletions tests/test_command_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -177,3 +177,32 @@ def test_motion_command_timer_resample_triggers_forward():
cmd._env.sim.forward.reset_mock()
MotionCommand._update_command(cmd, env_ids=None)
cmd._env.sim.forward.assert_not_called()


def test_motion_command_uniform_sampling_excludes_final_frame():
"""Uniform RSI leaves room for reset()'s +1 advance without wrapping."""
cmd = Mock()
cmd.device = "cpu"
cmd.bin_count = 4
cmd.time_steps = torch.zeros(256, dtype=torch.long)
cmd.metrics = {
"sampling_entropy": torch.zeros(256),
"sampling_top1_prob": torch.zeros(256),
"sampling_top1_bin": torch.zeros(256),
}
cmd.motion.time_step_total = 5
MotionCommand._uniform_sampling(cmd, torch.arange(256))
assert int(cmd.time_steps.min().item()) >= 0
assert int(cmd.time_steps.max().item()) <= 3


def test_motion_command_auto_reset_false_holds_final_frame():
"""Done envs do not teleport over terminal observations when auto_reset=False."""
cmd = _make_motion_command_stub([9, 9], total=10)
cmd._env.cfg.auto_reset = False
cmd._env.reset_buf = torch.tensor([True, False])
MotionCommand._update_command(cmd, env_ids=None)
# Env 0 is done so its frame holds at 9 without resampling; env 1 wraps.
assert cmd.time_steps[0].item() == 9
(wrap_ids,), _ = cmd._resample_command.call_args
assert wrap_ids.tolist() == [1]
35 changes: 35 additions & 0 deletions tests/test_terminations.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from mjlab.envs.mdp.terminations import nan_detection
from mjlab.managers.termination_manager import TerminationManager, TerminationTermCfg
from mjlab.sim.sim import Simulation, SimulationCfg
from mjlab.tasks.tracking.mdp.terminations import motion_time_out
from mjlab.tasks.velocity.mdp.terminations import (
out_of_terrain_bounds,
terrain_edge_reached,
Expand Down Expand Up @@ -238,3 +239,37 @@ def test_out_of_terrain_bounds_includes_border_width(mock_grid_terrain_env):
asset.data.root_link_pos_w[1, 0] = 42.0 # Past border edge (limit 41.7m).
result = out_of_terrain_bounds(env)
assert not result[0] and result[1]


def test_termination_overrides_simultaneous_time_out(mock_env):
"""Failure termination takes precedence over simultaneous timeout."""
cfg = {
"timeout": TerminationTermCfg(
func=lambda env: torch.tensor([True, True, False, False]),
time_out=True,
),
"failure": TerminationTermCfg(
func=lambda env: torch.tensor([False, True, True, False]),
time_out=False,
),
}
manager = TerminationManager(cfg, mock_env)
dones = manager.compute()
assert dones.tolist() == [True, True, True, False]
assert manager.terminated.tolist() == [False, True, True, False]
assert manager.time_outs.tolist() == [True, False, False, False]

reset_info = manager.reset()
assert reset_info["Episode_Termination/timeout"] == 2
assert reset_info["Episode_Termination/failure"] == 2


def test_motion_time_out_fires_on_final_frame(mock_env):
"""motion_time_out truncates when the clip reaches its final frame."""
cmd = Mock()
cmd.time_steps = torch.tensor([0, 8, 9, 10], dtype=torch.long)
cmd.motion.time_step_total = 10
mock_env.command_manager.get_term.return_value = cmd

result = motion_time_out(mock_env, command_name="motion")
assert result.tolist() == [False, False, True, True]
16 changes: 16 additions & 0 deletions tests/test_tracking_task.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from mjlab.asset_zoo.robots import G1_ACTION_SCALE
from mjlab.envs.mdp.actions import JointPositionActionCfg
from mjlab.tasks.registry import list_tasks, load_env_cfg
from mjlab.tasks.tracking import mdp
from mjlab.tasks.tracking.mdp import MotionCommandCfg


Expand Down Expand Up @@ -132,3 +133,18 @@ def test_g1_tracking_has_correct_action_scale(g1_tracking_task_ids: list[str]) -
assert joint_pos_action.scale == G1_ACTION_SCALE, (
f"Task {task_id} action scale mismatch, expected G1_ACTION_SCALE"
)


def test_tracking_tasks_have_motion_time_out_truncation(
tracking_task_ids: list[str],
) -> None:
"""All tracking tasks should truncate when the reference clip ends."""
for task_id in tracking_task_ids:
for play_mode in [False, True]:
cfg = load_env_cfg(task_id, play=play_mode)
assert "motion_time_out" in cfg.terminations, (
f"Task {task_id} (play={play_mode}) missing 'motion_time_out' termination"
)
term = cfg.terminations["motion_time_out"]
assert term.time_out is True
assert term.func is mdp.motion_time_out
Loading