-
Notifications
You must be signed in to change notification settings - Fork 2
/
lunar_lander_ape-x-SAC.py
194 lines (162 loc) · 8.14 KB
/
lunar_lander_ape-x-SAC.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
import gym
import numpy as np
import os
import tensorflow as tf
from tensorflow import keras
from time import sleep
from APEX.APEX_Rank_Priority_MemoryBuffer import APEX_Rank_Priority_MemoryBuffer
from APEX.neural_networks import sac_policy_network, sac_value_network
from APEX.sac_actor import RunActor
from APEX.sac_learner import RunLearner
from multiprocessing import Process, Pipe, Value
from threading import Thread, Lock
if __name__ == '__main__':
orchestrator_debug_mode = False
networks_initialized = False
def orchestrator_log(msg):
if orchestrator_debug_mode:
print(f'[Orchestrator] {msg}')
def actor_cmd_processor(actor, value_net, replay_buffer, cmd_pipe, actor_weight_pipes, replay_data_pipes, net_sync_obj, data_sync_obj):
global alpha_log
connection_alive = True
while connection_alive:
try:
cmd = cmd_pipe.recv()
orchestrator_log(f'Got actor {cmd[1]} command {cmd[0]}')
if cmd[0] == 0:
with net_sync_obj:
actor_weight_pipes[cmd[1]][1].send([actor.get_weights(), value_net.get_weights()])
orchestrator_log(f'Sent target weights for actor {cmd[1]}')
continue
if cmd[0] == 1:
replay_data = replay_data_pipes[cmd[1]][0].recv()
with data_sync_obj:
for r in replay_data:
# state, action, next_state, reward, gamma_power, done, td_error
replay_buffer.store(r[0], r[1], r[2], r[3], r[4], r[5], r[6])
orchestrator_log(f'Got replay data from actor {cmd[1]}')
continue
except EOFError:
print("Connection closed.")
connection_alive = False
except OSError:
print('Handle closed.')
connection_alive = False
def learner_cmd_processor(actor, value_net, replay_buffer, cmd_pipe, learner_weights_pipe, replay_data_pipe, priorities_pipe, net_sync_obj, data_sync_obj):
global networks_initialized
connection_alive = True
while connection_alive:
try:
cmd = cmd_pipe.recv()
orchestrator_log(f'Got learner command {cmd}')
if cmd == 0: # update target networks
weights = learner_weights_pipe.recv()
with net_sync_obj:
actor.set_weights(weights[0])
value_net.set_weights(weights[1])
networks_initialized = True
orchestrator_log(f'Target networks are updated')
continue
if cmd == 1: # fetch N batches of data
data = []
with data_sync_obj:
for _ in range(learner_prefetch_batches):
data.append([*replay_buffer()])
replay_data_pipe.send(data)
orchestrator_log(f'Sent {learner_prefetch_batches} batches of data to learner')
continue
if cmd == 2: # update priorities
data = priorities_pipe.recv()
with data_sync_obj:
for r in data:
replay_buffer.update_priorities(r[0], r[1])
continue
except EOFError:
print("Connection closed.")
connection_alive = False
except OSError:
print('Handle closed.')
connection_alive = False
# prevent TensorFlow of allocating whole GPU memory. Must be called in every module
gpus = tf.config.experimental.list_physical_devices('GPU')
tf.config.experimental.set_memory_growth(gpus[0], True)
env = gym.make('LunarLanderContinuous-v2')
learner_batch_size = 128
learner_prefetch_batches = 16
actor_learning_rate = 3e-4
critic_learning_rate = 3e-4
gamma = 0.99
actors_count = 6
exp_buffer = APEX_Rank_Priority_MemoryBuffer(1000000, learner_batch_size, env.observation_space.shape, env.action_space.shape)
weights_sync = Lock()
data_sync = Lock()
actor_cmd_read_pipe, actor_cmd_write_pipe = Pipe(False)
learner_cmd_read_pipe, learner_cmd_write_pipe = Pipe(False)
learner_weights_read_pipe, learner_weights_write_pipe = Pipe(False)
learner_priorities_read_pipe, learner_priorities_write_pipe = Pipe(False)
learner_replay_data_read_pipe, learner_replay_data_write_pipe = Pipe(False)
replay_data_distribution_pipes = []
weights_distribution_pipes = []
actor_processess = []
policy_net = sac_policy_network((env.observation_space.shape[0]), env.action_space.shape[0])
value_network = sac_value_network((env.observation_space.shape[0]))
cancelation_token = Value('i', 0)
training_active_flag = Value('i', 0)
buffer_ready = Value('i', 0)
# Agenda
# 1. Init networks at learner
# 2. Distribute target networks to actors
# 3. Fill up replay buffer
# 4. Start learning
actor_cmd_processor_thread = Thread(target=actor_cmd_processor, args=(policy_net, value_network, exp_buffer, \
actor_cmd_read_pipe, weights_distribution_pipes, replay_data_distribution_pipes, \
weights_sync, data_sync))
actor_cmd_processor_thread.start()
learner_cmd_processor_thread = Thread(target=learner_cmd_processor, args=(policy_net, value_network, exp_buffer, \
learner_cmd_read_pipe, learner_weights_read_pipe, learner_replay_data_write_pipe, learner_priorities_read_pipe, \
weights_sync, data_sync))
learner_cmd_processor_thread.start()
# 1. Init networks at learner
learner_process = Process(target=RunLearner, args=(learner_batch_size, gamma, actor_learning_rate, critic_learning_rate, \
(env.observation_space.shape[0],), (env.action_space.shape[0],), \
learner_cmd_write_pipe, learner_weights_write_pipe, learner_replay_data_read_pipe, learner_priorities_write_pipe, \
cancelation_token, training_active_flag, buffer_ready))
learner_process.start()
while not networks_initialized:
sleep(1)
# 2. Distribute target networks to actors
for i in range(actors_count):
weights_read_pipe, weights_write_pipe = Pipe(False)
weights_distribution_pipes.append((weights_read_pipe, weights_write_pipe))
replay_data_read_pipe, replay_data_write_pipe = Pipe(False)
replay_data_distribution_pipes.append((replay_data_read_pipe, replay_data_write_pipe))
p = Process(target=RunActor, args=(i, gamma, \
actor_cmd_write_pipe, weights_read_pipe, replay_data_write_pipe, \
cancelation_token, training_active_flag))
actor_processess.append(p)
p.start()
print("Awaiting buffer fill up")
# 3. Fill up replay buffer
while len(exp_buffer) < learner_batch_size * learner_prefetch_batches:
sleep(1)
# 4. Start learning
buffer_ready.value = 1
input("training networks.\nPress enter to finish\n\n")
cancelation_token.value = 1
actor_cmd_read_pipe.close()
actor_cmd_write_pipe.close()
actor_cmd_processor_thread.join()
learner_cmd_read_pipe.close()
learner_cmd_write_pipe.close()
learner_replay_data_write_pipe.close()
learner_replay_data_read_pipe.close()
learner_priorities_read_pipe.close()
learner_priorities_write_pipe.close()
learner_cmd_processor_thread.join()
for i in range(len(weights_distribution_pipes)):
weights_distribution_pipes[i][0].close()
weights_distribution_pipes[i][1].close()
replay_data_distribution_pipes[i][0].close()
weights_distribution_pipes[i][1].close()
actor_processess[i].join()
learner_process.join()