2019-01-31 23:34:32 -05:00
|
|
|
import gym
|
|
|
|
import torch
|
|
|
|
import torch.nn as nn
|
|
|
|
import torch.nn.functional as F
|
|
|
|
import rltorch
|
|
|
|
import rltorch.network as rn
|
|
|
|
import rltorch.memory as M
|
|
|
|
import rltorch.env as E
|
2019-02-27 09:52:28 -05:00
|
|
|
from rltorch.action_selector import StochasticSelector
|
2020-04-14 15:24:48 -04:00
|
|
|
# from tensorboardX import SummaryWriter
|
2019-02-27 09:52:28 -05:00
|
|
|
from copy import deepcopy
|
2020-04-14 15:24:48 -04:00
|
|
|
from rltorch.log import Logger
|
2019-01-31 23:34:32 -05:00
|
|
|
|
2019-03-04 17:09:46 -05:00
|
|
|
#
|
|
|
|
## Networks
|
|
|
|
#
|
2019-01-31 23:34:32 -05:00
|
|
|
class Value(nn.Module):
|
2020-04-14 15:24:48 -04:00
|
|
|
def __init__(self, state_size, action_size):
|
|
|
|
super(Value, self).__init__()
|
|
|
|
self.state_size = state_size
|
|
|
|
self.action_size = action_size
|
2019-02-13 00:36:23 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
self.fc1 = rn.NoisyLinear(state_size, 255)
|
|
|
|
self.fc_norm = nn.LayerNorm(255)
|
2019-01-31 23:34:32 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
self.value_fc = rn.NoisyLinear(255, 255)
|
|
|
|
self.value_fc_norm = nn.LayerNorm(255)
|
|
|
|
self.value = rn.NoisyLinear(255, 1)
|
|
|
|
|
|
|
|
self.advantage_fc = rn.NoisyLinear(255, 255)
|
|
|
|
self.advantage_fc_norm = nn.LayerNorm(255)
|
|
|
|
self.advantage = rn.NoisyLinear(255, action_size)
|
2019-01-31 23:34:32 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
def forward(self, x):
|
|
|
|
x = F.relu(self.fc_norm(self.fc1(x)))
|
2019-01-31 23:34:32 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
state_value = F.relu(self.value_fc_norm(self.value_fc(x)))
|
|
|
|
state_value = self.value(state_value)
|
2019-01-31 23:34:32 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
advantage = F.relu(self.advantage_fc_norm(self.advantage_fc(x)))
|
|
|
|
advantage = self.advantage(advantage)
|
2019-01-31 23:34:32 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
x = state_value + advantage - advantage.mean()
|
|
|
|
return x
|
2019-01-31 23:34:32 -05:00
|
|
|
|
|
|
|
|
2019-02-27 09:52:28 -05:00
|
|
|
class Policy(nn.Module):
|
2020-04-14 15:24:48 -04:00
|
|
|
def __init__(self, state_size, action_size):
|
|
|
|
super(Policy, self).__init__()
|
|
|
|
self.state_size = state_size
|
|
|
|
self.action_size = action_size
|
2019-02-27 09:52:28 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
self.fc1 = nn.Linear(state_size, 125)
|
|
|
|
self.fc_norm = nn.LayerNorm(125)
|
2019-02-27 09:52:28 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
self.fc2 = nn.Linear(125, 125)
|
|
|
|
self.fc2_norm = nn.LayerNorm(125)
|
2019-02-27 09:52:28 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
self.action_prob = nn.Linear(125, action_size)
|
2019-02-27 09:52:28 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
def forward(self, x):
|
|
|
|
x = F.relu(self.fc_norm(self.fc1(x)))
|
|
|
|
x = F.relu(self.fc2_norm(self.fc2(x)))
|
|
|
|
x = F.softmax(self.action_prob(x), dim = 1)
|
|
|
|
return x
|
2019-02-27 09:52:28 -05:00
|
|
|
|
2019-03-04 17:09:46 -05:00
|
|
|
#
|
|
|
|
## Configuration
|
|
|
|
#
|
2019-01-31 23:34:32 -05:00
|
|
|
config = {}
|
|
|
|
config['seed'] = 901
|
|
|
|
config['environment_name'] = 'Acrobot-v1'
|
|
|
|
config['memory_size'] = 2000
|
|
|
|
config['total_training_episodes'] = 50
|
2019-02-27 09:52:28 -05:00
|
|
|
config['total_evaluation_episodes'] = 5
|
2019-01-31 23:34:32 -05:00
|
|
|
config['batch_size'] = 32
|
|
|
|
config['learning_rate'] = 1e-3
|
|
|
|
config['target_sync_tau'] = 1e-1
|
|
|
|
config['discount_rate'] = 0.99
|
|
|
|
config['replay_skip'] = 0
|
|
|
|
# How many episodes between printing out the episode stats
|
|
|
|
config['print_stat_n_eps'] = 1
|
|
|
|
config['disable_cuda'] = False
|
2019-02-11 10:23:11 -05:00
|
|
|
# Prioritized vs Random Sampling
|
|
|
|
# 0 - Random sampling
|
|
|
|
# 1 - Only the highest prioirities
|
|
|
|
config['prioritized_replay_sampling_priority'] = 0.6
|
|
|
|
# How important are the weights for the loss?
|
|
|
|
# 0 - Treat all losses equally
|
|
|
|
# 1 - Lower the importance of high losses
|
|
|
|
# Should ideally start from 0 and move your way to 1 to prevent overfitting
|
|
|
|
config['prioritized_replay_weight_importance'] = rltorch.scheduler.ExponentialScheduler(initial_value = 0.4, end_value = 1, iterations = 5000)
|
2019-02-27 09:52:28 -05:00
|
|
|
|
|
|
|
|
2019-03-04 17:09:46 -05:00
|
|
|
#
|
|
|
|
## Training Loop
|
|
|
|
#
|
2020-04-14 15:24:48 -04:00
|
|
|
def train(runner, agent, config, logwriter=None):
|
2019-01-31 23:34:32 -05:00
|
|
|
finished = False
|
2019-02-13 23:47:37 -05:00
|
|
|
last_episode_num = 1
|
2019-01-31 23:34:32 -05:00
|
|
|
while not finished:
|
2019-02-27 09:52:28 -05:00
|
|
|
runner.run(config['replay_skip'] + 1)
|
2019-01-31 23:34:32 -05:00
|
|
|
agent.learn()
|
2019-02-27 09:52:28 -05:00
|
|
|
if logwriter is not None:
|
2020-04-14 15:24:48 -04:00
|
|
|
if last_episode_num < runner.episode_num:
|
|
|
|
last_episode_num = runner.episode_num
|
|
|
|
agent.value_net.log_named_parameters()
|
|
|
|
agent.policy_net.log_named_parameters()
|
|
|
|
logwriter.write(Logger)
|
2019-02-27 09:52:28 -05:00
|
|
|
finished = runner.episode_num > config['total_training_episodes']
|
2019-02-13 23:47:37 -05:00
|
|
|
|
2019-03-04 17:09:46 -05:00
|
|
|
|
2019-02-13 23:47:37 -05:00
|
|
|
if __name__ == "__main__":
|
2020-04-14 15:24:48 -04:00
|
|
|
# Setting up the environment
|
|
|
|
rltorch.set_seed(config['seed'])
|
|
|
|
print("Setting up environment...", end = " ")
|
|
|
|
env = E.TorchWrap(gym.make(config['environment_name']))
|
|
|
|
env.seed(config['seed'])
|
|
|
|
print("Done.")
|
2019-02-13 23:47:37 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
state_size = env.observation_space.shape[0]
|
|
|
|
action_size = env.action_space.n
|
2019-02-13 23:47:37 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
# Logging
|
|
|
|
logwriter = None
|
|
|
|
# logwriter = rltorch.log.LogWriter(SummaryWriter())
|
2019-02-13 23:47:37 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
# Setting up the networks
|
|
|
|
device = torch.device("cuda:0" if torch.cuda.is_available() and not config['disable_cuda'] else "cpu")
|
|
|
|
config2 = deepcopy(config)
|
|
|
|
config2['learning_rate'] = 0.01
|
|
|
|
policy_net = rn.ESNetwork(Policy(state_size, action_size),
|
|
|
|
torch.optim.Adam, 500, None, config2, sigma=0.1, device=device, name="ES")
|
|
|
|
value_net = rn.Network(Value(state_size, action_size),
|
|
|
|
torch.optim.Adam, config, device=device, name="DQN")
|
|
|
|
target_net = rn.TargetNetwork(value_net, device=device)
|
2019-02-13 23:47:37 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
# Actor takes a net and uses it to produce actions from given states
|
|
|
|
actor = StochasticSelector(policy_net, action_size, device=device)
|
2019-03-04 17:09:46 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
# Memory stores experiences for later training
|
|
|
|
memory = M.PrioritizedReplayMemory(capacity=config['memory_size'], alpha=config['prioritized_replay_sampling_priority'])
|
2019-02-13 23:47:37 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
# Runner performs a certain number of steps in the environment
|
|
|
|
runner = rltorch.env.EnvironmentRunSync(env, actor, config, name="Training", memory=memory, logwriter=logwriter)
|
2019-02-13 23:47:37 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
# Agent is what performs the training
|
|
|
|
agent = rltorch.agents.QEPAgent(policy_net, value_net, memory, config, target_value_net=target_net)
|
2019-02-27 09:52:28 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
print("Training...")
|
|
|
|
train(runner, agent, config, logwriter=logwriter)
|
2019-02-13 23:47:37 -05:00
|
|
|
|
|
|
|
# For profiling...
|
|
|
|
# import cProfile
|
2020-04-14 15:24:48 -04:00
|
|
|
# cProfile.run('train(runner, agent, config, logwriter = logwriter )')
|
2019-02-13 23:47:37 -05:00
|
|
|
# python -m torch.utils.bottleneck /path/to/source/script.py [args] is also a good solution...
|
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
print("Training Finished.")
|
2019-02-13 23:47:37 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
print("Evaluating...")
|
|
|
|
rltorch.env.simulateEnvEps(env, actor, config, total_episodes = config['total_evaluation_episodes'], name="Evaluation")
|
|
|
|
print("Evaulations Done.")
|
2019-02-13 23:47:37 -05:00
|
|
|
|
2020-04-14 15:24:48 -04:00
|
|
|
# logwriter.close() # We don't need to write anything out to disk anymore
|