Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Example: Simple RL example using DQN/Lightning #1232

Merged
merged 36 commits into from
Mar 28, 2020
Merged
Changes from 3 commits
Commits
Show all changes
36 commits
Select commit Hold shift + click to select a range
07a4e7d
Example: Simple RL example using DQN/Lightning
Mar 22, 2020
05cf5ac
Applied autopep8 fixes
Mar 23, 2020
fc9f31d
* Updated line length from 120 to 110
Mar 25, 2020
cafea47
Update pl_examples/domain_templates/dqn.py
djbyrne Mar 25, 2020
606f1f2
Update pl_examples/domain_templates/dqn.py
djbyrne Mar 25, 2020
45d671a
CI: split tests-examples (#990)
Borda Mar 25, 2020
31ef2eb
Clean up
Mar 25, 2020
e86e6b2
updated example image
williamFalcon Mar 26, 2020
d2ef4fa
update types
Borda Mar 26, 2020
b4b8dd7
rename script
Borda Mar 26, 2020
3255539
Update CHANGELOG.md
djbyrne Mar 26, 2020
8b2c9e2
another rename
Borda Mar 26, 2020
2a4cd47
Disable validation when val_percent_check=0 (#1251)
Mar 27, 2020
d394b80
calling self.forward() -> self() (#1211)
jeremyjordan Mar 27, 2020
6a0b171
Fix requirements-extra.txt Trains package to release version (#1229)
bmartinn Mar 27, 2020
6772e0c
Remove unnecessary parameters to super() in documentation and source …
TylerYep Mar 27, 2020
593bf50
update deprecation warning (#1258)
Borda Mar 27, 2020
bec43c9
update docs for progress bat values (#1253)
Borda Mar 27, 2020
9bb2e00
lower timeouts for inactive issues (#1250)
Borda Mar 27, 2020
da18534
update contrib list (#1241)
Borda Mar 27, 2020
3a93aaf
Fix outdated docs (#1227)
5n7-sk Mar 27, 2020
ac6692d
Fix typo (#1224)
5n7-sk Mar 27, 2020
1a9719c
drop unused Tox (#1242)
Borda Mar 27, 2020
61177cd
system info (#1234)
Borda Mar 27, 2020
12b39a7
Changed smoothing in tqdm to decrease variability of time remaining b…
pertschuk Mar 27, 2020
582fe4c
Example: Simple RL example using DQN/Lightning
Mar 22, 2020
3ed2739
Applied autopep8 fixes
Mar 23, 2020
dac522e
* Updated line length from 120 to 110
Mar 25, 2020
ec85171
Update pl_examples/domain_templates/dqn.py
djbyrne Mar 25, 2020
eb72022
Update pl_examples/domain_templates/dqn.py
djbyrne Mar 25, 2020
e03e015
Clean up
Mar 25, 2020
0e9ca89
update types
Borda Mar 26, 2020
42838b3
rename script
Borda Mar 26, 2020
9cf4915
Update CHANGELOG.md
djbyrne Mar 26, 2020
f9be8b0
another rename
Borda Mar 26, 2020
a44c90c
Merge branch 'dqn_example' of https://github.com/djbyrne/pytorch-ligh…
Mar 28, 2020
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
271 changes: 271 additions & 0 deletions pl_examples/domain_templates/dqn.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,271 @@
from typing import Tuple, OrderedDict, List

import pytorch_lightning as pl
import argparse
import gym
import numpy as np
import collections

import torch
import torch.nn as nn
import torch.optim as optim
from torch.optim import Optimizer
from torch.utils.data import DataLoader
from torch.utils.data.dataset import IterableDataset
djbyrne marked this conversation as resolved.
Show resolved Hide resolved


class DQN(nn.Module):
""" Simple MLP network"""

def __init__(self, obs_size, n_actions, hidden_size=128):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pls add types

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done

super(DQN, self).__init__()
self.net = nn.Sequential(
nn.Linear(obs_size[0], hidden_size),
nn.ReLU(),
nn.Linear(hidden_size, n_actions)
)

def forward(self, x):
return self.net(x.float())


# Named tuple for storing experience steps gathered in training
Experience = collections.namedtuple(
'Experience', field_names=['state', 'action', 'reward',
'done', 'new_state'])


class ExperienceBuffer:
"""Replay Buffer for storing past experiences allowing the agent to learn from them"""

def __init__(self, capacity: int) -> None:
self.buffer = collections.deque(maxlen=capacity)

def __len__(self) -> None:
return len(self.buffer)

def append(self, experience: Experience) -> None:
self.buffer.append(experience)

def sample(self, batch_size: int) -> Tuple:
indices = np.random.choice(len(self.buffer), batch_size, replace=False)
states, actions, rewards, dones, next_states = zip(*[self.buffer[idx] for idx in indices])

return (np.array(states), np.array(actions), np.array(rewards, dtype=np.float32),
np.array(dones, dtype=np.bool), np.array(next_states))


class RLDataset(IterableDataset):
"""
Iterable Dataset containing the ExperienceBuffer
which will be updated with new experiences during training
"""

def __init__(self, buffer: ExperienceBuffer, sample_size: int = 200) -> None:
self.buffer = buffer
self.sample_size = sample_size

def __iter__(self) -> Tuple:
states, actions, rewards, dones, new_states = self.buffer.sample(self.sample_size)
for i in range(len(dones)):
yield states[i], actions[i], rewards[i], dones[i], new_states[i]


class Agent:
"""
Base Agent class handeling the interaction with the environment
"""

def __init__(self, env: gym.Env, exp_buffer: ExperienceBuffer) -> None:
self.env = env
self.exp_buffer = exp_buffer
self.reset()
self.state = self.env.reset()

def reset(self) -> None:
self.state = self.env.reset()

def get_action(self, net: nn.Module, epsilon: float, device: str) -> int:
"""
Using the given network, decide what action to carry out
using an epsilon-greedy policy
"""
if np.random.random() < epsilon:
action = self.env.action_space.sample()
else:
state_a = np.array([self.state], copy=False)
state_v = torch.tensor(state_a)
if device not in ['cpu']:
state_v = state_v.cuda(device)

q_vals_v = net(state_v)
_, act_v = torch.max(q_vals_v, dim=1)
action = int(act_v.item())

return action

@torch.no_grad()
def play_step(self, net: nn.Module, epsilon: float = 0.0, device: str = 'cpu') -> Tuple[float, bool]:
"""Carries out a single interaction step between the agent and the environment"""

action = self.get_action(net, epsilon, device)

# do step in the environment
new_state, reward, is_done, _ = self.env.step(action)

exp = Experience(self.state, action, reward,
is_done, new_state)
self.exp_buffer.append(exp)

self.state = new_state
if is_done:
self.reset()
return reward, is_done


class DQNLightning(pl.LightningModule):
""" Basic DQN Model """

def __init__(self, hparams) -> None:
super().__init__()
self.hparams = hparams
self.env = gym.make(self.hparams.env)
self.net = DQN(self.env.observation_space.shape,
self.env.action_space.n)
self.tgt_net = DQN(self.env.observation_space.shape,
self.env.action_space.n)
self.buffer = ExperienceBuffer(self.hparams.replay_size)
self.agent = Agent(self.env, self.buffer)
self.total_reward = 0
self.episode_reward = 0
self.populate(self.hparams.warm_start_steps)

def populate(self, steps: int = 1000) -> None:
"""
Carries out several random steps through the environment to initially fill
up the replay buffer with experiences
"""
for i in range(steps):
self.agent.play_step(self.net, epsilon=1.0)

def forward(self, x: torch.Tensor) -> torch.Tensor:
"""
Passes in a state x through the network and gets an action as an output
"""
if isinstance(x, list):
x = x[0]
output = self.net(x)
return output

def dqn_mse_loss(self, batch) -> torch.Tensor:
"""
Calculates the mse loss using a mini batch from the replay buffer
"""
states, actions, rewards, dones, next_states = batch

state_action_values = self.net(states).gather(
1, actions.unsqueeze(-1)).squeeze(-1)
with torch.no_grad():
next_state_values = self.tgt_net(next_states).max(1)[0]
next_state_values[dones] = 0.0
next_state_values = next_state_values.detach()

expected_state_action_values = next_state_values * self.hparams.gamma + rewards
return nn.MSELoss()(state_action_values,
expected_state_action_values)

def training_step(self, batch, nb_batch) -> OrderedDict:
""" Carries out a single step through the environment to update the replay buffer.
Then calculates loss based on the minibatch recieved"""
device = self.get_device(batch)
epsilon = max(self.hparams.eps_end, self.hparams.eps_start -
self.global_step + 1 / self.hparams.eps_last_frame)

# step through environment with agent
reward, done = self.agent.play_step(self.net, epsilon, device)
self.episode_reward += reward

# calculates training loss
loss = self.dqn_mse_loss(batch)

if self.trainer.use_dp or self.trainer.use_ddp2:
loss = loss.unsqueeze(0)

if done:
self.total_reward = self.episode_reward
self.episode_reward = 0

# Soft update of target network
if self.global_step % self.hparams.sync_rate == 0:
self.tgt_net.load_state_dict(self.net.state_dict())

log = {'total_reward': torch.tensor(self.total_reward).to(device),
'reward': torch.tensor(reward).to(device),
'steps': torch.tensor(self.global_step).to(device)}

return collections.OrderedDict({'loss': loss, 'log': log, 'progress_bar': log})

def configure_optimizers(self) -> List[Optimizer]:
""" Initialize Adam optimizer"""
optimizer = optim.Adam(self.net.parameters(), lr=self.hparams.lr)
return [optimizer]

def __dataloader(self) -> DataLoader:
"""Initialize the Replay Buffer dataset used for retrieving experiences"""
dataset = RLDataset(self.buffer, self.hparams.episode_length)
dataloader = DataLoader(dataset=dataset,
batch_size=self.hparams.batch_size,
sampler=None
)
return dataloader

def train_dataloader(self) -> DataLoader:
"""Get train loader"""
return self.__dataloader()

def get_device(self, batch) -> str:
"""Retrieve device currently being used by minibatch"""
if self.on_gpu:
device = batch[0].device.index
else:
device = 'cpu'

return device
djbyrne marked this conversation as resolved.
Show resolved Hide resolved


def main(hparams) -> None:
model = DQNLightning(hparams)

trainer = pl.Trainer(gpus=1, distributed_backend='dp', early_stop_callback=False, val_check_interval=100)

trainer.fit(model)


if __name__ == '__main__':
torch.manual_seed(0)
np.random.seed(0)

parser = argparse.ArgumentParser()
parser.add_argument("--batch_size", type=int, default=16, help="size of the batches")
parser.add_argument("--lr", type=float, default=1e-2, help="learning rate")
parser.add_argument("--env", type=str, default="CartPole-v0", help="gym environment tag")
parser.add_argument("--gamma", type=float, default=0.99, help="discount factor")
parser.add_argument("--sync_rate", type=int, default=10,
help="how many frames do we update the target network")
parser.add_argument("--replay_size", type=int, default=1000,
help="capacity of the replay buffer")
parser.add_argument("--warm_start_size", type=int, default=1000,
help="how many samples do we use to fill our buffer at the start of training")
parser.add_argument("--eps_last_frame", type=int, default=1000,
help="what frame should epsilon stop decaying")
parser.add_argument("--eps_start", type=float, default=1.0, help="starting value of epsilon")
parser.add_argument("--eps_end", type=float, default=0.01, help="final value of epsilon")
parser.add_argument("--episode_length", type=int, default=200, help="max length of an episode")
parser.add_argument("--max_episode_reward", type=int, default=200,
help="max episode reward in the environment")
parser.add_argument("--warm_start_steps", type=int, default=1000,
help="max episode reward in the environment")

args = parser.parse_args()

main(args)