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
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
|
- """
- This file is copied/apdated from https://github.com/berkeleydeeprlcourse/homework/tree/master/hw3
- """
- import sys
- import pickle
- import numpy as np
- from collections import namedtuple
- from itertools import count
- import random
- import gym.spaces
- import json
- import torch
- import torch.autograd as autograd
- from utils.replay_buffer import ReplayBuffer
- from utils.gym import get_wrapper_by_name
- USE_CUDA = torch.cuda.is_available()
- print("USE_CUDA=", USE_CUDA)
- dtype = torch.cuda.FloatTensor if USE_CUDA else torch.FloatTensor
- longType = torch.cuda.LongTensor if USE_CUDA else torch.LongTensor
- class Variable(autograd.Variable):
- def __init__(self, data, *args, **kwargs):
- if USE_CUDA:
- data = data.cuda()
- super(Variable, self).__init__(data, *args, **kwargs)
- """
- OptimizerSpec containing following attributes
- constructor: The optimizer constructor ex: RMSprop
- kwargs: {Dict} arguments for constructing optimizer
- """
- OptimizerSpec = namedtuple("OptimizerSpec", ["constructor", "kwargs"])
- def double_dqn_learning(
- env,
- q_func,
- optimizer_spec,
- exploration,
- stopping_criterion=None,
- replay_buffer_size=1000000,
- batch_size=32,
- gamma=0.99,
- learning_starts=50000,
- learning_freq=4,
- frame_history_len=4,
- target_update_freq=10000,
- save_path=None,
- save_freq=100000,
- log_every_n_steps=3000,
- loss="bellman",
- **kwargs # To avoid complaints of unknown keywords
- ):
- """
- Similar to dqn_learn.py, but implements double DQN learning instead of normal DQN:
- https://arxiv.org/abs/1509.06461.pdf
- """
- assert type(env.observation_space) == gym.spaces.Box
- assert type(env.action_space) == gym.spaces.Discrete
- ###############
- # BUILD MODEL #
- ###############
- if len(env.observation_space.shape) == 1:
- # This means we are running on low-dimensional observations (e.g. RAM)
- input_arg = env.observation_space.shape[0]
- else:
- img_h, img_w, img_c = env.observation_space.shape
- input_arg = frame_history_len * img_c
- num_actions = env.action_space.n
- def to_pytorch(obs, type=dtype, normalize=True):
- t = torch.from_numpy(obs).type(type)
- if normalize:
- return t / 255.0
- else:
- return t
- def to_pytorch_var(x, grad=False, type=dtype, normalize=True):
- return Variable(to_pytorch(x, type=type, normalize=normalize), requires_grad=grad)
- # Construct an epilson greedy policy with given exploration schedule
- def select_epsilon_greedy_action(model, obs, t):
- sample = random.random()
- eps_threshold = exploration.value(t)
- if sample > eps_threshold:
- obs = to_pytorch(obs).unsqueeze(0)
- # Use volatile = True if variable is only used in inference mode, i.e. don’t save the history
- return model(Variable(obs, volatile=True)).data.max(1)[1].cpu()
- else:
- return torch.IntTensor([[random.randrange(num_actions)]])
- # Initialize target q function and q function, i.e. build the model.
- ######
- # YOUR CODE HERE
- print("Input and output size of network:")
- print(input_arg, num_actions)
- Q = q_func(input_arg, num_actions)
- Q_target = q_func(input_arg, num_actions)
- bellman_l1_loss = torch.nn.SmoothL1Loss(size_average=False)
- if USE_CUDA:
- Q = Q.cuda()
- Q_target = Q_target.cuda()
- Q_target.load_state_dict(Q.state_dict())
- def switch_Q_functions():
- print("Switching Q functions")
- q_state_dict = Q.state_dict()
- q_target_state_dict = Q_target.state_dict()
- Q.load_state_dict(q_target_state_dict)
- Q_target.load_state_dict(q_state_dict)
- ######
- # Construct Q network optimizer function
- optimizer = optimizer_spec.constructor(Q.parameters(), **optimizer_spec.kwargs)
- replay_buffer = ReplayBuffer(replay_buffer_size, frame_history_len)
- start_step = 0
- start_episode = 0
- Statistic = {
- "episode_rewards": []
- }
- def update_stats(t,episode,reward):
- rewards = Statistic["episode_rewards"]
- if len(rewards) == 0 or \
- rewards[-1][1] < episode:
- stat_tuple = (t, episode, reward)
- # print("Updating stats with ", stat_tuple)
- rewards.append(stat_tuple)
- def get_mean_episode_rewards(range):
- return np.mean([r for (_,_,r) in Statistic["episode_rewards"][-range:]])
- if save_path is not None:
- try:
- print("Trying to load state from ", save_path)
- with open(save_path + ".Q.pkl", 'rb') as f:
- Q.load_state_dict(pickle.load(f))
- with open(save_path + ".Q_target.pkl", 'rb') as f:
- Q_target.load_state_dict(pickle.load(f))
- with open(save_path + ".stats.json", 'r') as f:
- saved_stats = json.load(f)
- Statistic = saved_stats["stats"]
- start_step = saved_stats["timestep"]
- start_episode = saved_stats["episode"]
- except Exception as e:
- print("Saved state doesn't exist yet (probably)")
- print(e)
- def save_state(t,episode):
- """
- Saves the current stable network weights, together with the current time step and statistics, for resuming later.
- """
- if save_path is not None:
- print("Saving state")
- with open(save_path + ".Q.pkl", 'wb') as f:
- pickle.dump(Q.state_dict(), f, pickle.HIGHEST_PROTOCOL)
- with open(save_path + ".Q_target.pkl", 'wb') as f:
- pickle.dump(Q.state_dict(), f, pickle.HIGHEST_PROTOCOL)
- with open(save_path + ".stats.json", 'w') as f:
- saved_stats = {
- "timestep": t,
- "episode": episode,
- "stats": Statistic
- }
- json.dump(saved_stats, f)
- ###############
- # RUN ENV #
- ###############
- num_param_updates = 0
- last_obs = env.reset()
- for t in count(start=start_step):
- ### 1. Check stopping criterion
- if stopping_criterion is not None and stopping_criterion(env):
- break
- ### 2. Step the env and store the transition
- last_frame_idx = replay_buffer.store_frame(last_obs)
- enc_last_obs = replay_buffer.encode_recent_observation()
- action = select_epsilon_greedy_action(Q, enc_last_obs, t)
- new_frame, r, done, _ = env.step(action)
- replay_buffer.store_effect(last_frame_idx, action, r, done)
- if done:
- last_obs = env.reset()
- else:
- last_obs = new_frame
- #####
- ### 3. Perform experience replay and train the network.
- if (t > learning_starts and
- t % learning_freq == 0 and
- replay_buffer.can_sample(batch_size)):
- optimizer.zero_grad()
- obs_batch, act_batch, r_batch, next_obs_batch, done_mask = replay_buffer.sample(batch_size)
- Q_val_batch = Q(to_pytorch_var(obs_batch))
- Q_target_val_batch = Q_target(to_pytorch_var(next_obs_batch)).detach()
- # The following code will take only one cell from each vector of the Q_val_batch tensor.
- # Each vector corresponds to a single output of the Q net, and each cell corresponds to a single action.
- # This means we take only the cells of the actions that we actually took, since all others are irrelevant
- # when calculating the loss.
- act_batch_var = to_pytorch_var(act_batch, type=longType, normalize=False).unsqueeze(1)
- vals_of_actions_taken = Q_val_batch.gather(1, act_batch_var)
- # Here is the difference from normal DQN -
- # we select the maximal value action according to Q, and evaluate it according to Q_target
- Q_next_val_batch = Q(to_pytorch_var(next_obs_batch)).detach()
- _, Q_next_val_max_action = Q_next_val_batch.max(1)
- Q_next_val_max_action = Q_next_val_max_action.unsqueeze(1)
- Q_target_next_val_estimate = Q_target_val_batch.gather(1, Q_next_val_max_action)
- reverse_done_mask = 1 - to_pytorch_var(done_mask, normalize=False).unsqueeze(1)
- Q_target_masked_next_val_estimate = (reverse_done_mask * Q_target_next_val_estimate)
- Q_target_discounted = (gamma * Q_target_masked_next_val_estimate)
- r_batch_var = to_pytorch_var(r_batch, normalize=False).unsqueeze(1)
- Q_target_vals = r_batch_var + Q_target_discounted
- if loss == 'l1':
- bellman_l1_loss(vals_of_actions_taken, Q_target_vals).backward()
- else:
- bellman_error = Q_target_vals - vals_of_actions_taken
- clipped_error = bellman_error.clamp(-1, 1)
- vals_of_actions_taken.backward(-clipped_error)
- optimizer.step()
- num_param_updates += 1
- if num_param_updates % target_update_freq == 0:
- switch_Q_functions()
- ### 4. Log progress and keep track of statistics
- episode_rewards = get_wrapper_by_name(env, "Monitor").get_episode_rewards()
- episode_count = len(episode_rewards)
- total_episodes = start_episode + episode_count
- if episode_count > 0:
- update_stats(t, total_episodes, episode_rewards[-1])
- if t % log_every_n_steps == 0 and t > learning_starts and t > start_step:
- print("Timestep %d" % (t,))
- print("Episode %d" % (total_episodes,))
- print("mean reward (100 episodes) %f" % get_mean_episode_rewards(100))
- print("mean reward (10 episodes) %f" % get_mean_episode_rewards(10))
- print("exploration %f" % exploration.value(t))
- sys.stdout.flush()
- if t % save_freq == 0 and t > start_step:
- save_state(t,total_episodes)
|