swivel.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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 glob
  43. import math
  44. import os
  45. import sys
  46. import time
  47. import threading
  48. import numpy as np
  49. import tensorflow as tf
  50. from tensorflow.python.client import device_lib
  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_integer('num_readers', 4,
  73. 'Number of threads to read the input data and feed it')
  74. flags.DEFINE_float('num_epochs', 40, 'Number epochs to train for')
  75. flags.DEFINE_float('per_process_gpu_memory_fraction', 0,
  76. 'Fraction of GPU memory to use, 0 means allow_growth')
  77. flags.DEFINE_integer('num_gpus', 0,
  78. 'Number of GPUs to use, 0 means all available')
  79. FLAGS = flags.FLAGS
  80. def log(message, *args, **kwargs):
  81. tf.logging.info(message, *args, **kwargs)
  82. def get_available_gpus():
  83. return [d.name for d in device_lib.list_local_devices()
  84. if d.device_type == 'GPU']
  85. def embeddings_with_init(vocab_size, embedding_dim, name):
  86. """Creates and initializes the embedding tensors."""
  87. return tf.get_variable(name=name,
  88. shape=[vocab_size, embedding_dim],
  89. initializer=tf.random_normal_initializer(
  90. stddev=math.sqrt(1.0 / embedding_dim)))
  91. def count_matrix_input(filenames, submatrix_rows, submatrix_cols):
  92. """Reads submatrix shards from disk."""
  93. filename_queue = tf.train.string_input_producer(filenames)
  94. reader = tf.WholeFileReader()
  95. _, serialized_example = reader.read(filename_queue)
  96. features = tf.parse_single_example(
  97. serialized_example,
  98. features={
  99. 'global_row': tf.FixedLenFeature([submatrix_rows], dtype=tf.int64),
  100. 'global_col': tf.FixedLenFeature([submatrix_cols], dtype=tf.int64),
  101. 'sparse_local_row': tf.VarLenFeature(dtype=tf.int64),
  102. 'sparse_local_col': tf.VarLenFeature(dtype=tf.int64),
  103. 'sparse_value': tf.VarLenFeature(dtype=tf.float32)
  104. })
  105. global_row = features['global_row']
  106. global_col = features['global_col']
  107. sparse_local_row = features['sparse_local_row'].values
  108. sparse_local_col = features['sparse_local_col'].values
  109. sparse_count = features['sparse_value'].values
  110. sparse_indices = tf.concat(axis=1, values=[tf.expand_dims(sparse_local_row, 1),
  111. tf.expand_dims(sparse_local_col, 1)])
  112. count = tf.sparse_to_dense(sparse_indices, [submatrix_rows, submatrix_cols],
  113. sparse_count)
  114. queued_global_row, queued_global_col, queued_count = tf.train.batch(
  115. [global_row, global_col, count],
  116. batch_size=1,
  117. num_threads=FLAGS.num_readers,
  118. capacity=32)
  119. queued_global_row = tf.reshape(queued_global_row, [submatrix_rows])
  120. queued_global_col = tf.reshape(queued_global_col, [submatrix_cols])
  121. queued_count = tf.reshape(queued_count, [submatrix_rows, submatrix_cols])
  122. return queued_global_row, queued_global_col, queued_count
  123. def read_marginals_file(filename):
  124. """Reads text file with one number per line to an array."""
  125. with open(filename) as lines:
  126. return [float(line) for line in lines]
  127. def write_embedding_tensor_to_disk(vocab_path, output_path, sess, embedding):
  128. """Writes tensor to output_path as tsv"""
  129. # Fetch the embedding values from the model
  130. embeddings = sess.run(embedding)
  131. with open(output_path, 'w') as out_f:
  132. with open(vocab_path) as vocab_f:
  133. for index, word in enumerate(vocab_f):
  134. word = word.strip()
  135. embedding = embeddings[index]
  136. out_f.write(word + '\t' + '\t'.join([str(x) for x in embedding]) + '\n')
  137. def write_embeddings_to_disk(config, model, sess):
  138. """Writes row and column embeddings disk"""
  139. # Row Embedding
  140. row_vocab_path = config.input_base_path + '/row_vocab.txt'
  141. row_embedding_output_path = config.output_base_path + '/row_embedding.tsv'
  142. log('Writing row embeddings to: %s', row_embedding_output_path)
  143. write_embedding_tensor_to_disk(row_vocab_path, row_embedding_output_path,
  144. sess, model.row_embedding)
  145. # Column Embedding
  146. col_vocab_path = config.input_base_path + '/col_vocab.txt'
  147. col_embedding_output_path = config.output_base_path + '/col_embedding.tsv'
  148. log('Writing column embeddings to: %s', col_embedding_output_path)
  149. write_embedding_tensor_to_disk(col_vocab_path, col_embedding_output_path,
  150. sess, model.col_embedding)
  151. class SwivelModel(object):
  152. """Small class to gather needed pieces from a Graph being built."""
  153. def __init__(self, config):
  154. """Construct graph for dmc."""
  155. self._config = config
  156. # Create paths to input data files
  157. log('Reading model from: %s', config.input_base_path)
  158. count_matrix_files = glob.glob(config.input_base_path + '/shard-*.pb')
  159. row_sums_path = config.input_base_path + '/row_sums.txt'
  160. col_sums_path = config.input_base_path + '/col_sums.txt'
  161. # Read marginals
  162. row_sums = read_marginals_file(row_sums_path)
  163. col_sums = read_marginals_file(col_sums_path)
  164. self.n_rows = len(row_sums)
  165. self.n_cols = len(col_sums)
  166. log('Matrix dim: (%d,%d) SubMatrix dim: (%d,%d)',
  167. self.n_rows, self.n_cols, config.submatrix_rows, config.submatrix_cols)
  168. self.n_submatrices = (self.n_rows * self.n_cols /
  169. (config.submatrix_rows * config.submatrix_cols))
  170. log('n_submatrices: %d', self.n_submatrices)
  171. with tf.device('/cpu:0'):
  172. # ===== CREATE VARIABLES ======
  173. # Get input
  174. global_row, global_col, count = count_matrix_input(
  175. count_matrix_files, config.submatrix_rows, config.submatrix_cols)
  176. # Embeddings
  177. self.row_embedding = embeddings_with_init(
  178. embedding_dim=config.embedding_size,
  179. vocab_size=self.n_rows,
  180. name='row_embedding')
  181. self.col_embedding = embeddings_with_init(
  182. embedding_dim=config.embedding_size,
  183. vocab_size=self.n_cols,
  184. name='col_embedding')
  185. tf.summary.histogram('row_emb', self.row_embedding)
  186. tf.summary.histogram('col_emb', self.col_embedding)
  187. matrix_log_sum = math.log(np.sum(row_sums) + 1)
  188. row_bias_init = [math.log(x + 1) for x in row_sums]
  189. col_bias_init = [math.log(x + 1) for x in col_sums]
  190. self.row_bias = tf.Variable(
  191. row_bias_init, trainable=config.trainable_bias)
  192. self.col_bias = tf.Variable(
  193. col_bias_init, trainable=config.trainable_bias)
  194. tf.summary.histogram('row_bias', self.row_bias)
  195. tf.summary.histogram('col_bias', self.col_bias)
  196. # Add optimizer
  197. l2_losses = []
  198. sigmoid_losses = []
  199. self.global_step = tf.Variable(0, name='global_step')
  200. opt = tf.train.AdagradOptimizer(config.learning_rate)
  201. all_grads = []
  202. devices = ['/gpu:%d' % i for i in range(FLAGS.num_gpus)] \
  203. if FLAGS.num_gpus > 0 else get_available_gpus()
  204. self.devices_number = len(devices)
  205. with tf.variable_scope(tf.get_variable_scope()):
  206. for dev in devices:
  207. with tf.device(dev):
  208. with tf.name_scope(dev[1:].replace(':', '_')):
  209. # ===== CREATE GRAPH =====
  210. # Fetch embeddings.
  211. selected_row_embedding = tf.nn.embedding_lookup(
  212. self.row_embedding, global_row)
  213. selected_col_embedding = tf.nn.embedding_lookup(
  214. self.col_embedding, global_col)
  215. # Fetch biases.
  216. selected_row_bias = tf.nn.embedding_lookup(
  217. [self.row_bias], global_row)
  218. selected_col_bias = tf.nn.embedding_lookup(
  219. [self.col_bias], global_col)
  220. # Multiply the row and column embeddings to generate predictions.
  221. predictions = tf.matmul(
  222. selected_row_embedding, selected_col_embedding,
  223. transpose_b=True)
  224. # These binary masks separate zero from non-zero values.
  225. count_is_nonzero = tf.to_float(tf.cast(count, tf.bool))
  226. count_is_zero = 1 - count_is_nonzero
  227. objectives = count_is_nonzero * tf.log(count + 1e-30)
  228. objectives -= tf.reshape(
  229. selected_row_bias, [config.submatrix_rows, 1])
  230. objectives -= selected_col_bias
  231. objectives += matrix_log_sum
  232. err = predictions - objectives
  233. # The confidence function scales the L2 loss based on the raw
  234. # co-occurrence count.
  235. l2_confidence = (config.confidence_base +
  236. config.confidence_scale * tf.pow(
  237. count, config.confidence_exponent))
  238. l2_loss = config.loss_multiplier * tf.reduce_sum(
  239. 0.5 * l2_confidence * err * err * count_is_nonzero)
  240. l2_losses.append(tf.expand_dims(l2_loss, 0))
  241. sigmoid_loss = config.loss_multiplier * tf.reduce_sum(
  242. tf.nn.softplus(err) * count_is_zero)
  243. sigmoid_losses.append(tf.expand_dims(sigmoid_loss, 0))
  244. loss = l2_loss + sigmoid_loss
  245. grads = opt.compute_gradients(loss)
  246. all_grads.append(grads)
  247. with tf.device('/cpu:0'):
  248. # ===== MERGE LOSSES =====
  249. l2_loss = tf.reduce_mean(tf.concat(axis=0, values=l2_losses), 0,
  250. name="l2_loss")
  251. sigmoid_loss = tf.reduce_mean(tf.concat(axis=0, values=sigmoid_losses), 0,
  252. name="sigmoid_loss")
  253. self.loss = l2_loss + sigmoid_loss
  254. average = tf.train.ExponentialMovingAverage(0.8, self.global_step)
  255. loss_average_op = average.apply((self.loss,))
  256. tf.summary.scalar("l2_loss", l2_loss)
  257. tf.summary.scalar("sigmoid_loss", sigmoid_loss)
  258. tf.summary.scalar("loss", self.loss)
  259. # Apply the gradients to adjust the shared variables.
  260. apply_gradient_ops = []
  261. for grads in all_grads:
  262. apply_gradient_ops.append(opt.apply_gradients(
  263. grads, global_step=self.global_step))
  264. self.train_op = tf.group(loss_average_op, *apply_gradient_ops)
  265. self.saver = tf.train.Saver(sharded=True)
  266. def main(_):
  267. tf.logging.set_verbosity(tf.logging.INFO)
  268. start_time = time.time()
  269. # Create the output path. If this fails, it really ought to fail
  270. # now. :)
  271. if not os.path.isdir(FLAGS.output_base_path):
  272. os.makedirs(FLAGS.output_base_path)
  273. # Create and run model
  274. with tf.Graph().as_default():
  275. model = SwivelModel(FLAGS)
  276. # Create a session for running Ops on the Graph.
  277. gpu_opts = {}
  278. if FLAGS.per_process_gpu_memory_fraction > 0:
  279. gpu_opts["per_process_gpu_memory_fraction"] = \
  280. FLAGS.per_process_gpu_memory_fraction
  281. else:
  282. gpu_opts["allow_growth"] = True
  283. gpu_options = tf.GPUOptions(**gpu_opts)
  284. sess = tf.Session(config=tf.ConfigProto(gpu_options=gpu_options))
  285. # Run the Op to initialize the variables.
  286. sess.run(tf.global_variables_initializer())
  287. # Start feeding input
  288. coord = tf.train.Coordinator()
  289. threads = tf.train.start_queue_runners(sess=sess, coord=coord)
  290. # Calculate how many steps each thread should run
  291. n_total_steps = int(FLAGS.num_epochs * model.n_rows * model.n_cols) / (
  292. FLAGS.submatrix_rows * FLAGS.submatrix_cols)
  293. n_steps_per_thread = n_total_steps / (
  294. FLAGS.num_concurrent_steps * model.devices_number)
  295. n_submatrices_to_train = model.n_submatrices * FLAGS.num_epochs
  296. t0 = [time.time()]
  297. n_steps_between_status_updates = 100
  298. status_i = [0]
  299. status_lock = threading.Lock()
  300. msg = ('%%%dd/%%d submatrices trained (%%.1f%%%%), %%5.1f submatrices/sec |'
  301. ' loss %%f') % len(str(n_submatrices_to_train))
  302. def TrainingFn():
  303. for _ in range(int(n_steps_per_thread)):
  304. _, global_step, loss = sess.run((
  305. model.train_op, model.global_step, model.loss))
  306. show_status = False
  307. with status_lock:
  308. new_i = global_step // n_steps_between_status_updates
  309. if new_i > status_i[0]:
  310. status_i[0] = new_i
  311. show_status = True
  312. if show_status:
  313. elapsed = float(time.time() - t0[0])
  314. log(msg, global_step, n_submatrices_to_train,
  315. 100.0 * global_step / n_submatrices_to_train,
  316. n_steps_between_status_updates / elapsed, loss)
  317. t0[0] = time.time()
  318. # Start training threads
  319. train_threads = []
  320. for _ in range(FLAGS.num_concurrent_steps):
  321. t = threading.Thread(target=TrainingFn)
  322. train_threads.append(t)
  323. t.start()
  324. # Wait for threads to finish.
  325. for t in train_threads:
  326. t.join()
  327. coord.request_stop()
  328. coord.join(threads)
  329. # Write out vectors
  330. write_embeddings_to_disk(FLAGS, model, sess)
  331. # Shutdown
  332. sess.close()
  333. log("Elapsed: %s", time.time() - start_time)
  334. if __name__ == '__main__':
  335. tf.app.run()