Skip to content
Merged
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
180 changes: 122 additions & 58 deletions motrix_env_core/src/motrix_env_core/manager/observations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)."""
Expand Down Expand Up @@ -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."""
Expand Down Expand Up @@ -95,14 +99,53 @@ 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)
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(
Expand All @@ -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):
Expand All @@ -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
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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))
2 changes: 1 addition & 1 deletion motrix_env_core/src/motrix_env_core/manager/resolver.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}."
Expand Down
20 changes: 16 additions & 4 deletions motrix_env_core/src/motrix_env_core/observations.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
Loading