Skip to content
Open
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
53 changes: 53 additions & 0 deletions brax/envs/wrappers/training.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,59 @@ def wrap(
return env


class HistoryWrapper(Wrapper):
"""Stacks the last ``context_length`` observations and actions.

The wrapped observation is the flattened concatenation of the last
``context_length`` ``(observation, previous_action)`` pairs, oldest first.
The previous action paired with the observation returned by ``reset`` is
zero, and steps before the start of the episode are zero padded.

The history lives in ``state.obs`` itself, so wrappers that replace the
observation on reset (such as ``AutoResetWrapper``) also reset the history.
Apply this wrapper to the base environment, before ``wrap`` or any other
batching and auto-reset wrapper. Only environments with a flat (1-D)
observation are supported.
"""

def __init__(self, env: Env, context_length: int):
super().__init__(env)
if context_length < 1:
raise ValueError(f'context_length must be >= 1, got {context_length}.')
if not isinstance(env.observation_size, int):
raise ValueError(
'HistoryWrapper only supports environments with a flat observation,'
f' got observation_size={env.observation_size}.'
)
self.context_length = context_length
self._frame_size = env.observation_size + env.action_size

@property
def observation_size(self) -> int:
return self.context_length * self._frame_size

def reset(self, rng: jax.Array) -> State:
state = self.env.reset(rng)
action = jp.zeros(state.obs.shape[:-1] + (self.env.action_size,))
frame = jp.concatenate([state.obs, action], axis=-1)
history = jp.zeros(
frame.shape[:-1] + (self.context_length - 1, self._frame_size),
dtype=frame.dtype,
)
history = jp.concatenate([history, frame[..., None, :]], axis=-2)
return state.replace(obs=history.reshape(frame.shape[:-1] + (-1,))) # pyrefly: ignore[missing-attribute]

def step(self, state: State, action: jax.Array) -> State:
history = state.obs.reshape(
state.obs.shape[:-1] + (self.context_length, self._frame_size)
)
inner = state.replace(obs=history[..., -1, : self.env.observation_size]) # pyrefly: ignore[missing-attribute]
nstate = self.env.step(inner, action)
frame = jp.concatenate([nstate.obs, action], axis=-1)
history = jp.concatenate([history[..., 1:, :], frame[..., None, :]], axis=-2)
return nstate.replace(obs=history.reshape(frame.shape[:-1] + (-1,))) # pyrefly: ignore[missing-attribute]


class VmapWrapper(Wrapper):
"""Vectorizes Brax env."""

Expand Down
54 changes: 54 additions & 0 deletions brax/envs/wrappers/training_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,60 @@ def get_offset(rng):
self.assertEqual(state.pipeline_state.q[:, 0].shape[0], 256)
self.assertEqual(np.unique(state.pipeline_state.q[:, 0]).shape[0], 256)

def test_history_wrapper(self):
base = envs.get_environment('ant')
obs_size, act_size, length = base.observation_size, base.action_size, 3
env = training.HistoryWrapper(base, length)
frame = obs_size + act_size
self.assertEqual(env.observation_size, length * frame)

state = jax.jit(env.reset)(jax.random.PRNGKey(0))
hist = state.obs.reshape(length, frame)
np.testing.assert_array_equal(hist[:-1], 0)
np.testing.assert_array_equal(hist[-1, obs_size:], 0)
base_state = jax.jit(base.reset)(jax.random.PRNGKey(0))
np.testing.assert_allclose(hist[-1, :obs_size], base_state.obs)

step = jax.jit(env.step)
actions = [jp.full((act_size,), 0.1 * (i + 1)) for i in range(4)]
observed = []
for a in actions:
state = step(state, a)
observed.append(state.obs.reshape(length, frame))
# Oldest entries are dropped; the newest frame is (obs, action just taken).
np.testing.assert_allclose(observed[-1][-1, obs_size:], actions[-1])
np.testing.assert_allclose(observed[-1][-2, obs_size:], actions[-2])
np.testing.assert_allclose(observed[-1][-3, obs_size:], actions[-3])
np.testing.assert_allclose(observed[0][-2], hist[-1])
self.assertEqual(state.obs.shape, (length * frame,))

def test_history_wrapper_batched_autoreset(self):
length = 2
base = envs.get_environment('ant')
env = training.wrap(
training.HistoryWrapper(base, length), episode_length=3
)
frame = base.observation_size + base.action_size
state = jax.jit(env.reset)(jax.random.split(jax.random.PRNGKey(0), 4))
self.assertEqual(state.obs.shape, (4, length * frame))
step = jax.jit(env.step)
for _ in range(3):
state = step(state, jp.ones((4, base.action_size)))
# Episode ended on the third step: observation is reset to its first value,
# with an empty history.
np.testing.assert_array_equal(state.done, 1)
np.testing.assert_array_equal(state.obs[:, :frame], 0)
first_obs = state.obs
state = step(state, jp.ones((4, base.action_size)))
# The next episode starts from the reset history: its newest frame moves
# up one slot and nothing from the previous episode is carried over.
np.testing.assert_allclose(state.obs[:, :frame], first_obs[:, frame:])
np.testing.assert_array_equal(state.obs[:, -base.action_size:], 1)

def test_history_wrapper_invalid_context_length(self):
with self.assertRaises(ValueError):
training.HistoryWrapper(envs.get_environment('ant'), 0)


if __name__ == '__main__':
absltest.main()