-
Notifications
You must be signed in to change notification settings - Fork 257
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Jan Michelfeit
committed
Nov 30, 2022
1 parent
27b8a55
commit 2dec99f
Showing
7 changed files
with
211 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,44 @@ | ||
import numpy as np | ||
import torch as th | ||
from gym.vector.utils import spaces | ||
from stable_baselines3.common.preprocessing import get_obs_shape | ||
|
||
from imitation.policies.replay_buffer_wrapper import ReplayBufferView | ||
from imitation.rewards.reward_function import RewardFn | ||
from imitation.util import util | ||
from imitation.util.networks import RunningNorm | ||
|
||
|
||
class StateEntropyReward(RewardFn): | ||
def __init__(self, nearest_neighbor_k: int, observation_space: spaces.Space): | ||
self.nearest_neighbor_k = nearest_neighbor_k | ||
# TODO support n_envs > 1 | ||
self.entropy_stats = RunningNorm(1) | ||
self.obs_shape = get_obs_shape(observation_space) | ||
self.replay_buffer_view = ReplayBufferView( | ||
np.empty(0, dtype=observation_space.dtype), lambda: slice(0) | ||
) | ||
|
||
def set_buffer_view(self, replay_buffer_view: ReplayBufferView): | ||
self.replay_buffer_view = replay_buffer_view | ||
|
||
def __call__( | ||
self, | ||
state: np.ndarray, | ||
action: np.ndarray, | ||
next_state: np.ndarray, | ||
done: np.ndarray, | ||
) -> np.ndarray: | ||
# TODO: should this work with torch instead of numpy internally? | ||
# (The RewardFn protocol requires numpy) | ||
|
||
all_observations = self.replay_buffer_view.observations | ||
# ReplayBuffer sampling flattens the venv dimension, let's adapt to that | ||
all_observations = all_observations.reshape((-1, *self.obs_shape)) | ||
entropies = util.compute_state_entropy( | ||
state, | ||
all_observations, | ||
self.nearest_neighbor_k, | ||
) | ||
normalized_entropies = self.entropy_stats.forward(th.as_tensor(entropies)) | ||
return normalized_entropies.numpy() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,70 @@ | ||
from unittest.mock import patch | ||
|
||
import numpy as np | ||
import torch as th | ||
from gym.spaces import Discrete | ||
from stable_baselines3.common.preprocessing import get_obs_shape | ||
|
||
from imitation.algorithms.pebble.entropy_reward import StateEntropyReward | ||
from imitation.policies.replay_buffer_wrapper import ReplayBufferView | ||
from imitation.util import util | ||
|
||
SPACE = Discrete(4) | ||
PLACEHOLDER = np.empty(get_obs_shape(SPACE)) | ||
|
||
BUFFER_SIZE = 20 | ||
K = 4 | ||
BATCH_SIZE = 8 | ||
VENVS = 2 | ||
|
||
|
||
def test_state_entropy_reward_returns_entropy(rng): | ||
obs_shape = get_obs_shape(SPACE) | ||
all_observations = rng.random((BUFFER_SIZE, VENVS, *obs_shape)) | ||
|
||
reward_fn = StateEntropyReward(K, SPACE) | ||
reward_fn.set_buffer_view(ReplayBufferView(all_observations, lambda: slice(None))) | ||
|
||
# Act | ||
observations = rng.random((BATCH_SIZE, *obs_shape)) | ||
reward = reward_fn(observations, PLACEHOLDER, PLACEHOLDER, PLACEHOLDER) | ||
|
||
# Assert | ||
expected = util.compute_state_entropy( | ||
observations, all_observations.reshape(-1, *obs_shape), K | ||
) | ||
expected_normalized = reward_fn.entropy_stats.normalize(th.as_tensor(expected)).numpy() | ||
np.testing.assert_allclose(reward, expected_normalized) | ||
|
||
|
||
def test_state_entropy_reward_returns_normalized_values(): | ||
with patch("imitation.util.util.compute_state_entropy") as m: | ||
# mock entropy computation so that we can test only stats collection in this test | ||
m.side_effect = lambda obs, all_obs, k: obs | ||
|
||
reward_fn = StateEntropyReward(K, SPACE) | ||
all_observations = np.empty((BUFFER_SIZE, VENVS, *get_obs_shape(SPACE))) | ||
reward_fn.set_buffer_view( | ||
ReplayBufferView(all_observations, lambda: slice(None)) | ||
) | ||
|
||
dim = 8 | ||
shift = 3 | ||
scale = 2 | ||
|
||
# Act | ||
for _ in range(1000): | ||
state = th.randn(dim) * scale + shift | ||
reward_fn(state, PLACEHOLDER, PLACEHOLDER, PLACEHOLDER) | ||
|
||
normalized_reward = reward_fn( | ||
np.zeros(dim), PLACEHOLDER, PLACEHOLDER, PLACEHOLDER | ||
) | ||
|
||
# Assert | ||
np.testing.assert_allclose( | ||
normalized_reward, | ||
np.repeat(-shift / scale, dim), | ||
rtol=0.05, | ||
atol=0.05, | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters