|
| 1 | +import numpy as np |
| 2 | +import tensorflow as tf |
| 3 | + |
| 4 | +def build_shared_network(X, add_summaries=False): |
| 5 | + """ |
| 6 | + Builds a 3-layer network conv -> conv -> fc as described |
| 7 | + in the A3C paper. This network is shared by bother the policy and value net. |
| 8 | +
|
| 9 | + Args: |
| 10 | + X: Inputs |
| 11 | + add_summaries: If true, add layer summaries to Tensorboard. |
| 12 | +
|
| 13 | + Returns: |
| 14 | + Final layer activations. |
| 15 | + """ |
| 16 | + |
| 17 | + # Three convolutional layers |
| 18 | + conv1 = tf.contrib.layers.conv2d( |
| 19 | + X, 16, 8, 4, activation_fn=tf.nn.relu, scope="conv1") |
| 20 | + conv2 = tf.contrib.layers.conv2d( |
| 21 | + conv1, 32, 4, 2, activation_fn=tf.nn.relu, scope="conv2") |
| 22 | + |
| 23 | + # Fully connected layer |
| 24 | + fc1 = tf.contrib.layers.fully_connected( |
| 25 | + inputs=tf.contrib.layers.flatten(conv2), |
| 26 | + num_outputs=256, |
| 27 | + scope="fc1") |
| 28 | + |
| 29 | + if add_summaries: |
| 30 | + tf.contrib.layers.summarize_activation(conv1) |
| 31 | + tf.contrib.layers.summarize_activation(conv2) |
| 32 | + tf.contrib.layers.summarize_activation(fc1) |
| 33 | + |
| 34 | + return fc1 |
| 35 | + |
| 36 | +class PolicyEstimator(): |
| 37 | + """ |
| 38 | + Policy Function approximator. Given a observation, returns probabilities |
| 39 | + over all possible actions. |
| 40 | +
|
| 41 | + Args: |
| 42 | + num_outputs: Size of the action space. |
| 43 | + reuse: If true, an existing shared network will be re-used. |
| 44 | + trainable: If true we add train ops to the network. |
| 45 | + Actor threads that don't update their local models and don't need |
| 46 | + train ops would set this to false. |
| 47 | + """ |
| 48 | + |
| 49 | + def __init__(self, num_outputs, reuse=False, trainable=True): |
| 50 | + self.num_outputs = num_outputs |
| 51 | + |
| 52 | + # Placeholders for our input |
| 53 | + # Our input are 4 RGB frames of shape 160, 160 each |
| 54 | + self.states = tf.placeholder(shape=[None, 84, 84, 4], dtype=tf.uint8, name="X") |
| 55 | + # The TD target value |
| 56 | + self.targets = tf.placeholder(shape=[None], dtype=tf.float32, name="y") |
| 57 | + # Integer id of which action was selected |
| 58 | + self.actions = tf.placeholder(shape=[None], dtype=tf.int32, name="actions") |
| 59 | + |
| 60 | + # Normalize |
| 61 | + X = tf.to_float(self.states) / 255.0 |
| 62 | + batch_size = tf.shape(self.states)[0] |
| 63 | + |
| 64 | + # Graph shared with Value Net |
| 65 | + with tf.variable_scope("shared", reuse=reuse): |
| 66 | + fc1 = build_shared_network(X, add_summaries=(not reuse)) |
| 67 | + |
| 68 | + |
| 69 | + with tf.variable_scope("policy_net"): |
| 70 | + self.logits = tf.contrib.layers.fully_connected(fc1, num_outputs, activation_fn=None) |
| 71 | + self.probs = tf.nn.softmax(self.logits) + 1e-8 |
| 72 | + |
| 73 | + self.predictions = { |
| 74 | + "logits": self.logits, |
| 75 | + "probs": self.probs |
| 76 | + } |
| 77 | + |
| 78 | + # We add cross-entropy to the loss to encourage exploration |
| 79 | + self.cross_entropy = -tf.reduce_sum(self.probs * tf.log(self.probs), 1, name="cross_entropy") |
| 80 | + self.cross_entropy_mean = tf.reduce_mean(self.cross_entropy, name="cross_entropy_mean") |
| 81 | + |
| 82 | + # Get the predictions for the chosen actions only |
| 83 | + gather_indices = tf.range(batch_size) * tf.shape(self.probs)[1] + self.actions |
| 84 | + self.picked_action_probs = tf.gather(tf.reshape(self.probs, [-1]), gather_indices) |
| 85 | + |
| 86 | + self.losses = - (tf.log(self.picked_action_probs) * self.targets + 0.01 * self.cross_entropy) |
| 87 | + self.loss = tf.reduce_sum(self.losses, name="loss") |
| 88 | + |
| 89 | + tf.scalar_summary(self.loss.op.name, self.loss) |
| 90 | + tf.scalar_summary(self.cross_entropy_mean.op.name, self.cross_entropy_mean) |
| 91 | + tf.histogram_summary(self.cross_entropy.op.name, self.cross_entropy) |
| 92 | + |
| 93 | + if trainable: |
| 94 | + # self.optimizer = tf.train.AdamOptimizer(1e-4) |
| 95 | + self.optimizer = tf.train.RMSPropOptimizer(0.00025, 0.99, 0.0, 1e-6) |
| 96 | + self.grads_and_vars = self.optimizer.compute_gradients(self.loss) |
| 97 | + self.grads_and_vars = [[grad, var] for grad, var in self.grads_and_vars if grad is not None] |
| 98 | + self.train_op = self.optimizer.apply_gradients(self.grads_and_vars, |
| 99 | + global_step=tf.contrib.framework.get_global_step()) |
| 100 | + |
| 101 | + # Merge summaries from this network and the shared network (but not the value net) |
| 102 | + var_scope_name = tf.get_variable_scope().name |
| 103 | + summary_ops = tf.get_collection(tf.GraphKeys.SUMMARIES) |
| 104 | + sumaries = [s for s in summary_ops if "policy_net" in s.name or "shared" in s.name] |
| 105 | + sumaries = [s for s in summary_ops if var_scope_name in s.name] |
| 106 | + self.summaries = tf.merge_summary(sumaries) |
| 107 | + |
| 108 | + |
| 109 | +class ValueEstimator(): |
| 110 | + """ |
| 111 | + Value Function approximator. Returns a value estimator for a batch of observations. |
| 112 | +
|
| 113 | + Args: |
| 114 | + reuse: If true, an existing shared network will be re-used. |
| 115 | + trainable: If true we add train ops to the network. |
| 116 | + Actor threads that don't update their local models and don't need |
| 117 | + train ops would set this to false. |
| 118 | + """ |
| 119 | + |
| 120 | + def __init__(self, reuse=False, trainable=True): |
| 121 | + # Placeholders for our input |
| 122 | + # Our input are 4 RGB frames of shape 160, 160 each |
| 123 | + self.states = tf.placeholder(shape=[None, 84, 84, 4], dtype=tf.uint8, name="X") |
| 124 | + # The TD target value |
| 125 | + self.targets = tf.placeholder(shape=[None], dtype=tf.float32, name="y") |
| 126 | + |
| 127 | + X = tf.to_float(self.states) / 255.0 |
| 128 | + batch_size = tf.shape(self.states)[0] |
| 129 | + |
| 130 | + # Graph shared with Value Net |
| 131 | + with tf.variable_scope("shared", reuse=reuse): |
| 132 | + fc1 = build_shared_network(X, add_summaries=(not reuse)) |
| 133 | + |
| 134 | + with tf.variable_scope("value_net"): |
| 135 | + self.logits = tf.contrib.layers.fully_connected( |
| 136 | + inputs=fc1, |
| 137 | + num_outputs=1, |
| 138 | + activation_fn=None) |
| 139 | + self.logits = tf.squeeze(self.logits, squeeze_dims=[1], name="logits") |
| 140 | + |
| 141 | + self.losses = tf.squared_difference(self.logits, self.targets) |
| 142 | + self.loss = tf.reduce_sum(self.losses, name="loss") |
| 143 | + |
| 144 | + self.predictions = { |
| 145 | + "logits": self.logits |
| 146 | + } |
| 147 | + |
| 148 | + # Summaries |
| 149 | + prefix = tf.get_variable_scope().name |
| 150 | + tf.scalar_summary(self.loss.name, self.loss) |
| 151 | + tf.scalar_summary("{}/max_value".format(prefix), tf.reduce_max(self.logits)) |
| 152 | + tf.scalar_summary("{}/min_value".format(prefix), tf.reduce_min(self.logits)) |
| 153 | + tf.scalar_summary("{}/mean_value".format(prefix), tf.reduce_mean(self.logits)) |
| 154 | + tf.scalar_summary("{}/reward_max".format(prefix), tf.reduce_max(self.targets)) |
| 155 | + tf.scalar_summary("{}/reward_min".format(prefix), tf.reduce_min(self.targets)) |
| 156 | + tf.scalar_summary("{}/reward_mean".format(prefix), tf.reduce_mean(self.targets)) |
| 157 | + tf.histogram_summary("{}/reward_targets".format(prefix), self.targets) |
| 158 | + tf.histogram_summary("{}/values".format(prefix), self.logits) |
| 159 | + |
| 160 | + if trainable: |
| 161 | + # self.optimizer = tf.train.AdamOptimizer(1e-4) |
| 162 | + self.optimizer = tf.train.RMSPropOptimizer(0.00025, 0.99, 0.0, 1e-6) |
| 163 | + self.grads_and_vars = self.optimizer.compute_gradients(self.loss) |
| 164 | + self.grads_and_vars = [[grad, var] for grad, var in self.grads_and_vars if grad is not None] |
| 165 | + self.train_op = self.optimizer.apply_gradients(self.grads_and_vars, |
| 166 | + global_step=tf.contrib.framework.get_global_step()) |
| 167 | + |
| 168 | + var_scope_name = tf.get_variable_scope().name |
| 169 | + summary_ops = tf.get_collection(tf.GraphKeys.SUMMARIES) |
| 170 | + sumaries = [s for s in summary_ops if "policy_net" in s.name or "shared" in s.name] |
| 171 | + sumaries = [s for s in summary_ops if var_scope_name in s.name] |
| 172 | + self.summaries = tf.merge_summary(sumaries) |
0 commit comments