swivel.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2016 Google Inc. All Rights Reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. """Submatrix-wise Vector Embedding Learner.
  17. Implementation of SwiVel algorithm described at:
  18. http://arxiv.org/abs/1602.02215
  19. This program expects an input directory that contains the following files.
  20. row_vocab.txt, col_vocab.txt
  21. The row an column vocabulary files. Each file should contain one token per
  22. line; these will be used to generate a tab-separate file containing the
  23. trained embeddings.
  24. row_sums.txt, col_sum.txt
  25. The matrix row and column marginal sums. Each file should contain one
  26. decimal floating point number per line which corresponds to the marginal
  27. count of the matrix for that row or column.
  28. shards.recs
  29. A file containing the sub-matrix shards, stored as TFRecords. Each shard is
  30. expected to be a serialzed tf.Example protocol buffer with the following
  31. properties:
  32. global_row: the global row indicies contained in the shard
  33. global_col: the global column indicies contained in the shard
  34. sparse_local_row, sparse_local_col, sparse_value: three parallel arrays
  35. that are a sparse representation of the submatrix counts.
  36. It will generate embeddings, training from the input directory for the specified
  37. number of epochs. When complete, it will output the trained vectors to a
  38. tab-separated file that contains one line per embedding. Row and column
  39. embeddings are stored in separate files.
  40. """
  41. from __future__ import print_function
  42. import argparse
  43. import glob
  44. import math
  45. import os
  46. import sys
  47. import time
  48. import threading
  49. import numpy as np
  50. import tensorflow as tf
  51. flags = tf.app.flags
  52. flags.DEFINE_string('input_base_path', '/tmp/swivel_data',
  53. 'Directory containing input shards, vocabularies, '
  54. 'and marginals.')
  55. flags.DEFINE_string('output_base_path', '/tmp/swivel_data',
  56. 'Path where to write the trained embeddings.')
  57. flags.DEFINE_integer('embedding_size', 300, 'Size of the embeddings')
  58. flags.DEFINE_boolean('trainable_bias', False, 'Biases are trainable')
  59. flags.DEFINE_integer('submatrix_rows', 4096, 'Rows in each training submatrix. '
  60. 'This must match the training data.')
  61. flags.DEFINE_integer('submatrix_cols', 4096, 'Rows in each training submatrix. '
  62. 'This must match the training data.')
  63. flags.DEFINE_float('loss_multiplier', 1.0 / 4096,
  64. 'constant multiplier on loss.')
  65. flags.DEFINE_float('confidence_exponent', 0.5,
  66. 'Exponent for l2 confidence function')
  67. flags.DEFINE_float('confidence_scale', 0.25, 'Scale for l2 confidence function')
  68. flags.DEFINE_float('confidence_base', 0.1, 'Base for l2 confidence function')
  69. flags.DEFINE_float('learning_rate', 1.0, 'Initial learning rate')
  70. flags.DEFINE_integer('num_concurrent_steps', 2,
  71. 'Number of threads to train with')
  72. flags.DEFINE_float('num_epochs', 40, 'Number epochs to train for')
  73. flags.DEFINE_float('per_process_gpu_memory_fraction', 0.25,
  74. 'Fraction of GPU memory to use')
  75. FLAGS = flags.FLAGS
  76. def embeddings_with_init(vocab_size, embedding_dim, name):
  77. """Creates and initializes the embedding tensors."""
  78. return tf.get_variable(name=name,
  79. shape=[vocab_size, embedding_dim],
  80. initializer=tf.random_normal_initializer(
  81. stddev=math.sqrt(1.0 / embedding_dim)))
  82. def count_matrix_input(filenames, submatrix_rows, submatrix_cols):
  83. """Reads submatrix shards from disk."""
  84. filename_queue = tf.train.string_input_producer(filenames)
  85. reader = tf.WholeFileReader()
  86. _, serialized_example = reader.read(filename_queue)
  87. features = tf.parse_single_example(
  88. serialized_example,
  89. features={
  90. 'global_row': tf.FixedLenFeature([submatrix_rows], dtype=tf.int64),
  91. 'global_col': tf.FixedLenFeature([submatrix_cols], dtype=tf.int64),
  92. 'sparse_local_row': tf.VarLenFeature(dtype=tf.int64),
  93. 'sparse_local_col': tf.VarLenFeature(dtype=tf.int64),
  94. 'sparse_value': tf.VarLenFeature(dtype=tf.float32)
  95. })
  96. global_row = features['global_row']
  97. global_col = features['global_col']
  98. sparse_local_row = features['sparse_local_row'].values
  99. sparse_local_col = features['sparse_local_col'].values
  100. sparse_count = features['sparse_value'].values
  101. sparse_indices = tf.concat([tf.expand_dims(sparse_local_row, 1),
  102. tf.expand_dims(sparse_local_col, 1)], 1)
  103. count = tf.sparse_to_dense(sparse_indices, [submatrix_rows, submatrix_cols],
  104. sparse_count)
  105. queued_global_row, queued_global_col, queued_count = tf.train.batch(
  106. [global_row, global_col, count],
  107. batch_size=1,
  108. num_threads=4,
  109. capacity=32)
  110. queued_global_row = tf.reshape(queued_global_row, [submatrix_rows])
  111. queued_global_col = tf.reshape(queued_global_col, [submatrix_cols])
  112. queued_count = tf.reshape(queued_count, [submatrix_rows, submatrix_cols])
  113. return queued_global_row, queued_global_col, queued_count
  114. def read_marginals_file(filename):
  115. """Reads text file with one number per line to an array."""
  116. with open(filename) as lines:
  117. return [float(line) for line in lines]
  118. def write_embedding_tensor_to_disk(vocab_path, output_path, sess, embedding):
  119. """Writes tensor to output_path as tsv"""
  120. # Fetch the embedding values from the model
  121. embeddings = sess.run(embedding)
  122. with open(output_path, 'w') as out_f:
  123. with open(vocab_path) as vocab_f:
  124. for index, word in enumerate(vocab_f):
  125. word = word.strip()
  126. embedding = embeddings[index]
  127. out_f.write(word + '\t' + '\t'.join([str(x) for x in embedding]) + '\n')
  128. def write_embeddings_to_disk(config, model, sess):
  129. """Writes row and column embeddings disk"""
  130. # Row Embedding
  131. row_vocab_path = config.input_base_path + '/row_vocab.txt'
  132. row_embedding_output_path = config.output_base_path + '/row_embedding.tsv'
  133. print('Writing row embeddings to:', row_embedding_output_path)
  134. sys.stdout.flush()
  135. write_embedding_tensor_to_disk(row_vocab_path, row_embedding_output_path,
  136. sess, model.row_embedding)
  137. # Column Embedding
  138. col_vocab_path = config.input_base_path + '/col_vocab.txt'
  139. col_embedding_output_path = config.output_base_path + '/col_embedding.tsv'
  140. print('Writing column embeddings to:', col_embedding_output_path)
  141. sys.stdout.flush()
  142. write_embedding_tensor_to_disk(col_vocab_path, col_embedding_output_path,
  143. sess, model.col_embedding)
  144. class SwivelModel(object):
  145. """Small class to gather needed pieces from a Graph being built."""
  146. def __init__(self, config):
  147. """Construct graph for dmc."""
  148. self._config = config
  149. # Create paths to input data files
  150. print('Reading model from:', config.input_base_path)
  151. sys.stdout.flush()
  152. count_matrix_files = glob.glob(config.input_base_path + '/shard-*.pb')
  153. row_sums_path = config.input_base_path + '/row_sums.txt'
  154. col_sums_path = config.input_base_path + '/col_sums.txt'
  155. # Read marginals
  156. row_sums = read_marginals_file(row_sums_path)
  157. col_sums = read_marginals_file(col_sums_path)
  158. self.n_rows = len(row_sums)
  159. self.n_cols = len(col_sums)
  160. print('Matrix dim: (%d,%d) SubMatrix dim: (%d,%d) ' % (
  161. self.n_rows, self.n_cols, config.submatrix_rows, config.submatrix_cols))
  162. sys.stdout.flush()
  163. self.n_submatrices = (self.n_rows * self.n_cols /
  164. (config.submatrix_rows * config.submatrix_cols))
  165. print('n_submatrices: %d' % (self.n_submatrices))
  166. sys.stdout.flush()
  167. # ===== CREATE VARIABLES ======
  168. with tf.device('/cpu:0'):
  169. # embeddings
  170. self.row_embedding = embeddings_with_init(
  171. embedding_dim=config.embedding_size,
  172. vocab_size=self.n_rows,
  173. name='row_embedding')
  174. self.col_embedding = embeddings_with_init(
  175. embedding_dim=config.embedding_size,
  176. vocab_size=self.n_cols,
  177. name='col_embedding')
  178. tf.summary.histogram('row_emb', self.row_embedding)
  179. tf.summary.histogram('col_emb', self.col_embedding)
  180. matrix_log_sum = math.log(np.sum(row_sums) + 1)
  181. row_bias_init = [math.log(x + 1) for x in row_sums]
  182. col_bias_init = [math.log(x + 1) for x in col_sums]
  183. self.row_bias = tf.Variable(row_bias_init,
  184. trainable=config.trainable_bias)
  185. self.col_bias = tf.Variable(col_bias_init,
  186. trainable=config.trainable_bias)
  187. tf.summary.histogram('row_bias', self.row_bias)
  188. tf.summary.histogram('col_bias', self.col_bias)
  189. # ===== CREATE GRAPH =====
  190. # Get input
  191. with tf.device('/cpu:0'):
  192. global_row, global_col, count = count_matrix_input(
  193. count_matrix_files, config.submatrix_rows, config.submatrix_cols)
  194. # Fetch embeddings.
  195. selected_row_embedding = tf.nn.embedding_lookup(self.row_embedding,
  196. global_row)
  197. selected_col_embedding = tf.nn.embedding_lookup(self.col_embedding,
  198. global_col)
  199. # Fetch biases.
  200. selected_row_bias = tf.nn.embedding_lookup([self.row_bias], global_row)
  201. selected_col_bias = tf.nn.embedding_lookup([self.col_bias], global_col)
  202. # Multiply the row and column embeddings to generate predictions.
  203. predictions = tf.matmul(
  204. selected_row_embedding, selected_col_embedding, transpose_b=True)
  205. # These binary masks separate zero from non-zero values.
  206. count_is_nonzero = tf.to_float(tf.cast(count, tf.bool))
  207. count_is_zero = 1 - tf.to_float(tf.cast(count, tf.bool))
  208. objectives = count_is_nonzero * tf.log(count + 1e-30)
  209. objectives -= tf.reshape(selected_row_bias, [config.submatrix_rows, 1])
  210. objectives -= selected_col_bias
  211. objectives += matrix_log_sum
  212. err = predictions - objectives
  213. # The confidence function scales the L2 loss based on the raw co-occurrence
  214. # count.
  215. l2_confidence = (config.confidence_base + config.confidence_scale * tf.pow(
  216. count, config.confidence_exponent))
  217. l2_loss = config.loss_multiplier * tf.reduce_sum(
  218. 0.5 * l2_confidence * err * err * count_is_nonzero)
  219. sigmoid_loss = config.loss_multiplier * tf.reduce_sum(
  220. tf.nn.softplus(err) * count_is_zero)
  221. self.loss = l2_loss + sigmoid_loss
  222. tf.summary.scalar("l2_loss", l2_loss)
  223. tf.summary.scalar("sigmoid_loss", sigmoid_loss)
  224. tf.summary.scalar("loss", self.loss)
  225. # Add optimizer.
  226. self.global_step = tf.Variable(0, name='global_step')
  227. opt = tf.train.AdagradOptimizer(config.learning_rate)
  228. self.train_op = opt.minimize(self.loss, global_step=self.global_step)
  229. self.saver = tf.train.Saver(sharded=True)
  230. def main(_):
  231. # Create the output path. If this fails, it really ought to fail
  232. # now. :)
  233. if not os.path.isdir(FLAGS.output_base_path):
  234. os.makedirs(FLAGS.output_base_path)
  235. # Create and run model
  236. with tf.Graph().as_default():
  237. model = SwivelModel(FLAGS)
  238. # Create a session for running Ops on the Graph.
  239. gpu_options = tf.GPUOptions(
  240. per_process_gpu_memory_fraction=FLAGS.per_process_gpu_memory_fraction)
  241. sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
  242. # Run the Op to initialize the variables.
  243. sess.run(tf.global_variables_initializer())
  244. # Start feeding input
  245. coord = tf.train.Coordinator()
  246. threads = tf.train.start_queue_runners(sess=sess, coord=coord)
  247. # Calculate how many steps each thread should run
  248. n_total_steps = int(FLAGS.num_epochs * model.n_rows * model.n_cols) / (
  249. FLAGS.submatrix_rows * FLAGS.submatrix_cols)
  250. n_steps_per_thread = n_total_steps / FLAGS.num_concurrent_steps
  251. n_submatrices_to_train = model.n_submatrices * FLAGS.num_epochs
  252. t0 = [time.time()]
  253. def TrainingFn():
  254. for _ in range(int(n_steps_per_thread)):
  255. _, global_step = sess.run([model.train_op, model.global_step])
  256. n_steps_between_status_updates = 100
  257. if (global_step % n_steps_between_status_updates) == 0:
  258. elapsed = float(time.time() - t0[0])
  259. print('%d/%d submatrices trained (%.1f%%), %.1f submatrices/sec' % (
  260. global_step, n_submatrices_to_train,
  261. 100.0 * global_step / n_submatrices_to_train,
  262. n_steps_between_status_updates / elapsed))
  263. sys.stdout.flush()
  264. t0[0] = time.time()
  265. # Start training threads
  266. train_threads = []
  267. for _ in range(FLAGS.num_concurrent_steps):
  268. t = threading.Thread(target=TrainingFn)
  269. train_threads.append(t)
  270. t.start()
  271. # Wait for threads to finish.
  272. for t in train_threads:
  273. t.join()
  274. coord.request_stop()
  275. coord.join(threads)
  276. # Write out vectors
  277. write_embeddings_to_disk(FLAGS, model, sess)
  278. #Shutdown
  279. sess.close()
  280. if __name__ == '__main__':
  281. tf.app.run()