stable-baselines3/tests/test_sde.py

61 lines
2 KiB
Python
Raw Normal View History

2019-10-28 17:24:13 +00:00
import pytest
2019-11-18 13:09:31 +00:00
import gym
2019-10-28 17:24:13 +00:00
import torch as th
from torch.distributions import Normal
from torchy_baselines import A2C
2019-11-18 13:09:31 +00:00
from torchy_baselines.common.vec_env import DummyVecEnv, VecNormalize
from torchy_baselines.common.monitor import Monitor
2019-10-28 17:24:13 +00:00
def test_state_dependent_exploration():
2019-11-18 13:09:31 +00:00
"""
Check that the gradient correspond to the expected one
"""
2019-10-31 13:14:30 +00:00
n_states = 2
2019-10-28 17:24:13 +00:00
state_dim = 3
# TODO: fix for action_dim > 1
action_dim = 1
2019-11-18 13:09:31 +00:00
sigma = th.ones(state_dim, 1, requires_grad=True)
# Reduce the number of parameters
# sigma_ = th.ones(state_dim, action_dim) * sigma_
2019-10-28 17:24:13 +00:00
# weights_dist = Normal(th.zeros_like(log_sigma), th.exp(log_sigma))
th.manual_seed(2)
weights_dist = Normal(th.zeros_like(sigma), sigma)
weights = weights_dist.rsample()
2019-10-31 13:14:30 +00:00
state = th.rand(n_states, state_dim)
2019-10-28 17:24:13 +00:00
mu = th.ones(action_dim)
# print(weights.shape, state.shape)
noise = th.mm(state, weights)
2019-10-31 13:14:30 +00:00
2019-10-28 17:24:13 +00:00
variance = th.mm(state ** 2, sigma ** 2)
action_dist = Normal(mu, th.sqrt(variance))
loss = action_dist.log_prob((mu + noise).detach()).mean()
loss.backward()
# From Rueckstiess paper
grad = th.zeros_like(sigma)
for j in range(action_dim):
for i in range(state_dim):
2019-10-31 13:14:30 +00:00
a = ((noise[:, j] ** 2 - variance[:, j]) / (variance[:, j] ** 2)) * (state[:, i] ** 2 * sigma[i, j])
grad[i, j] = a.mean()
2019-10-28 17:24:13 +00:00
# sigma.grad should be equal to grad
assert sigma.grad.allclose(grad)
@pytest.mark.parametrize("model_class", [A2C])
def test_state_dependent_noise(model_class):
2019-10-31 13:14:30 +00:00
env_id = 'MountainCarContinuous-v0'
2019-11-18 13:09:31 +00:00
2019-10-31 13:14:30 +00:00
env = VecNormalize(DummyVecEnv([lambda: Monitor(gym.make(env_id))]), norm_reward=True)
eval_env = VecNormalize(DummyVecEnv([lambda: Monitor(gym.make(env_id))]), training=False, norm_reward=False)
2019-11-18 13:09:31 +00:00
model = model_class('MlpPolicy', env, n_steps=200, use_sde=True, ent_coef=0.00, verbose=1, learning_rate=3e-4,
policy_kwargs=dict(log_std_init=0.0, ortho_init=False), seed=None)
model.learn(total_timesteps=int(1000), log_interval=5, eval_freq=500, eval_env=eval_env)