-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathworker.py
265 lines (220 loc) · 10.8 KB
/
worker.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
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
264
##
## @package worker This is the worker class that is spun up for every available
## thread.
##
import tensorflow as tf
import numpy as np
from common.parse_args import ensure_dir
mse = tf.losses.mean_squared_error
##
## @brief Class for worker. Workers execute their own environment as well
## as push and pull values to and from the global network.
##
class Worker:
##
## @brief Constructs the object and initializes member variables.
##
## @param self The object
## @param number The number
## @param main The main
## @param env The environment
## @param actions The actions
## @param agent The agent
## @param global_episodes The global episodes
## @param name The name
## @param model_path The model path
## @param summary_dir The summary directory
## @param episodes_per_record The episodes per record
## @param episodes_for_model_checkpoint The episodes for model checkpoint
## @param buffer_min The buffer minimum
## @param buffer_max The buffer maximum
## @param max_episodes The maximum episodes
##
def __init__(self, number, main, env, actions, agent, global_episodes,
# keyword args
name=None, model_path=None, summary_dir="workerData/",
episodes_per_record=10, episodes_for_model_checkpoint=250,
buffer_min=10, buffer_max=30, max_episodes=10000):
self.number = number
self.name = (name or "worker_") + str(number)
self.model_path = model_path or summary_dir + "model"
ensure_dir(summary_dir)
ensure_dir(self.model_path)
self.buffer_min = buffer_min
self.buffer_max = buffer_max
self.global_episodes = global_episodes
self.increment = self.global_episodes.assign_add(1)
self.episodes_for_model_checkpoint = episodes_for_model_checkpoint
self.episodes_per_record = episodes_per_record
self.episode_rewards = np.zeros(episodes_per_record)
self.episode_real_rewards = np.zeros(episodes_per_record)
self.episode_lengths = np.zeros(episodes_per_record)
self.episode_mean_values = np.zeros(episodes_per_record)
self.max_episodes = max_episodes
self.summary_writer = tf.summary.FileWriter(summary_dir + self.name)
self.main = main
self.agent = agent
self.actions = actions
self.env = env
##
## @brief Workers train when episode buffers are full or after so many
## episodes. This function calls agent.train and updates the
## policy.
##
## @param self The object
## @param rollout The rollout
## @param sess The session
## @param bootstrap_value The bootstrap value
##
## @return Returns the network loss, accuracy, consistency, advantage,
## grad_norms, and var_norms.
##
def train(self, rollout, sess, bootstrap_value):
actions = np.array(rollout[0])
rewards = np.array(rollout[1])
observations = np.concatenate(rollout[2])
values = np.array(rollout[3] + [bootstrap_value])
#print(rewards)
#print(values)
loss, accuracy, consistency, advantage, grad_norms, var_norms = \
self.agent.train(sess, actions, rewards, observations, values)
self.agent.update_policy(sess)
return loss, \
accuracy, \
consistency, \
advantage, \
grad_norms, \
var_norms
##
## @brief Has the environment execute actions.
##
## @param self The object
## @param choice The choice
## @param env_obs The environment observation
##
## @return Reward feedback and the updated environment observation.
##
def do_actions(self, choice, env_obs):
feed_back = self.actions.act(choice, env_obs[0])
while True:
act_call, feed = self.actions.action_step(env_obs)
env_obs = self.env.step(actions=[act_call])
feed_back += feed
if not self.actions.actionq:
break
return feed_back, env_obs
##
## @brief This is the function that the worker spends most of it's time
## operating. Workers run a session where they reset everything
## and then run an instance of the environment. The environment
## will run until the episode is finished, at which point
## globals are pulled down and the values this worker generated
## are pushed up.
##
## @param self The object
## @param sess The session
## @param coord The coordinator
## @param saver The saver
##
##
def work(self, sess, coord, saver):
if self.number == 0:
self.summary_writer.add_graph(sess.graph)
checkpoint_steps = 0
per_point = self.episodes_per_record
episode_count = sess.run(self.global_episodes)
self.summary_writer.add_graph(sess.graph)
total_steps = 0
print("Starting worker " + str(self.number))
with sess.as_default(), sess.graph.as_default():
while not coord.should_stop() and episode_count < self.max_episodes:
self.agent.update_policy(sess)
episode_buffer = [[] for _ in range(4)]
episode_values = 0
episode_reward = 0
episode_step_count = 0
buffer_dumps = 0
loss = accuracy = consistency = advantage = gradient_norms = var_norms = 0
# Start new episode
env_obs = self.env.reset() # There is only one agent running, so [0]
self.actions.reset()
self.agent.policy.reset()
reward, obs, episode_end = self.agent.process_observation(env_obs)
while not episode_end:
choice, value = self.agent.step(sess, obs)
feedback, env_obs = self.do_actions(choice, env_obs)
reward, obs, episode_end = self.agent.process_observation(env_obs)
for i, v in enumerate([choice, reward + feedback, obs, value]):
episode_buffer[i].append(v)
episode_values += value
episode_reward += reward + feedback
episode_step_count += 1
if episode_end:
break
if len(episode_buffer[0]) == self.buffer_max:
buffer_dumps += 1
bootstrap = self.agent.value(sess, obs)
v = self.train(episode_buffer, sess, bootstrap)
loss += v[0]
accuracy += v[1]
consistency += v[2]
advantage += v[3]
gradient_norms += v[4]
var_norms += v[5]
episode_buffer = [feed[-self.buffer_min:] for feed in episode_buffer]
self.episode_real_rewards[episode_count % per_point] = episode_reward
self.episode_rewards[episode_count % per_point] = env_obs[0][1].resources_collected
self.episode_lengths[episode_count % per_point] = episode_step_count
self.episode_mean_values[episode_count % per_point] = episode_values / episode_step_count
episode_count += 1
self.main._episodes[self.number] = episode_count
print("{:6.0f} Episodes: "
"loss = {:13.4f}, "
"accuracy = {:13.4g}, "
"consistency = {:13.4g}, "
"advantage = {:13.4g}, "
"reward = {:8.1f}, "
"minerals = {:8.1f}, ".format(
np.sum(self.main._episodes), loss, accuracy,
consistency, advantage, episode_reward,
env_obs[0][1].resources_collected))
# Update the network using the episode buffer at the end of the episode
if len(episode_buffer) > self.buffer_min:
buffer_dumps += 1
bootstrap = self.agent.value(sess, obs)
v = self.train(episode_buffer, sess, bootstrap)
loss += v[0]
accuracy += v[1]
consistency += v[2]
advantage += v[3]
gradient_norms += v[4]
var_norms += v[5]
loss /= buffer_dumps
accuracy /= buffer_dumps
consistency /= buffer_dumps
advantage /= buffer_dumps
gradient_norms /= buffer_dumps
var_norms /= buffer_dumps
if episode_count % per_point == 0:
mean_reward = np.mean(self.episode_rewards)
mean_real_reward = np.mean(self.episode_real_rewards)
mean_value = np.mean(self.episode_mean_values)
summary = tf.Summary()
summary.value.add(tag="Perf/RealReward", simple_value=float(mean_real_reward))
summary.value.add(tag='Perf/Reward', simple_value=float(mean_reward))
summary.value.add(tag='Perf/Value', simple_value=float(mean_value))
summary.value.add(tag='Losses/Accuracy', simple_value=float(accuracy))
summary.value.add(tag='Losses/Consistency', simple_value=float(consistency))
summary.value.add(tag='Losses/Advantage', simple_value=float(advantage))
summary.value.add(tag='Losses/Grad Norm', simple_value=float(gradient_norms))
summary.value.add(tag='Losses/Var Norm', simple_value=float(var_norms))
self.summary_writer.add_summary(summary, episode_count)
self.summary_writer.flush()
if self.number == 0:
if checkpoint_steps > self.episodes_for_model_checkpoint:
checkpoint_steps = 0
saver.save(sess, self.model_path + '/model-' + str(episode_count) + '.cptk')
print("Saved Model")
else:
checkpoint_steps += 1
sess.run(self.increment)