diff --git a/motrix_env_core/src/motrix_env_core/manager/observations.py b/motrix_env_core/src/motrix_env_core/manager/observations.py index 24fe92cc8..57ad0edc9 100644 --- a/motrix_env_core/src/motrix_env_core/manager/observations.py +++ b/motrix_env_core/src/motrix_env_core/manager/observations.py @@ -27,6 +27,9 @@ class ObservationTermCfg(abc.ABC): """Configuration that creates one environment-local observation term.""" + history_length: int = 0 + flatten_history_dim: bool = True + @abc.abstractmethod def __call__(self, ctx: BuildContext) -> ObsTerm: """Assemble the runtime term (dispatch plus static arguments).""" @@ -59,7 +62,8 @@ def __post_init__(self) -> None: class ManagerObservationGroupCfg: """Typed declaration group for one named observation group's terms.""" - history_length: int = 1 + history_length: int | None = None + flatten_history_dim: bool = True def to_dict(self) -> dict[str, ObservationTermCfg]: """Return observation term configs keyed by their declaration names.""" @@ -95,6 +99,16 @@ class ObservationTermEntry: name: str term: ObsTerm size: int + history_length: int = 0 + flatten_history_dim: bool = True + + @property + def output_shape(self) -> tuple[int, ...]: + if self.history_length == 0: + return (self.size,) + if self.flatten_history_dim: + return (self.history_length * self.size,) + return (self.history_length, self.size) @dataclass(frozen=True) @@ -102,7 +116,36 @@ class ObservationGroupEntry: name: str terms: tuple[ObservationTermEntry, ...] size: int - history_length: int = 1 + + @property + def output_shape(self) -> tuple[int, ...]: + return (*self.terms[0].output_shape[:-1], sum(term.output_shape[-1] for term in self.terms)) + + @property + def observation_spec(self) -> ObservationGroupSpec: + shape = self.output_shape + if len(shape) == 2: + return ObservationGroupSpec( + gym.spaces.Box(-np.inf, np.inf, (self.size,), dtype=np.float32), + shape[0], + flatten_history_dim=False, + ) + if len(self.terms) == 1: + term = self.terms[0] + return ObservationGroupSpec( + gym.spaces.Box(-np.inf, np.inf, (term.size,), dtype=np.float32), + max(1, term.history_length), + term.flatten_history_dim if term.history_length else True, + ) + # Term-major windows cannot be transported as uniform group-frame histories. + return ObservationGroupSpec(gym.spaces.Box(-np.inf, np.inf, self.output_shape, dtype=np.float32)) + + +def _validate_history_length(length: int, context: str) -> None: + if not isinstance(length, numbers.Integral) or isinstance(length, (bool, np.bool_)): + raise TypeError(f"{context} history_length must be an integer.") + if length < 0: + raise ValueError(f"{context} history_length must be non-negative.") def create_observation_groups( @@ -114,6 +157,10 @@ def create_observation_groups( for group_name, term_cfgs in cfg.observation_cfgs().items(): entries = [] group_size = 0 + group_cfg = cfg.observation_group_cfgs()[group_name] + group_history = group_cfg.history_length if isinstance(group_cfg, ManagerObservationGroupCfg) else None + if group_history is not None: + _validate_history_length(group_history, f"Observation group {group_name!r}") for term_name, term_cfg in term_cfgs.items(): created = term_cfg(ctx) if not isinstance(created, ObsTerm): @@ -127,16 +174,25 @@ def create_observation_groups( *canonicalize_term_args(created.args, context=f"Observation term {group_name}.{term_name}"), ) resolved_size = int(term.size) - entries.append(ObservationTermEntry(term_name, term, resolved_size)) + history_length = term_cfg.history_length if group_history is None else group_history + flatten_history_dim = ( + group_cfg.flatten_history_dim + if isinstance(group_cfg, ManagerObservationGroupCfg) and group_history is not None + else term_cfg.flatten_history_dim + ) + if group_history is None: + _validate_history_length(history_length, f"Observation term {group_name}.{term_name}") + entries.append(ObservationTermEntry(term_name, term, resolved_size, history_length, flatten_history_dim)) group_size += resolved_size if entries: - group_cfg = cfg.observation_group_cfgs()[group_name] - history_length = group_cfg.history_length if isinstance(group_cfg, ManagerObservationGroupCfg) else 1 - if not isinstance(history_length, numbers.Integral) or isinstance(history_length, (bool, np.bool_)): - raise TypeError("Observation history_length must be an integer.") - if history_length < 1: - raise ValueError("Observation history_length must be at least 1.") - groups[group_name] = ObservationGroupEntry(group_name, tuple(entries), group_size, history_length) + prefix = entries[0].output_shape[:-1] + if any(entry.output_shape[:-1] != prefix for entry in entries): + raise ValueError( + f"Observation group {group_name!r} term outputs cannot concatenate along the last dimension: " + f"{[(entry.name, entry.output_shape) for entry in entries]}. " + "Use flattened histories or matching non-flattened history lengths." + ) + groups[group_name] = ObservationGroupEntry(group_name, tuple(entries), group_size) if "policy" not in groups: raise ValueError("Manager environment config requires a 'policy' observation group.") return groups @@ -181,35 +237,31 @@ class ObservationManager: def __init__(self, groups: dict[str, ObservationGroupEntry], num_envs: int) -> None: self.groups = groups self.num_envs = num_envs - specs = { - name: ObservationGroupSpec( - gym.spaces.Box(-np.inf, np.inf, (group.size,), dtype=np.float32), group.history_length - ) - for name, group in groups.items() - } - self.spec = ObservationSpec(specs) + self.spec = ObservationSpec({name: group.observation_spec for name, group in groups.items()}) self._frame_spec = ObservationSpec( - {name: ObservationGroupSpec(group.frame_space) for name, group in self.spec.groups.items()} + { + name: ObservationGroupSpec(gym.spaces.Box(-np.inf, np.inf, (group.size,), dtype=np.float32)) + for name, group in groups.items() + } ) self._history_reset = torch.ones(num_envs, dtype=torch.bool) - self._stack_buffer = _SwapObsBuffer((self._zeros(self.spec), self._zeros(self.spec))) - has_history = any(group.history_length > 1 for group in self.groups.values()) + current_only = all( + term.history_length <= 1 and (term.flatten_history_dim or term.history_length == 0) + for group in groups.values() + for term in group.terms + ) self._frame_buffer = ( - _SwapObsBuffer( - ( - self._zeros(self._frame_spec), - self._zeros(self._frame_spec), - ) - ) - if has_history - else self._stack_buffer + self._stack_buffer + if current_only + else _SwapObsBuffer((self._zeros(self._frame_spec), self._zeros(self._frame_spec))) ) self._scratch = self._zeros(self._frame_spec) self._history = { - name: torch.zeros((self.num_envs, group.history_length, group.size), dtype=torch.float32) - for name, group in self.groups.items() - if group.history_length > 1 + (name, term.name): torch.zeros((num_envs, term.history_length, term.size), dtype=torch.float32) + for name, group in groups.items() + for term in group.terms + if term.history_length > 1 } def bind_observe_kernel(self, observe_kernel: Callable[[EnvObs], None]) -> None: @@ -251,43 +303,55 @@ def publish_reset(self, env_ids: torch.Tensor) -> None: frame = self._scratch output = self._stack_buffer.current for name, group in self.groups.items(): - values = frame[name][reset] - destination = output[name] - if group.history_length == 1: - destination[reset] = values - else: - initialized = repeat_observation(values, group.history_length) - self._history[name][reset] = initialized - destination[reset] = initialized.flatten(1) + parts = [] + offset = 0 + for term in group.terms: + values = frame[name][reset, offset : offset + term.size] + offset += term.size + window = repeat_observation(values, max(1, term.history_length)) + if term.history_length > 1: + self._history[name, term.name][reset] = window + parts.append(self._term_output(term, window)) + output[name][reset] = torch.cat(parts, dim=-1) self._history_reset[env_ids] = False + @staticmethod + def _term_output(term: ObservationTermEntry, window: torch.Tensor) -> torch.Tensor: + return window.flatten(1) if term.flatten_history_dim or term.history_length == 0 else window + def commit(self) -> None: """Publish exactly one control-step endpoint, repeat-filling new episodes.""" self._observe_kernel(self.frame_output) - frame = self._frame_buffer.current - output = self._stack_buffer.current for name, group in self.groups.items(): - values = frame[name] - destination = output[name] - if group.history_length == 1: - if destination is not values: - destination.copy_(values) - else: - history = self._history[name] - history.copy_(append_observation(history, values, self._history_reset)) - destination.copy_(history.flatten(1)) + parts = [] + offset = 0 + for term in group.terms: + values = self.frame_output[name][:, offset : offset + term.size] + offset += term.size + if term.history_length > 1: + window = self._history[name, term.name] + window.copy_(append_observation(window, values, self._history_reset)) + else: + window = values.unsqueeze(1) + parts.append(self._term_output(term, window)) + self.observation[name].copy_(torch.cat(parts, dim=-1)) self._history_reset.fill_(False) def preview(self, env_ids: torch.Tensor) -> FinalObs: - """Return owned sparse endpoint windows without committing history.""" + """Append the current endpoint to owned windows without committing history.""" self._observe_kernel(self._scratch) - frame = self._scratch stacked = {} for name, group in self.groups.items(): - values = frame[name][env_ids] - stacked[name] = ( - values - if group.history_length == 1 - else append_observation(self._history[name][env_ids], values).flatten(1) - ) + parts = [] + offset = 0 + for term in group.terms: + values = self._scratch[name][env_ids, offset : offset + term.size] + offset += term.size + window = ( + append_observation(self._history[name, term.name][env_ids], values) + if term.history_length > 1 + else values.unsqueeze(1) + ) + parts.append(self._term_output(term, window)) + stacked[name] = torch.cat(parts, dim=-1) return FinalObs(env_ids.clone(), EnvObs(stacked)) diff --git a/motrix_env_core/src/motrix_env_core/manager/resolver.py b/motrix_env_core/src/motrix_env_core/manager/resolver.py index 40b2d0dd8..7ef555e40 100644 --- a/motrix_env_core/src/motrix_env_core/manager/resolver.py +++ b/motrix_env_core/src/motrix_env_core/manager/resolver.py @@ -686,7 +686,7 @@ def _validate_observation_spaces(self, groups: dict[str, ObservationGroupEntry]) raise ValueError("Environment observation groups must match the manager config's groups.") for name, group in groups.items(): space = spec[name].space - expected = (group.size * group.history_length,) + expected = group.output_shape if space.shape != expected: raise ValueError( f"Observation group {name!r} space has shape {space.shape}, manager config produces {expected}." diff --git a/motrix_env_core/src/motrix_env_core/observations.py b/motrix_env_core/src/motrix_env_core/observations.py index 6af9df716..90c137eb7 100644 --- a/motrix_env_core/src/motrix_env_core/observations.py +++ b/motrix_env_core/src/motrix_env_core/observations.py @@ -13,23 +13,35 @@ @dataclass(frozen=True) class ObservationGroupSpec: - """One flat frame and its oldest-to-newest, repeat-filled history.""" + """An observation payload, optionally a uniform oldest-to-newest history. + + A manager group with multiple term-major windows uses history_length=1 and + describes the full payload as frame_space; it cannot be deduplicated as one + shared chronological frame sequence. + """ frame_space: gym.spaces.Box history_length: int = 1 + flatten_history_dim: bool = True def __post_init__(self) -> None: if not isinstance(self.history_length, Integral) or isinstance(self.history_length, bool): raise TypeError("Observation history_length must be an integer.") if self.history_length < 1: raise ValueError("Observation history_length must be at least 1.") - if len(self.frame_space.shape) != 1: - raise ValueError("Observation frame_space must be one-dimensional.") + if self.history_length > 1 and len(self.frame_space.shape) != 1: + raise ValueError("Observation history frame_space must be one-dimensional.") @property def space(self) -> gym.spaces.Box: - """Derive the final flat space without mutating the static description.""" + """Derive the published space without mutating the static description.""" space = self.frame_space + if not self.flatten_history_dim: + return gym.spaces.Box( + np.repeat(space.low[None], self.history_length, axis=0), + np.repeat(space.high[None], self.history_length, axis=0), + dtype=space.dtype, + ) if self.history_length == 1: return space return gym.spaces.Box( diff --git a/motrix_env_core/tests/test_manager_env.py b/motrix_env_core/tests/test_manager_env.py index c3228bdf8..fcc542811 100644 --- a/motrix_env_core/tests/test_manager_env.py +++ b/motrix_env_core/tests/test_manager_env.py @@ -330,8 +330,21 @@ def _counter_command(env: _ManagerEnv) -> _CounterCommand: return command +def _policy_window(values: torch.Tensor, history_length: int) -> torch.Tensor: + """Read declared widths (2, 1, 1) as term-major chronological windows.""" + return torch.cat( + [ + part.reshape(values.shape[0], history_length, width) + for part, width in zip( + values.split([2 * history_length, history_length, history_length], dim=-1), (2, 1, 1) + ) + ], + dim=-1, + ) + + @pytest.mark.parametrize("policy_h,value_h", [(1, 1), (3, 1), (2, 3)]) -def test_history_frames_time_major_and_partial_episode_reset(policy_h: int, value_h: int) -> None: +def test_history_terms_oldest_to_newest_and_partial_episode_reset(policy_h: int, value_h: int) -> None: cfg = _ManagerEnvCfg( observations={ "policy": _ManagerPolicyObsCfg(history_length=policy_h), @@ -344,20 +357,21 @@ def test_history_frames_time_major_and_partial_episode_reset(policy_h: int, valu state = env.state assert env.observation_spec.policy.space.shape == (4 * policy_h,) assert env.observation_spec.value.space.shape == (value_h,) - assert env.observation_spec.policy.frame_space.shape == (4,) - frames = [env.state.obs.policy[:, -4:].clone()] - torch.testing.assert_close(state.obs.policy.reshape(2, policy_h, 4), frames[0][:, None].expand(-1, policy_h, -1)) + assert env.observation_spec.policy.frame_space.shape == (4 * policy_h,) + assert env.observation_spec.policy.history_length == 1 + frames = [_policy_window(env.state.obs.policy, policy_h)[:, -1].clone()] + torch.testing.assert_close(_policy_window(state.obs.policy, policy_h), frames[0][:, None].expand(-1, policy_h, -1)) for action in (0.1, 0.2, 0.3): state = env.step(torch.full((2, 1), action)) - frames.append(env.state.obs.policy[:, -4:].clone()) + frames.append(_policy_window(env.state.obs.policy, policy_h)[:, -1].clone()) expected = ([frames[0]] * policy_h + frames[1:])[-policy_h:] - torch.testing.assert_close(state.obs.policy.reshape(2, policy_h, 4), torch.stack(expected, dim=1)) + torch.testing.assert_close(_policy_window(state.obs.policy, policy_h), torch.stack(expected, dim=1)) untouched = state.obs.policy[1].clone() - frame_untouched = env.state.obs.policy[:, -4:][1].clone() + frame_untouched = _policy_window(env.state.obs.policy, policy_h)[:, -1][1].clone() env.reset(torch.tensor([0])) env.reset_observation(env.state, env_ids=torch.tensor([0])) - current = env.state.obs.policy[:, -4:] - torch.testing.assert_close(env.state.obs.policy[0].reshape(policy_h, 4), current[0].expand(policy_h, -1)) + current = _policy_window(env.state.obs.policy, policy_h)[:, -1] + torch.testing.assert_close(_policy_window(env.state.obs.policy, policy_h)[0], current[0].expand(policy_h, -1)) torch.testing.assert_close(env.state.obs.policy[1], untouched) torch.testing.assert_close(current[1], frame_untouched) @@ -376,15 +390,15 @@ def test_explicit_sim_only_reset_waits_for_next_control_step(history_length: int torch.testing.assert_close(env.state.obs.policy, published) torch.testing.assert_close(env.state.episode_steps, steps) state = env.step(torch.full((2, 1), 0.2)) - window = state.obs.policy.reshape(2, history_length, 4) - torch.testing.assert_close(window[:, :-1], published.reshape(2, history_length, 4)[:, 1:]) + window = _policy_window(state.obs.policy, history_length) + torch.testing.assert_close(window[:, :-1], _policy_window(published, history_length)[:, 1:]) torch.testing.assert_close(state.episode_steps, steps + 1) assert window[1, -1, 1] == pytest.approx(-1.0 + env.cfg.ctrl_dt) assert window[1, -1, 0] == pytest.approx(1.6) # Explicit whole-batch publication is an additional frame, not a cache read. snapshot = window.clone() env.compute_observation(state) - updated = state.obs.policy.reshape(2, history_length, 4) + updated = _policy_window(state.obs.policy, history_length) torch.testing.assert_close(updated[:, :-1], snapshot[:, 1:]) torch.testing.assert_close(updated[:, -1], snapshot[:, -1]) @@ -399,7 +413,7 @@ def test_history_final_preview_owned_frames_and_sim_only_reset() -> None: env.initialize() state = env.state state = env.step(torch.full((2, 1), 0.1)) - prefix = state.obs.policy.reshape(2, 3, 4).clone() + prefix = _policy_window(state.obs.policy, 3).clone() # Request a simulator-only reset during the real control step. It changes # the endpoint command but must retain this episode's historical prefix. evaluate = env._task_program.evaluate_kernel @@ -413,15 +427,15 @@ def request_sim_reset(weights, buffers, outputs): state = env.step(torch.full((2, 1), 0.2)) final = state.final_obs assert final is not None - final_frame = final.obs.policy[:, -4:] + final_frame = _policy_window(final.obs.policy, 3)[:, -1] torch.testing.assert_close(final.env_ids, torch.tensor([0])) expected = torch.cat((prefix[[0], 1:], final_frame[:, None]), dim=1) - torch.testing.assert_close(final.obs.policy.reshape(1, 3, 4), expected) - frame = env.state.obs.policy[:, -4:] + torch.testing.assert_close(_policy_window(final.obs.policy, 3), expected) + frame = _policy_window(env.state.obs.policy, 3)[:, -1] assert state.episode_steps[1] == 2 assert frame[1, 1] == -1.0 - torch.testing.assert_close(state.obs.policy[0].reshape(3, 4), frame[0].expand(3, -1)) - torch.testing.assert_close(state.obs.policy[1].reshape(3, 4)[:-1], prefix[1, 1:]) + torch.testing.assert_close(_policy_window(state.obs.policy, 3)[0], frame[0].expand(3, -1)) + torch.testing.assert_close(_policy_window(state.obs.policy, 3)[1][:-1], prefix[1, 1:]) saved = final_frame.clone() state.episode_steps.zero_() env.step(torch.full((2, 1), 0.1)) @@ -447,11 +461,11 @@ class _NamedObservationsCfg(ManagerObservationsCfg): assert env.observation_spec["goal"].space.shape == (4 * history_length,) assert initial.obs.value is None torch.testing.assert_close( - initial.obs["goal"].reshape(2, history_length, 4), - initial.obs["goal"][:, -4:][:, None].expand(-1, history_length, -1), + _policy_window(initial.obs["goal"], history_length), + _policy_window(initial.obs["goal"], history_length)[:, -1][:, None].expand(-1, history_length, -1), ) state = env.step(torch.full((2, 1), 0.1)) - prefix = state.obs["goal"].reshape(2, history_length, 4).clone() + prefix = _policy_window(state.obs["goal"], history_length).clone() state.episode_steps[0] = 2 state = env.step(torch.full((2, 1), 0.2)) final = state.final_obs @@ -459,8 +473,8 @@ class _NamedObservationsCfg(ManagerObservationsCfg): torch.testing.assert_close(final.env_ids, torch.tensor([0])) expected_endpoint = torch.tensor([[1.6, -1.0 + 2 * cfg.ctrl_dt, 0.4, 0.0]]) expected_final = torch.cat((prefix[[0], 1:], expected_endpoint[:, None]), dim=1) - torch.testing.assert_close(final.obs["goal"].reshape(1, history_length, 4), expected_final) - goal = state.obs["goal"].reshape(2, history_length, 4) + torch.testing.assert_close(_policy_window(final.obs["goal"], history_length), expected_final) + goal = _policy_window(state.obs["goal"], history_length) torch.testing.assert_close(goal[0], goal[0, -1:].expand(history_length, -1)) torch.testing.assert_close(goal[1, :-1], prefix[1, 1:]) saved_final = final.obs["goal"].clone() @@ -658,7 +672,7 @@ class _MultipleActionsCfg(ManagerActionsCfg): np.testing.assert_array_equal(env.action_terms["test"].state.source, actions[:, :1]) np.testing.assert_array_equal(env.action_terms["second"].state.source, actions[:, 1:]) env._refresh_sim_reads() - env._task_program.observe_kernel(env.observation_manager.frame_output) + env.observation_manager.commit() np.testing.assert_array_equal(state.obs.policy, actions) assert [(term.name, term.input_slice) for term in env.manager_layout.actions] == [ ("test", slice(0, 1)), @@ -1263,3 +1277,55 @@ def test_reward_terms_read_the_current_transition_termination() -> None: env.step(torch.full((2, 1), 0.9, dtype=torch.float32)) assert env.state.terminated.all() torch.testing.assert_close(env.state.reward_terms["penalty"], torch.full((2,), -1.0)) + + +@pytest.mark.parametrize("override", [None, 0, 1, 3]) +def test_term_histories_and_group_override(override: int | None) -> None: + group = _ManagerPolicyObsCfg( + history_length=override, + injected=_InjectedObservationCfg(scale=3.0, history_length=2), + derived=_DerivedObservationCfg(history_length=3), + ) + env = ManagerEnv(_ManagerEnvCfg(observations={"policy": group}), num_envs=2) + env.physics_step = lambda: None + env.initialize() + env.step(torch.full((2, 1), 0.1)) + state = env.step(torch.full((2, 1), 0.2)) + lengths = (2, 3, 1) if override is None else (max(1, override),) * 3 + parts = state.obs.policy.split([2 * lengths[0], lengths[1], lengths[2]], dim=-1) + torch.testing.assert_close(parts[0][:, -2], torch.full((2,), 1.6)) + torch.testing.assert_close(parts[1][:, -1], torch.full((2,), 0.4)) + torch.testing.assert_close(parts[2][:, -1], torch.arange(2, dtype=torch.float32)) + assert env.observation_spec.policy.space.shape == (sum((2 * lengths[0], *lengths[1:])),) + assert env.observation_spec.policy.history_length == 1 + if override is None: + torch.testing.assert_close( + parts[0][0], torch.tensor([1.3, -1 + env.cfg.ctrl_dt, 1.6, -1 + 2 * env.cfg.ctrl_dt]) + ) + torch.testing.assert_close(parts[1][0], torch.tensor([0.0, 0.2, 0.4])) + + +@pytest.mark.parametrize("length", [0, 1, 3]) +def test_nonflattened_group_history_matches_observation_spec(length: int) -> None: + env = ManagerEnv( + _ManagerEnvCfg(observations={"policy": _ManagerPolicyObsCfg(history_length=length, flatten_history_dim=False)}), + num_envs=2, + ) + env.physics_step = lambda: None + env.initialize() + shape = (4,) if length == 0 else (length, 4) + assert env.observation_spec.policy.space.shape == shape + assert env.observation_spec.policy.frame_space.shape == (4,) + assert env.observation_spec.policy.history_length == max(1, length) + assert env.state.obs.policy.shape == (2, *shape) + env.step(torch.full((2, 1), 0.1)) + final = env.observation_manager.preview(torch.tensor([1])) + assert final.obs.policy.shape == (1, *shape) + + +def test_incompatible_nonflattened_term_histories_fail_at_config_boundary() -> None: + group = _ManagerPolicyObsCfg( + injected=_InjectedObservationCfg(scale=3.0, history_length=3, flatten_history_dim=False) + ) + with pytest.raises(ValueError, match="cannot concatenate"): + ManagerEnv(_ManagerEnvCfg(observations={"policy": group}), num_envs=2) diff --git a/motrix_env_core/tests/test_observation_manager.py b/motrix_env_core/tests/test_observation_manager.py index c193d28c8..4c0ee1bdb 100644 --- a/motrix_env_core/tests/test_observation_manager.py +++ b/motrix_env_core/tests/test_observation_manager.py @@ -5,12 +5,23 @@ import torch from motrix_env_core.array.env import EnvObs -from motrix_env_core.manager.observations import ObservationGroupEntry, ObservationManager +from motrix_env_core.manager.observations import ( + ObservationGroupEntry, + ObservationManager, + ObservationTermEntry, + ObsTerm, +) -@pytest.mark.parametrize("history_length", [1, 3]) +def _unused_observe() -> None: + pass + + +@pytest.mark.parametrize("history_length", [0, 1, 3]) def test_observation_manager_owns_commit_reset_and_preview(history_length: int) -> None: - manager = ObservationManager({"policy": ObservationGroupEntry("policy", (), 2, history_length)}, 2) + term = ObservationTermEntry("state", ObsTerm(2, _unused_observe), 2, history_length) + manager = ObservationManager({"policy": ObservationGroupEntry("policy", (term,), 2)}, 2) + history_length = max(1, history_length) source = torch.tensor([[1.0, 2.0], [3.0, 4.0]]) evaluations = 0 @@ -45,3 +56,49 @@ def observe(outputs: EnvObs) -> None: manager.begin_step() manager.commit() torch.testing.assert_close(preview.obs.policy, saved) + + +@pytest.mark.parametrize("history_length", [1, 3]) +def test_uniform_unflattened_terms_publish_chronological_frames(history_length: int) -> None: + terms = ( + ObservationTermEntry("position", ObsTerm(2, _unused_observe), 2, history_length, False), + ObservationTermEntry("velocity", ObsTerm(1, _unused_observe), 1, history_length, False), + ) + group = ObservationGroupEntry("policy", terms, 3) + manager = ObservationManager({"policy": group}, 2) + spec = manager.spec.policy + assert spec.frame_space.shape == (3,) + assert spec.history_length == history_length + assert spec.space.shape == (history_length, 3) + source = torch.tensor([[1.0, 2.0, 100.0], [3.0, 4.0, 200.0]]) + + def observe(outputs: EnvObs) -> None: + outputs.policy.copy_(source) + + manager.bind_observe_kernel(observe) + manager.publish_reset(torch.arange(2)) + expected = source[:, None].expand(-1, history_length, -1).clone() + initial = manager.observation.policy + torch.testing.assert_close(initial, expected) + source.add_(10) + preview = manager.preview(torch.tensor([1])) + endpoint = torch.cat((expected[[1], 1:], source[[1], None]), dim=1) + torch.testing.assert_close(preview.obs.policy, endpoint) + torch.testing.assert_close(initial, expected) + manager.begin_step() + manager.reset(torch.tensor([0])) + manager.commit() + expected = torch.cat((expected[:, 1:], source[:, None]), dim=1) + expected[0] = source[0].expand(history_length, -1) + torch.testing.assert_close(manager.observation.policy, expected) + # Flattening at the policy boundary retains complete frames, not term blocks. + torch.testing.assert_close(manager.observation.policy.flatten(1), expected.flatten(1)) + held = manager.observation.policy.clone() + saved_preview = preview.obs.policy.clone() + source.add_(10) + manager.publish_reset(torch.tensor([1])) + torch.testing.assert_close(manager.observation.policy[0], held[0]) + torch.testing.assert_close(manager.observation.policy[1], source[1].expand(history_length, -1)) + manager.begin_step() + manager.commit() + torch.testing.assert_close(preview.obs.policy, saved_preview) diff --git a/motrix_env_core/tests/test_observations.py b/motrix_env_core/tests/test_observations.py index bffdaea02..62360c84b 100644 --- a/motrix_env_core/tests/test_observations.py +++ b/motrix_env_core/tests/test_observations.py @@ -28,6 +28,15 @@ def test_static_spec_derives_time_major_bounds_and_optional_value() -> None: group.history_length = 2 +@pytest.mark.parametrize("length", [1, 3]) +def test_nonflattened_history_spec_preserves_time_axis(length: int) -> None: + frame = gym.spaces.Box(np.array([-1, -2], dtype=np.float32), np.array([3, 4], dtype=np.float32)) + spec = ObservationGroupSpec(frame, length, flatten_history_dim=False) + assert spec.space.shape == (length, 2) + np.testing.assert_array_equal(spec.space.low, np.repeat(frame.low[None], length, axis=0)) + np.testing.assert_array_equal(spec.space.high, np.repeat(frame.high[None], length, axis=0)) + + def test_named_groups_and_semantic_conveniences_share_storage() -> None: group = ObservationGroupSpec(gym.spaces.Box(-1, 1, (2,))) spec = ObservationSpec({"policy": group, "goal": group}) diff --git a/motrix_envs/tests/test_walk_randomization.py b/motrix_envs/tests/test_walk_randomization.py index 8426c285e..df8d34bb2 100644 --- a/motrix_envs/tests/test_walk_randomization.py +++ b/motrix_envs/tests/test_walk_randomization.py @@ -12,7 +12,12 @@ import torch from motrix_env_core.manager import ManagerEnv -from motrix_env_core.manager.observations import ObservationGroupEntry, ObservationManager +from motrix_env_core.manager.observations import ( + ObservationGroupEntry, + ObservationManager, + ObservationTermEntry, + ObsTerm, +) from motrix_env_core.mdp.action import JointPositionActionCfg, JointPositionActionState, JointPositionActionTerm from motrix_envs.locomotion.humanoid.g1 import make_g129dof_walk_flat_cfg from motrix_envs.locomotion.humanoid.walk_manager_mdp.randomization import WalkRandomizationCfg @@ -68,7 +73,10 @@ def _tiny_delay_manager(num_envs: int = 2, num_actuators: int = 3, lo: int = 0, env._truncated = torch.zeros(num_envs, dtype=torch.bool) env._episode_steps = torch.zeros(num_envs, dtype=torch.long) env._final_obs = None - env.observation_manager = ObservationManager({"policy": ObservationGroupEntry("policy", (), 1)}, num_envs) + observation_term = ObservationTermEntry("unused", ObsTerm(1, lambda: None), 1) + env.observation_manager = ObservationManager( + {"policy": ObservationGroupEntry("policy", (observation_term,), 1)}, num_envs + ) env._compiled_manager_program = SimpleNamespace( context=SimpleNamespace( terminated=env.termination_manager.terminated, diff --git a/motrix_rl_appo/src/motrix_rl_appo/collector.py b/motrix_rl_appo/src/motrix_rl_appo/collector.py index a13b7647e..7ddc12044 100644 --- a/motrix_rl_appo/src/motrix_rl_appo/collector.py +++ b/motrix_rl_appo/src/motrix_rl_appo/collector.py @@ -29,6 +29,23 @@ from motrix_rl_appo.transport import CollectorConnection, CollectorMetadata, GpuRingConnection, chunk_schema +def collector_metadata(env: ArrayEnv) -> CollectorMetadata: + """Resolve network dimensions, rejecting unsupported non-vector observations.""" + spec = env.observation_spec + if len(spec.policy.space.shape) != 1 or len(spec.value_or_policy.space.shape) != 1: + raise ValueError( + "APPO requires flat vector observations; enable flatten_history_dim for observation histories." + ) + return CollectorMetadata( + spec.policy.space.shape[0], + spec.value_or_policy.space.shape[0], + env.action_space.shape[0], + spec.policy.history_length, + spec.value_or_policy.history_length, + spec.value is None, + ) + + def publish_chunk( ring: HostTransitionRing | GpuIpcTransitionRing, chunk: dict[str, torch.Tensor], @@ -100,14 +117,7 @@ def __init__( ) self._reward_terms = TensorMetricWindow({}, default_reduction="mean") spec = env.observation_spec - self.dims = CollectorMetadata( - spec.policy.space.shape[0], - spec.value_or_policy.space.shape[0], - env.action_space.shape[0], - spec.policy.history_length, - spec.value_or_policy.history_length, - spec.value is None, - ) + self.dims = collector_metadata(env) schema = chunk_schema( cfg.rollout_steps, spec.policy.frame_space.shape[0], @@ -213,14 +223,7 @@ def run(self) -> None: raise TypeError("APPO requires a Torch ArrayEnv frontend") if not isinstance(env.action_space, gym.spaces.Box) or len(env.action_space.shape) != 1: raise TypeError("APPO requires a vector Box action space") - dims = CollectorMetadata( - env.observation_spec.policy.space.shape[0], - env.observation_spec.value_or_policy.space.shape[0], - env.action_space.shape[0], - env.observation_spec.policy.history_length, - env.observation_spec.value_or_policy.history_length, - env.observation_spec.value is None, - ) + dims = collector_metadata(env) self.startup.send(dims) if not self.startup.poll(self.cfg.worker_timeout): raise TimeoutError("APPO learner did not complete collector handshake") diff --git a/motrix_rl_appo/src/motrix_rl_appo/trainer.py b/motrix_rl_appo/src/motrix_rl_appo/trainer.py index fc50e6ff5..1045e3bc6 100644 --- a/motrix_rl_appo/src/motrix_rl_appo/trainer.py +++ b/motrix_rl_appo/src/motrix_rl_appo/trainer.py @@ -36,7 +36,7 @@ WeightChannelShared, ) from motrix_rl.worker import WorkerHandle, WorkerRuntime -from motrix_rl_appo.collector import CollectorWorker +from motrix_rl_appo.collector import CollectorWorker, collector_metadata from motrix_rl_appo.config import AppoCfg from motrix_rl_appo.history import ChunkHistory from motrix_rl_appo.learner import APPOLearner @@ -340,9 +340,8 @@ def play(self, policy: str) -> None: ) if not isinstance(env, ArrayEnv): raise TypeError("APPO requires a Torch ArrayEnv frontend") - actor = build_actor( - context.rl_cfg.actor, env.observation_spec.policy.space.shape[0], env.action_space.shape[0] - ).to(device) + dims = collector_metadata(env) + actor = build_actor(context.rl_cfg.actor, dims.obs_dim, dims.action_dim).to(device) checkpoint = torch.load(policy, map_location=device, weights_only=False) actor.load_state_dict(checkpoint["learner"]["actor"]) actor.eval() diff --git a/motrix_rl_appo/tests/test_appo_history.py b/motrix_rl_appo/tests/test_appo_history.py index e82e72ff1..591c676fc 100644 --- a/motrix_rl_appo/tests/test_appo_history.py +++ b/motrix_rl_appo/tests/test_appo_history.py @@ -7,16 +7,30 @@ import numpy as np import pytest import torch -from motrix_rl_appo.collector import ChunkCollector +from motrix_rl_appo.collector import ChunkCollector, collector_metadata from motrix_rl_appo.config import AppoCfg from motrix_rl_appo.history import ChunkHistory from motrix_rl_appo.transport import CollectorMetadata, chunk_schema, take_chunk from motrix_env_core.array.env import ArrayEnvState, EnvObs -from motrix_env_core.manager.observations import ObservationGroupEntry, ObservationManager +from motrix_env_core.manager.observations import ( + ObservationGroupEntry, + ObservationManager, + ObservationTermEntry, + ObsTerm, +) from motrix_rl.transport.ring import HostTransitionRing +def _unused_observe() -> None: + pass + + +def _history_group(name: str, size: int, history: int) -> ObservationGroupEntry: + entry = ObservationTermEntry("state", ObsTerm(size, _unused_observe), size, history) + return ObservationGroupEntry(name, (entry,), size) + + class RecordingActor: def __init__(self) -> None: self.inputs: list[torch.Tensor] = [] @@ -36,9 +50,9 @@ class NoisyHistoryEnv: action_space = gym.spaces.Box(-np.inf, np.inf, (1,), dtype=np.float32) def __init__(self, history: int, value_history: int | None) -> None: - groups = {"policy": ObservationGroupEntry("policy", (), 2, history)} + groups = {"policy": _history_group("policy", 2, history)} if value_history is not None: - groups["value"] = ObservationGroupEntry("value", (), 3, value_history) + groups["value"] = _history_group("value", 3, value_history) self.manager = ObservationManager(groups, self.num_envs) self.observation_spec = self.manager.spec self.generator = torch.Generator().manual_seed(315) @@ -199,3 +213,15 @@ def test_history_one_schema_remains_direct(critic_uses_policy: bool) -> None: def test_history_metadata_rejects_invalid_stack_dimensions(dims: tuple[int, ...]) -> None: with pytest.raises(ValueError, match="multiples"): CollectorMetadata(*dims) + + +@pytest.mark.parametrize("name", ["policy", "value"]) +def test_appo_rejects_nonflattened_history_before_inferring_network_dimensions(name: str) -> None: + env = NoisyHistoryEnv(3, 2) + group = _history_group(name, 2, 3) + entry = group.terms[0] + env.observation_spec.groups[name] = ObservationGroupEntry( + name, (ObservationTermEntry(entry.name, entry.term, entry.size, 3, False),), 2 + ).observation_spec + with pytest.raises(ValueError, match="flat vector observations"): + collector_metadata(env) diff --git a/motrix_rl_supermimic/src/motrix_rl_supermimic/env.py b/motrix_rl_supermimic/src/motrix_rl_supermimic/env.py index 84c003b94..5264d8816 100644 --- a/motrix_rl_supermimic/src/motrix_rl_supermimic/env.py +++ b/motrix_rl_supermimic/src/motrix_rl_supermimic/env.py @@ -103,8 +103,10 @@ def __init__( if not cfg.world_model_state: raise TypeError("SuperMimicEnv requires world-model state terms") goal = self.observation_spec["goal"] - if goal.history_length != 1: - raise ValueError("MBRL goal observation must have history_length=1") + if len(goal.space.shape) != 1 or any( + term.history_length > 1 for term in self.observation_manager.groups["goal"].terms + ): + raise ValueError("MBRL goal observation must be flat without temporal history") reference = self.command_terms[cfg.reference_command] if not isinstance(reference, ReferenceCommand): raise TypeError("MBRL reference_command must select a ReferenceCommand") diff --git a/motrix_rl_supermimic/src/motrix_rl_supermimic/imagined_task.py b/motrix_rl_supermimic/src/motrix_rl_supermimic/imagined_task.py index b698911d6..96878eb1e 100644 --- a/motrix_rl_supermimic/src/motrix_rl_supermimic/imagined_task.py +++ b/motrix_rl_supermimic/src/motrix_rl_supermimic/imagined_task.py @@ -30,7 +30,7 @@ from motrix_env_core.manager.observations import ObsTerm, create_observation_groups from motrix_env_core.manager.resolver import ManagerTermResolver, ObservationTermCall from motrix_env_core.manager.rewards import RewardTerm, create_reward_terms -from motrix_env_core.observations import ObservationGroupSpec, ObservationSpec +from motrix_env_core.observations import ObservationSpec from motrix_rl_supermimic.imagination import ImaginationContextFactory, ImaginationTerm from motrix_rl_supermimic.world_context import WorldContext from motrix_rl_supermimic.world_state import WorldStateManager @@ -180,19 +180,27 @@ def __init__(self, cfg: SuperMimicEnvCfg, device: str) -> None: for name in ("policy", "value", "goal"): if name not in groups: raise ValueError(f"MBRL requires observation group {name!r}") - if groups["goal"].history_length != 1: - raise ValueError("MBRL goal observation must have history_length=1") + for name, group in groups.items(): + # Only frame-major group histories can be reconstructed from + # replay and advanced one frame at a time during imagination. + if ( + len(group.terms) > 1 + and any(term.history_length > 1 for term in group.terms) + and len(group.output_shape) != 2 + ): + raise ValueError( + f"MBRL imagined observations do not support mixed or term-major multi-term history: {name!r}" + ) + if any(term.history_length > 1 for term in groups["goal"].terms): + raise ValueError("MBRL goal observation must not contain temporal history") + if len(groups["goal"].output_shape) != 1: + raise ValueError("MBRL goal observation must be flat") action_space = Box( np.concatenate([term.action_space.low for term in actions.values()]), np.concatenate([term.action_space.high for term in actions.values()]), dtype=np.float32, ) - observation_spec = ObservationSpec( - groups={ - name: ObservationGroupSpec(Box(-float("inf"), float("inf"), (group.size,)), group.history_length) - for name, group in groups.items() - } - ) + observation_spec = ObservationSpec(groups={name: group.observation_spec for name, group in groups.items()}) resolver = ManagerTermResolver() def observation(group_name: str) -> ObsTerm: diff --git a/motrix_rl_supermimic/tests/test_collector_transport.py b/motrix_rl_supermimic/tests/test_collector_transport.py index 5e02fe8a5..4c21b832d 100644 --- a/motrix_rl_supermimic/tests/test_collector_transport.py +++ b/motrix_rl_supermimic/tests/test_collector_transport.py @@ -44,9 +44,11 @@ ), ], ) -def test_policy_bundle_and_transition_snapshots(monkeypatch, policy_device, weight_ipc): +@pytest.mark.parametrize("flatten_history", [True, False]) +def test_policy_bundle_and_transition_snapshots(monkeypatch, policy_device, weight_ipc, flatten_history): register_toy() cfg = ToyEnvCfg(goal_frames=2) + cfg.observations["policy"].flatten_history_dim = flatten_history manager = make_toy(num_envs=2, cfg=cfg) env = manager agent = AgentCfg(hidden=16, z_dim=8) diff --git a/motrix_rl_supermimic/tests/test_manager_task.py b/motrix_rl_supermimic/tests/test_manager_task.py index 04f70453b..9f6311646 100644 --- a/motrix_rl_supermimic/tests/test_manager_task.py +++ b/motrix_rl_supermimic/tests/test_manager_task.py @@ -172,6 +172,39 @@ def make_task(world_state: WorldStateManager | None = None) -> ImaginedTask: return ImaginedTask(cfg.for_imagined(), "cpu") +@pytest.mark.parametrize("kind", ["mixed", "term_major", "goal_history", "goal_nonflat"]) +def test_imagined_task_rejects_unsupported_temporal_layouts(kind: str) -> None: + cfg = replace(FixtureTaskCfg(), world_model_state={"state": _FixtureStateCfg(term=SimStateTerm(4))}) + if kind == "mixed": + + @configclass + class MixedPolicy(ManagerObservationGroupCfg): + current: ObservationTermCfg = _ObsCfg(size=2, fn=policy) + temporal: ObservationTermCfg = _ObsCfg(size=2, fn=policy, history_length=3) + + cfg.observations["policy"] = MixedPolicy() + message = "multi-term history" + elif kind == "term_major": + + @configclass + class TermMajorPolicy(ManagerObservationGroupCfg): + history_length: int = 3 + first: ObservationTermCfg = _ObsCfg(size=2, fn=policy) + second: ObservationTermCfg = _ObsCfg(size=1, fn=value) + + cfg.observations["policy"] = TermMajorPolicy() + message = "term-major" + elif kind == "goal_history": + cfg.observations["goal"].task.history_length = 2 + message = "goal observation" + else: + cfg.observations["goal"].task.history_length = 1 + cfg.observations["goal"].task.flatten_history_dim = False + message = "goal observation" + with pytest.raises(ValueError, match=message): + ImaginedTask(cfg.for_imagined(), "cpu") + + def test_runtime_slices_named_physical_inputs_and_preserves_all_gradients() -> None: class AgentTerm(SimViewTerm): pass diff --git a/motrix_rl_supermimic/tests/test_policy_history.py b/motrix_rl_supermimic/tests/test_policy_history.py new file mode 100644 index 000000000..a4fe92849 --- /dev/null +++ b/motrix_rl_supermimic/tests/test_policy_history.py @@ -0,0 +1,107 @@ +# Copyright Motphys Technology Co., Ltd. 2025, 2026 +# SPDX-License-Identifier: Apache-2.0 + +"""Real, replay and imagined policies consume oldest-first frame histories.""" + +import pytest +import torch +from _helpers import ingest_toy_steps, make_toy +from _supermimic_toy import ToyEnvCfg, _policy_term +from motrix_rl_supermimic.config import AgentCfg, SuperMimicCfg, TrainerCfg +from motrix_rl_supermimic.imagined_task import ImaginedTask +from motrix_rl_supermimic.learner import Learner +from motrix_rl_supermimic.networks import Policy + +from motrix_env_core.config import configclass +from motrix_env_core.manager.context import BuildContext, ManagerContext +from motrix_env_core.manager.observations import ManagerObservationGroupCfg, ObservationTermCfg, ObsTerm + + +def _policy_part(ctx: ManagerContext, out: torch.Tensor, start: int, stop: int) -> None: + frame = out.new_empty((ctx.env_id.numel(), 4)) + _policy_term(ctx, frame) + out.copy_(frame[:, start:stop]) + + +@configclass(kw_only=True) +class _PolicyPartCfg(ObservationTermCfg): + start: int + stop: int + + def __call__(self, ctx: BuildContext) -> ObsTerm: + return ObsTerm(self.stop - self.start, _policy_part, self.start, self.stop) + + +@configclass +class _FramePolicyCfg(ManagerObservationGroupCfg): + flatten_history_dim: bool = False + position: ObservationTermCfg = _PolicyPartCfg(start=0, stop=2) + velocity_action: ObservationTermCfg = _PolicyPartCfg(start=2, stop=4) + + +@pytest.mark.parametrize("history_length", [1, 3]) +def test_multiterm_frame_history_matches_replay_and_rolls_during_imagination(tmp_path, history_length: int) -> None: + env_cfg = ToyEnvCfg(goal_frames=2) + env_cfg.observations["policy"] = _FramePolicyCfg(history_length=history_length) + env = make_toy(num_envs=2, cfg=env_cfg) + env.initialize() + task = ImaginedTask(env.cfg.for_imagined(), "cpu") + spec = task.heads.observation_spec.policy + assert spec.frame_space.shape == (4,) + assert spec.space.shape == (history_length, 4) + assert spec.history_length == history_length + cfg = SuperMimicCfg( + agent=AgentCfg(hidden=8), + trainer=TrainerCfg(buffer_steps=8, pi_batch=4, horizon=3, critic_epochs=1, critic_minibatches=1), + ) + learner = Learner(cfg, task, env.num_envs, env.cfg.ctrl_dt, "cpu", tmp_path) + initial = env.state.obs["policy"].clone() + assert initial.shape == (2, history_length, 4) + torch.testing.assert_close(initial, initial[:, -1:].expand_as(initial)) + result = env.step(torch.full((2, 1), 0.1)) + if history_length > 1: + torch.testing.assert_close(result.obs["policy"][:, :-1], initial[:, 1:]) + frame = torch.cat((env.sim.position.sin(), env.sim.position.cos(), env.sim.velocity, torch.full((2, 1), 0.1)), -1) + torch.testing.assert_close(result.obs["policy"][:, -1], frame) + # A replay start owns raw state/action frames, not pre-flattened term windows. + ingest_toy_steps(learner, env, 5) + _, history = learner.starts() + reconstructed = learner.observation_history(history) + state, action = history["s"], history["a_prev"] + expected = torch.cat((state[..., :1].sin(), state[..., :1].cos(), state[..., 1:], action), -1) + torch.testing.assert_close(reconstructed, expected.gather(1, history["index"][..., None].expand_as(expected))) + assert reconstructed.shape == (cfg.trainer.pi_batch, history_length, 4) + assert learner.pi.obs_norm.mean.shape == (4,) + + seen = [] + + def capture_history(module: Policy, args: tuple[torch.Tensor, ...]) -> None: + seen.append(args[0].detach().clone()) + + handle = learner.pi.register_forward_pre_hook(capture_history) + try: + losses = learner.policy_update() + finally: + handle.remove() + assert all(torch.isfinite(value) for value in losses) + assert len(seen) == cfg.trainer.horizon + for previous, current in zip(seen, seen[1:]): + assert current.shape == reconstructed.shape + torch.testing.assert_close(current[:, :-1], previous[:, 1:]) + + +def test_policy_normalizes_each_frame_before_frame_major_flattening() -> None: + policy = Policy(2, 1, 1, hist=3, hidden=(4,)) + with torch.no_grad(): + policy.obs_norm.mean.copy_(torch.tensor([2.0, -3.0])) + policy.obs_norm.var.copy_(torch.tensor([4.0, 9.0])) + history = torch.arange(12, dtype=torch.float32).reshape(2, 3, 2) + goal = torch.ones(2, 1) + inputs = [] + handle = policy.dec.register_forward_pre_hook(lambda module, args: inputs.append(args[0].detach().clone())) + try: + policy(history, goal) + finally: + handle.remove() + expected = ((history - policy.obs_norm.mean) / policy.obs_norm.std()).reshape(2, 6) + torch.testing.assert_close(inputs[0][:, -6:], expected) diff --git a/wiki/design/manager/task-authoring.md b/wiki/design/manager/task-authoring.md index 6870ab9aa..90756c528 100644 --- a/wiki/design/manager/task-authoring.md +++ b/wiki/design/manager/task-authoring.md @@ -6,6 +6,16 @@ 内容覆盖任务文件组织、manager groups、term 创建、`SimDataQuery` 参数、kernel-data dataclass 字段和常用 term 接口。 运行时边界见 [Manager Runtime](./runtime.md)。 +## 观测历史配置 + +ObservationTermCfg提供`history_length=0`(不启用历史)和`flatten_history_dim=True`。Group的`history_length=None`默认尊重各term;显式设置非负整数则覆盖所有term的长度,同时应用group的flatten选项。每个term先形成自己的时间窗口,group按声明顺序term-major拼接。未展开的时间轴只有在各term输出rank/长度可拼接时允许,否则配置构造阶段报错。 + +长度0直接输出本次frame;长度1输出本次frame(不保留旧值),flatten=False时仍保留单帧时间轴。正常commit推进一次,preview用当前endpoint构造临时窗口但不推进;reset后的选中行用新观测repeat-fill,不暴露上一回合历史。这不采用mjlab/IsaacLab某些非更新调用返回旧buffer的语义。 + +单term组可向ObservationSpec派生统一history metadata。多term在相同正数历史长度且全部`flatten_history_dim=False`时,沿特征轴拼接为`(N,H,sum(term.size))`,metadata描述单帧宽度和H;运行时统一按term维护历史,再沿最后一维拼接;历史存储方式不改变对外的frame-major布局,也不要求下游传输完整历史。Policy可先按单帧特征归一化,再flatten最后两个轴。该布局也适用于SuperMimic:imagined observation head只计算单帧,rollout负责维护历史。 + +其他多term组发布完整term-major输入,metadata history=1,避免消费者把它错误重建为整组frame-major历史。各term先flatten再拼接与完整frame先堆叠再flatten的排列不同,checkpoint必须匹配所选布局。统一未flatten历史在policy边界flatten时保留完整frame的时间顺序;单term帧组(例如Wuji Actor)保持原排列。 + ## 1. 任务文件组织 一个简单任务通常拆成: