|
| 1 | +from unittest.mock import patch |
| 2 | + |
| 3 | +import numpy as np |
| 4 | +import torch as th |
| 5 | +from gym.spaces import Discrete |
| 6 | +from stable_baselines3.common.preprocessing import get_obs_shape |
| 7 | + |
| 8 | +from imitation.algorithms.pebble.entropy_reward import StateEntropyReward |
| 9 | +from imitation.policies.replay_buffer_wrapper import ReplayBufferView |
| 10 | +from imitation.util import util |
| 11 | + |
| 12 | +SPACE = Discrete(4) |
| 13 | +PLACEHOLDER = np.empty(get_obs_shape(SPACE)) |
| 14 | + |
| 15 | +BUFFER_SIZE = 20 |
| 16 | +K = 4 |
| 17 | +BATCH_SIZE = 8 |
| 18 | +VENVS = 2 |
| 19 | + |
| 20 | + |
| 21 | +def test_state_entropy_reward_returns_entropy(rng): |
| 22 | + obs_shape = get_obs_shape(SPACE) |
| 23 | + all_observations = rng.random((BUFFER_SIZE, VENVS, *obs_shape)) |
| 24 | + |
| 25 | + reward_fn = StateEntropyReward(K, SPACE) |
| 26 | + reward_fn.set_buffer_view(ReplayBufferView(all_observations, lambda: slice(None))) |
| 27 | + |
| 28 | + # Act |
| 29 | + observations = rng.random((BATCH_SIZE, *obs_shape)) |
| 30 | + reward = reward_fn(observations, PLACEHOLDER, PLACEHOLDER, PLACEHOLDER) |
| 31 | + |
| 32 | + # Assert |
| 33 | + expected = util.compute_state_entropy( |
| 34 | + observations, all_observations.reshape(-1, *obs_shape), K |
| 35 | + ) |
| 36 | + expected_normalized = reward_fn.entropy_stats.normalize(th.as_tensor(expected)).numpy() |
| 37 | + np.testing.assert_allclose(reward, expected_normalized) |
| 38 | + |
| 39 | + |
| 40 | +def test_state_entropy_reward_returns_normalized_values(): |
| 41 | + with patch("imitation.util.util.compute_state_entropy") as m: |
| 42 | + # mock entropy computation so that we can test only stats collection in this test |
| 43 | + m.side_effect = lambda obs, all_obs, k: obs |
| 44 | + |
| 45 | + reward_fn = StateEntropyReward(K, SPACE) |
| 46 | + all_observations = np.empty((BUFFER_SIZE, VENVS, *get_obs_shape(SPACE))) |
| 47 | + reward_fn.set_buffer_view( |
| 48 | + ReplayBufferView(all_observations, lambda: slice(None)) |
| 49 | + ) |
| 50 | + |
| 51 | + dim = 8 |
| 52 | + shift = 3 |
| 53 | + scale = 2 |
| 54 | + |
| 55 | + # Act |
| 56 | + for _ in range(1000): |
| 57 | + state = th.randn(dim) * scale + shift |
| 58 | + reward_fn(state, PLACEHOLDER, PLACEHOLDER, PLACEHOLDER) |
| 59 | + |
| 60 | + normalized_reward = reward_fn( |
| 61 | + np.zeros(dim), PLACEHOLDER, PLACEHOLDER, PLACEHOLDER |
| 62 | + ) |
| 63 | + |
| 64 | + # Assert |
| 65 | + np.testing.assert_allclose( |
| 66 | + normalized_reward, |
| 67 | + np.repeat(-shift / scale, dim), |
| 68 | + rtol=0.05, |
| 69 | + atol=0.05, |
| 70 | + ) |
0 commit comments