model.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. # Copyright 2017 Google Inc. All Rights Reserved.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. #
  15. # ==============================================================================
  16. """Model using memory component.
  17. The model embeds images using a standard CNN architecture.
  18. These embeddings are used as keys to the memory component,
  19. which returns nearest neighbors.
  20. """
  21. import tensorflow as tf
  22. import memory
  23. FLAGS = tf.flags.FLAGS
  24. class BasicClassifier(object):
  25. def __init__(self, output_dim):
  26. self.output_dim = output_dim
  27. def core_builder(self, memory_val, x, y):
  28. del x, y
  29. y_pred = memory_val
  30. loss = 0.0
  31. return loss, y_pred
  32. class LeNet(object):
  33. """Standard CNN architecture."""
  34. def __init__(self, image_size, num_channels, hidden_dim):
  35. self.image_size = image_size
  36. self.num_channels = num_channels
  37. self.hidden_dim = hidden_dim
  38. self.matrix_init = tf.truncated_normal_initializer(stddev=0.1)
  39. self.vector_init = tf.constant_initializer(0.0)
  40. def core_builder(self, x):
  41. """Embeds x using standard CNN architecture.
  42. Args:
  43. x: Batch of images as a 2-d Tensor [batch_size, -1].
  44. Returns:
  45. A 2-d Tensor [batch_size, hidden_dim] of embedded images.
  46. """
  47. ch1 = 32 * 2 # number of channels in 1st layer
  48. ch2 = 64 * 2 # number of channels in 2nd layer
  49. conv1_weights = tf.get_variable('conv1_w',
  50. [3, 3, self.num_channels, ch1],
  51. initializer=self.matrix_init)
  52. conv1_biases = tf.get_variable('conv1_b', [ch1],
  53. initializer=self.vector_init)
  54. conv1a_weights = tf.get_variable('conv1a_w',
  55. [3, 3, ch1, ch1],
  56. initializer=self.matrix_init)
  57. conv1a_biases = tf.get_variable('conv1a_b', [ch1],
  58. initializer=self.vector_init)
  59. conv2_weights = tf.get_variable('conv2_w', [3, 3, ch1, ch2],
  60. initializer=self.matrix_init)
  61. conv2_biases = tf.get_variable('conv2_b', [ch2],
  62. initializer=self.vector_init)
  63. conv2a_weights = tf.get_variable('conv2a_w', [3, 3, ch2, ch2],
  64. initializer=self.matrix_init)
  65. conv2a_biases = tf.get_variable('conv2a_b', [ch2],
  66. initializer=self.vector_init)
  67. # fully connected
  68. fc1_weights = tf.get_variable(
  69. 'fc1_w', [self.image_size // 4 * self.image_size // 4 * ch2,
  70. self.hidden_dim], initializer=self.matrix_init)
  71. fc1_biases = tf.get_variable('fc1_b', [self.hidden_dim],
  72. initializer=self.vector_init)
  73. # define model
  74. x = tf.reshape(x,
  75. [-1, self.image_size, self.image_size, self.num_channels])
  76. batch_size = tf.shape(x)[0]
  77. conv1 = tf.nn.conv2d(x, conv1_weights,
  78. strides=[1, 1, 1, 1], padding='SAME')
  79. relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1_biases))
  80. conv1 = tf.nn.conv2d(relu1, conv1a_weights,
  81. strides=[1, 1, 1, 1], padding='SAME')
  82. relu1 = tf.nn.relu(tf.nn.bias_add(conv1, conv1a_biases))
  83. pool1 = tf.nn.max_pool(relu1, ksize=[1, 2, 2, 1],
  84. strides=[1, 2, 2, 1], padding='SAME')
  85. conv2 = tf.nn.conv2d(pool1, conv2_weights,
  86. strides=[1, 1, 1, 1], padding='SAME')
  87. relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2_biases))
  88. conv2 = tf.nn.conv2d(relu2, conv2a_weights,
  89. strides=[1, 1, 1, 1], padding='SAME')
  90. relu2 = tf.nn.relu(tf.nn.bias_add(conv2, conv2a_biases))
  91. pool2 = tf.nn.max_pool(relu2, ksize=[1, 2, 2, 1],
  92. strides=[1, 2, 2, 1], padding='SAME')
  93. reshape = tf.reshape(pool2, [batch_size, -1])
  94. hidden = tf.matmul(reshape, fc1_weights) + fc1_biases
  95. return hidden
  96. class Model(object):
  97. """Model for coordinating between CNN embedder and Memory module."""
  98. def __init__(self, input_dim, output_dim, rep_dim, memory_size, vocab_size,
  99. learning_rate=0.0001, use_lsh=False):
  100. self.input_dim = input_dim
  101. self.output_dim = output_dim
  102. self.rep_dim = rep_dim
  103. self.memory_size = memory_size
  104. self.vocab_size = vocab_size
  105. self.learning_rate = learning_rate
  106. self.use_lsh = use_lsh
  107. self.embedder = self.get_embedder()
  108. self.memory = self.get_memory()
  109. self.classifier = self.get_classifier()
  110. self.global_step = tf.contrib.framework.get_or_create_global_step()
  111. def get_embedder(self):
  112. return LeNet(int(self.input_dim ** 0.5), 1, self.rep_dim)
  113. def get_memory(self):
  114. cls = memory.LSHMemory if self.use_lsh else memory.Memory
  115. return cls(self.rep_dim, self.memory_size, self.vocab_size)
  116. def get_classifier(self):
  117. return BasicClassifier(self.output_dim)
  118. def core_builder(self, x, y, keep_prob, use_recent_idx=True):
  119. embeddings = self.embedder.core_builder(x)
  120. if keep_prob < 1.0:
  121. embeddings = tf.nn.dropout(embeddings, keep_prob)
  122. memory_val, _, teacher_loss = self.memory.query(
  123. embeddings, y, use_recent_idx=use_recent_idx)
  124. loss, y_pred = self.classifier.core_builder(memory_val, x, y)
  125. return loss + teacher_loss, y_pred
  126. def train(self, x, y):
  127. loss, _ = self.core_builder(x, y, keep_prob=0.3)
  128. gradient_ops = self.training_ops(loss)
  129. return loss, gradient_ops
  130. def eval(self, x, y):
  131. _, y_preds = self.core_builder(x, y, keep_prob=1.0,
  132. use_recent_idx=False)
  133. return y_preds
  134. def get_xy_placeholders(self):
  135. return (tf.placeholder(tf.float32, [None, self.input_dim]),
  136. tf.placeholder(tf.int32, [None]))
  137. def setup(self):
  138. """Sets up all components of the computation graph."""
  139. self.x, self.y = self.get_xy_placeholders()
  140. with tf.variable_scope('core', reuse=None):
  141. self.loss, self.gradient_ops = self.train(self.x, self.y)
  142. with tf.variable_scope('core', reuse=True):
  143. self.y_preds = self.eval(self.x, self.y)
  144. # setup memory "reset" ops
  145. (self.mem_keys, self.mem_vals,
  146. self.mem_age, self.recent_idx) = self.memory.get()
  147. self.mem_keys_reset = tf.placeholder(self.mem_keys.dtype,
  148. tf.identity(self.mem_keys).shape)
  149. self.mem_vals_reset = tf.placeholder(self.mem_vals.dtype,
  150. tf.identity(self.mem_vals).shape)
  151. self.mem_age_reset = tf.placeholder(self.mem_age.dtype,
  152. tf.identity(self.mem_age).shape)
  153. self.recent_idx_reset = tf.placeholder(self.recent_idx.dtype,
  154. tf.identity(self.recent_idx).shape)
  155. self.mem_reset_op = self.memory.set(self.mem_keys_reset,
  156. self.mem_vals_reset,
  157. self.mem_age_reset,
  158. None)
  159. def training_ops(self, loss):
  160. opt = self.get_optimizer()
  161. params = tf.trainable_variables()
  162. gradients = tf.gradients(loss, params)
  163. clipped_gradients, _ = tf.clip_by_global_norm(gradients, 5.0)
  164. return opt.apply_gradients(zip(clipped_gradients, params),
  165. global_step=self.global_step)
  166. def get_optimizer(self):
  167. return tf.train.AdamOptimizer(learning_rate=self.learning_rate,
  168. epsilon=1e-4)
  169. def one_step(self, sess, x, y):
  170. outputs = [self.loss, self.gradient_ops]
  171. return sess.run(outputs, feed_dict={self.x: x, self.y: y})
  172. def episode_step(self, sess, x, y, clear_memory=False):
  173. """Performs training steps on episodic input.
  174. Args:
  175. sess: A Tensorflow Session.
  176. x: A list of batches of images defining the episode.
  177. y: A list of batches of labels corresponding to x.
  178. clear_memory: Whether to clear the memory before the episode.
  179. Returns:
  180. List of losses the same length as the episode.
  181. """
  182. outputs = [self.loss, self.gradient_ops]
  183. if clear_memory:
  184. self.clear_memory(sess)
  185. losses = []
  186. for xx, yy in zip(x, y):
  187. out = sess.run(outputs, feed_dict={self.x: xx, self.y: yy})
  188. loss = out[0]
  189. losses.append(loss)
  190. return losses
  191. def predict(self, sess, x, y=None):
  192. """Predict the labels on a single batch of examples.
  193. Args:
  194. sess: A Tensorflow Session.
  195. x: A batch of images.
  196. y: The labels for the images in x.
  197. This allows for updating the memory.
  198. Returns:
  199. Predicted y.
  200. """
  201. cur_memory = sess.run([self.mem_keys, self.mem_vals,
  202. self.mem_age])
  203. outputs = [self.y_preds]
  204. if y is None:
  205. ret = sess.run(outputs, feed_dict={self.x: x})
  206. else:
  207. ret = sess.run(outputs, feed_dict={self.x: x, self.y: y})
  208. sess.run([self.mem_reset_op],
  209. feed_dict={self.mem_keys_reset: cur_memory[0],
  210. self.mem_vals_reset: cur_memory[1],
  211. self.mem_age_reset: cur_memory[2]})
  212. return ret
  213. def episode_predict(self, sess, x, y, clear_memory=False):
  214. """Predict the labels on an episode of examples.
  215. Args:
  216. sess: A Tensorflow Session.
  217. x: A list of batches of images.
  218. y: A list of labels for the images in x.
  219. This allows for updating the memory.
  220. clear_memory: Whether to clear the memory before the episode.
  221. Returns:
  222. List of predicted y.
  223. """
  224. cur_memory = sess.run([self.mem_keys, self.mem_vals,
  225. self.mem_age])
  226. if clear_memory:
  227. self.clear_memory(sess)
  228. outputs = [self.y_preds]
  229. y_preds = []
  230. for xx, yy in zip(x, y):
  231. out = sess.run(outputs, feed_dict={self.x: xx, self.y: yy})
  232. y_pred = out[0]
  233. y_preds.append(y_pred)
  234. sess.run([self.mem_reset_op],
  235. feed_dict={self.mem_keys_reset: cur_memory[0],
  236. self.mem_vals_reset: cur_memory[1],
  237. self.mem_age_reset: cur_memory[2]})
  238. return y_preds
  239. def clear_memory(self, sess):
  240. sess.run([self.memory.clear()])