-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdqn-example.py
223 lines (192 loc) · 7.41 KB
/
dqn-example.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
'''DLP DQN Lab'''
__author__ = 'chengscott'
__copyright__ = 'Copyright 2020, NCTU CGI Lab'
import argparse
from collections import deque
import itertools
import random
import time
import gym
import numpy as np
import torch
import torch.nn as nn
from torch.utils.tensorboard import SummaryWriter
class ReplayMemory:
__slots__ = ['buffer']
def __init__(self, capacity):
self.buffer = deque(maxlen=capacity)
def __len__(self):
return len(self.buffer)
def append(self, *transition):
# (state, action, reward, next_state, done)
self.buffer.append(tuple(map(tuple, transition)))
def sample(self, batch_size, device):
'''sample a batch of transition tensors'''
transitions = random.sample(self.buffer, batch_size)
return (torch.tensor(x, dtype=torch.float, device=device)
for x in zip(*transitions))
class Net(nn.Module):
def __init__(self, state_dim=8, action_dim=4, hidden_dim=32):
super().__init__()
## TODO ##
raise NotImplementedError
def forward(self, x):
## TODO ##
raise NotImplementedError
class DQN:
def __init__(self, args):
self._behavior_net = Net().to(args.device)
self._target_net = Net().to(args.device)
# initialize target network
self._target_net.load_state_dict(self._behavior_net.state_dict())
## TODO ##
# self._optimizer = ?
raise NotImplementedError
# memory
self._memory = ReplayMemory(capacity=args.capacity)
## config ##
self.device = args.device
self.batch_size = args.batch_size
self.gamma = args.gamma
self.freq = args.freq
self.target_freq = args.target_freq
def select_action(self, state, epsilon, action_space):
'''epsilon-greedy based on behavior network'''
## TODO ##
raise NotImplementedError
def append(self, state, action, reward, next_state, done):
self._memory.append(state, [action], [reward / 10], next_state,
[int(done)])
def update(self, total_steps):
if total_steps % self.freq == 0:
self._update_behavior_network(self.gamma)
if total_steps % self.target_freq == 0:
self._update_target_network()
def _update_behavior_network(self, gamma):
# sample a minibatch of transitions
state, action, reward, next_state, done = self._memory.sample(
self.batch_size, self.device)
## TODO ##
# q_value = ?
# with torch.no_grad():
# q_next = ?
# q_target = ?
# criterion = ?
# loss = criterion(q_value, q_target)
raise NotImplementedError
# optimize
self._optimizer.zero_grad()
loss.backward()
nn.utils.clip_grad_norm_(self._behavior_net.parameters(), 5)
self._optimizer.step()
def _update_target_network(self):
'''update target network by copying from behavior network'''
## TODO ##
raise NotImplementedError
def save(self, model_path, checkpoint=False):
if checkpoint:
torch.save(
{
'behavior_net': self._behavior_net.state_dict(),
'target_net': self._target_net.state_dict(),
'optimizer': self._optimizer.state_dict(),
}, model_path)
else:
torch.save({
'behavior_net': self._behavior_net.state_dict(),
}, model_path)
def load(self, model_path, checkpoint=False):
model = torch.load(model_path)
self._behavior_net.load_state_dict(model['behavior_net'])
if checkpoint:
self._target_net.load_state_dict(model['target_net'])
self._optimizer.load_state_dict(model['optimizer'])
def train(args, env_name, agent, writer):
print('Start Training')
env = gym.make(env_name)
action_space = env.action_space
total_steps, epsilon, ewma_reward = 0, 1., 0.
for episode in range(args.episode):
total_reward = 0
state = env.reset()
for t in itertools.count(start=1):
# select action
if total_steps < args.warmup:
action = action_space.sample()
else:
action = agent.select_action(state, epsilon, action_space)
epsilon = max(epsilon * args.eps_decay, args.eps_min)
# execute action
next_state, reward, done, _ = env.step(action)
# store transition
agent.append(state, action, reward, next_state, done)
if total_steps >= args.warmup:
agent.update(total_steps)
state = next_state
total_reward += reward
total_steps += 1
if done:
ewma_reward = 0.05 * total_reward + (1 - 0.05) * ewma_reward
writer.add_scalar('Train/Episode Reward', total_reward,
total_steps)
writer.add_scalar('Train/Ewma Reward', ewma_reward,
total_steps)
print(
'Step: {}\tEpisode: {}\tLength: {:3d}\tTotal reward: {:.2f}\tEwma reward: {:.2f}\tEpsilon: {:.3f}'
.format(total_steps, episode, t, total_reward, ewma_reward,
epsilon))
break
env.close()
def test(args, env_name, agent, writer):
print('Start Testing')
env = gym.make(env_name)
action_space = env.action_space
epsilon = args.test_epsilon
seeds = (args.seed + i for i in range(10))
rewards = []
for n_episode, seed in enumerate(seeds):
total_reward = 0
env.seed(seed)
state = env.reset()
## TODO ##
# ...
# if done:
# writer.add_scalar('Test/Episode Reward', total_reward, n_episode)
# ...
raise NotImplementedError
print('Average Reward', np.mean(rewards))
env.close()
def main():
## arguments ##
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('-d', '--device', default='cuda')
parser.add_argument('-m', '--model', default='dqn.pth')
parser.add_argument('--logdir', default='log/dqn')
# train
parser.add_argument('--warmup', default=10000, type=int)
parser.add_argument('--episode', default=1200, type=int)
parser.add_argument('--capacity', default=10000, type=int)
parser.add_argument('--batch_size', default=128, type=int)
parser.add_argument('--lr', default=.0005, type=float)
parser.add_argument('--eps_decay', default=.995, type=float)
parser.add_argument('--eps_min', default=.01, type=float)
parser.add_argument('--gamma', default=.99, type=float)
parser.add_argument('--freq', default=4, type=int)
parser.add_argument('--target_freq', default=1000, type=int)
# test
parser.add_argument('--test_only', action='store_true')
parser.add_argument('--render', action='store_true')
parser.add_argument('--seed', default=2021111, type=int)
parser.add_argument('--test_epsilon', default=.001, type=float)
args = parser.parse_args()
## main ##
env_name = 'LunarLander-v2'
agent = DQN(args)
writer = SummaryWriter(args.logdir)
if not args.test_only:
train(args, env_name, agent, writer)
agent.save(args.model)
agent.load(args.model)
test(args, env_name, agent, writer)
if __name__ == '__main__':
main()