|
| 1 | +from __future__ import print_function |
| 2 | +from builtins import zip |
| 3 | +from builtins import range |
| 4 | +from builtins import object |
| 5 | +# Copyright 2018 The TensorFlow Authors All Rights Reserved. |
| 6 | +# |
| 7 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 8 | +# you may not use this file except in compliance with the License. |
| 9 | +# You may obtain a copy of the License at |
| 10 | +# |
| 11 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | +# |
| 13 | +# Unless required by applicable law or agreed to in writing, software |
| 14 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 15 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 16 | +# See the License for the specific language governing permissions and |
| 17 | +# limitations under the License. |
| 18 | +# ============================================================================== |
| 19 | + |
| 20 | +import numpy as np |
| 21 | +import tensorflow as tf |
| 22 | +import time, os, traceback, multiprocessing, portalocker |
| 23 | + |
| 24 | +import envwrap |
| 25 | +import valuerl |
| 26 | +import util |
| 27 | +from config import config |
| 28 | + |
| 29 | + |
| 30 | +def run_env(pipe): |
| 31 | + env = envwrap.get_env(config["env"]["name"]) |
| 32 | + reset = True |
| 33 | + while True: |
| 34 | + if reset is True: pipe.send(env.reset()) |
| 35 | + action = pipe.recv() |
| 36 | + obs, reward, done, reset = env.step(action) |
| 37 | + pipe.send((obs, reward, done, reset)) |
| 38 | + |
| 39 | +class AgentManager(object): |
| 40 | + """ |
| 41 | + Interact with the environment according to the learned policy, |
| 42 | + """ |
| 43 | + def __init__(self, proc_num, evaluation, policy_lock, batch_size, config): |
| 44 | + self.evaluation = evaluation |
| 45 | + self.policy_lock = policy_lock |
| 46 | + self.batch_size = batch_size |
| 47 | + self.config = config |
| 48 | + |
| 49 | + self.log_path = util.create_directory("%s/%s/%s/%s" % (config["output_root"], config["env"]["name"], config["name"], config["log_path"])) + "/%s" % config["name"] |
| 50 | + self.load_path = util.create_directory("%s/%s/%s/%s" % (config["output_root"], config["env"]["name"], config["name"], config["save_model_path"])) |
| 51 | + |
| 52 | + ## placeholders for intermediate states (basis for rollout) |
| 53 | + self.obs_loader = tf.placeholder(tf.float32, [self.batch_size, np.prod(self.config["env"]["obs_dims"])]) |
| 54 | + |
| 55 | + ## build model |
| 56 | + self.valuerl = valuerl.ValueRL(self.config["name"], self.config["env"], self.config["policy_config"]) |
| 57 | + self.policy_actions = self.valuerl.build_evalution_graph(self.obs_loader, mode="exploit" if self.evaluation else "explore") |
| 58 | + |
| 59 | + # interactors |
| 60 | + self.agent_pipes, self.agent_child_pipes = list(zip(*[multiprocessing.Pipe() for _ in range(self.batch_size)])) |
| 61 | + self.agents = [multiprocessing.Process(target=run_env, args=(self.agent_child_pipes[i],)) for i in range(self.batch_size)] |
| 62 | + for agent in self.agents: agent.start() |
| 63 | + self.obs = [pipe.recv() for pipe in self.agent_pipes] |
| 64 | + self.total_rewards = [0. for _ in self.agent_pipes] |
| 65 | + self.loaded_policy = False |
| 66 | + |
| 67 | + self.sess = tf.Session() |
| 68 | + self.sess.run(tf.global_variables_initializer()) |
| 69 | + |
| 70 | + self.rollout_i = 0 |
| 71 | + self.proc_num = proc_num |
| 72 | + self.epoch = -1 |
| 73 | + self.frame_total = 0 |
| 74 | + self.hours = 0. |
| 75 | + |
| 76 | + self.first = True |
| 77 | + |
| 78 | + def get_action(self, obs): |
| 79 | + if self.loaded_policy: |
| 80 | + all_actions = self.sess.run(self.policy_actions, feed_dict={self.obs_loader: obs}) |
| 81 | + all_actions = np.clip(all_actions, -1., 1.) |
| 82 | + return all_actions[:self.batch_size] |
| 83 | + else: |
| 84 | + return [self.get_random_action() for _ in range(obs.shape[0])] |
| 85 | + |
| 86 | + def get_random_action(self, *args, **kwargs): |
| 87 | + return np.random.random(self.config["env"]["action_dim"]) * 2 - 1 |
| 88 | + |
| 89 | + def step(self): |
| 90 | + actions = self.get_action(np.stack(self.obs)) |
| 91 | + self.first = False |
| 92 | + [pipe.send(action) for pipe, action in zip(self.agent_pipes, actions)] |
| 93 | + next_obs, rewards, dones, resets = list(zip(*[pipe.recv() for pipe in self.agent_pipes])) |
| 94 | + |
| 95 | + frames = list(zip(self.obs, next_obs, actions, rewards, dones)) |
| 96 | + |
| 97 | + self.obs = [o if resets[i] is False else self.agent_pipes[i].recv() for i, o in enumerate(next_obs)] |
| 98 | + |
| 99 | + for i, (t,r,reset) in enumerate(zip(self.total_rewards, rewards, resets)): |
| 100 | + if reset: |
| 101 | + self.total_rewards[i] = 0. |
| 102 | + if self.evaluation and self.loaded_policy: |
| 103 | + with portalocker.Lock(self.log_path+'.greedy.csv', mode="a") as f: f.write("%2f,%d,%d,%2f\n" % (self.hours, self.epoch, self.frame_total, t+r)) |
| 104 | + |
| 105 | + else: |
| 106 | + self.total_rewards[i] = t + r |
| 107 | + |
| 108 | + if self.evaluation and np.any(resets): self.reload() |
| 109 | + |
| 110 | + self.rollout_i += 1 |
| 111 | + return frames |
| 112 | + |
| 113 | + def reload(self): |
| 114 | + if not os.path.exists("%s/%s.params.index" % (self.load_path ,self.valuerl.saveid)): return False |
| 115 | + with self.policy_lock: |
| 116 | + self.valuerl.load(self.sess, self.load_path) |
| 117 | + self.epoch, self.frame_total, self.hours = self.sess.run([self.valuerl.epoch_n, self.valuerl.frame_n, self.valuerl.hours]) |
| 118 | + self.loaded_policy = True |
| 119 | + self.first = True |
| 120 | + return True |
| 121 | + |
| 122 | +def main(proc_num, evaluation, policy_replay_frame_queue, model_replay_frame_queue, policy_lock, config): |
| 123 | + try: |
| 124 | + np.random.seed((proc_num * int(time.time())) % (2 ** 32 - 1)) |
| 125 | + agentmanager = AgentManager(proc_num, evaluation, policy_lock, config["evaluator_config"]["batch_size"] if evaluation else config["agent_config"]["batch_size"], config) |
| 126 | + frame_i = 0 |
| 127 | + while True: |
| 128 | + new_frames = agentmanager.step() |
| 129 | + if not evaluation: |
| 130 | + policy_replay_frame_queue.put(new_frames) |
| 131 | + if model_replay_frame_queue is not None: model_replay_frame_queue.put(new_frames) |
| 132 | + if frame_i % config["agent_config"]["reload_every_n"] == 0: agentmanager.reload() |
| 133 | + frame_i += len(new_frames) |
| 134 | + |
| 135 | + except Exception as e: |
| 136 | + print('Caught exception in agent process %d' % proc_num) |
| 137 | + traceback.print_exc() |
| 138 | + print() |
| 139 | + try: |
| 140 | + for i in agentmanager.agents: i.join() |
| 141 | + except: |
| 142 | + pass |
| 143 | + raise e |
0 commit comments