lm_1b_eval.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. # Copyright 2016 The TensorFlow Authors. 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. """Eval pre-trained 1 billion word language model.
  16. """
  17. import os
  18. import sys
  19. import numpy as np
  20. import tensorflow as tf
  21. from google.protobuf import text_format
  22. import data_utils
  23. FLAGS = tf.flags.FLAGS
  24. # General flags.
  25. tf.flags.DEFINE_string('mode', 'eval',
  26. 'One of [sample, eval, dump_emb, dump_lstm_emb]. '
  27. '"sample" mode samples future word predictions, using '
  28. 'FLAGS.prefix as prefix (prefix could be left empty). '
  29. '"eval" mode calculates perplexity of the '
  30. 'FLAGS.input_data. '
  31. '"dump_emb" mode dumps word and softmax embeddings to '
  32. 'FLAGS.save_dir. embeddings are dumped in the same '
  33. 'order as words in vocabulary. All words in vocabulary '
  34. 'are dumped.'
  35. 'dump_lstm_emb dumps lstm embeddings of FLAGS.sentence '
  36. 'to FLAGS.save_dir.')
  37. tf.flags.DEFINE_string('pbtxt', '',
  38. 'GraphDef proto text file used to construct model '
  39. 'structure.')
  40. tf.flags.DEFINE_string('ckpt', '',
  41. 'Checkpoint directory used to fill model values.')
  42. tf.flags.DEFINE_string('vocab_file', '', 'Vocabulary file.')
  43. tf.flags.DEFINE_string('save_dir', '',
  44. 'Used for "dump_emb" mode to save word embeddings.')
  45. # sample mode flags.
  46. tf.flags.DEFINE_string('prefix', '',
  47. 'Used for "sample" mode to predict next words.')
  48. tf.flags.DEFINE_integer('max_sample_words', 100,
  49. 'Sampling stops either when </S> is met or this number '
  50. 'of steps has passed.')
  51. tf.flags.DEFINE_integer('num_samples', 3,
  52. 'Number of samples to generate for the prefix.')
  53. # dump_lstm_emb mode flags.
  54. tf.flags.DEFINE_string('sentence', '',
  55. 'Used as input for "dump_lstm_emb" mode.')
  56. # eval mode flags.
  57. tf.flags.DEFINE_string('input_data', '',
  58. 'Input data files for eval model.')
  59. tf.flags.DEFINE_integer('max_eval_steps', 1000000,
  60. 'Maximum mumber of steps to run "eval" mode.')
  61. # For saving demo resources, use batch size 1 and step 1.
  62. BATCH_SIZE = 1
  63. NUM_TIMESTEPS = 1
  64. MAX_WORD_LEN = 50
  65. def _LoadModel(gd_file, ckpt_file):
  66. """Load the model from GraphDef and Checkpoint.
  67. Args:
  68. gd_file: GraphDef proto text file.
  69. ckpt_file: TensorFlow Checkpoint file.
  70. Returns:
  71. TensorFlow session and tensors dict.
  72. """
  73. with tf.Graph().as_default():
  74. sys.stderr.write('Recovering graph.\n')
  75. with tf.gfile.FastGFile(gd_file, 'r') as f:
  76. s = f.read()
  77. gd = tf.GraphDef()
  78. text_format.Merge(s, gd)
  79. tf.logging.info('Recovering Graph %s', gd_file)
  80. t = {}
  81. [t['states_init'], t['lstm/lstm_0/control_dependency'],
  82. t['lstm/lstm_1/control_dependency'], t['softmax_out'], t['class_ids_out'],
  83. t['class_weights_out'], t['log_perplexity_out'], t['inputs_in'],
  84. t['targets_in'], t['target_weights_in'], t['char_inputs_in'],
  85. t['all_embs'], t['softmax_weights'], t['global_step']
  86. ] = tf.import_graph_def(gd, {}, ['states_init',
  87. 'lstm/lstm_0/control_dependency:0',
  88. 'lstm/lstm_1/control_dependency:0',
  89. 'softmax_out:0',
  90. 'class_ids_out:0',
  91. 'class_weights_out:0',
  92. 'log_perplexity_out:0',
  93. 'inputs_in:0',
  94. 'targets_in:0',
  95. 'target_weights_in:0',
  96. 'char_inputs_in:0',
  97. 'all_embs_out:0',
  98. 'Reshape_3:0',
  99. 'global_step:0'], name='')
  100. sys.stderr.write('Recovering checkpoint %s\n' % ckpt_file)
  101. sess = tf.Session(config=tf.ConfigProto(allow_soft_placement=True))
  102. sess.run('save/restore_all', {'save/Const:0': ckpt_file})
  103. sess.run(t['states_init'])
  104. return sess, t
  105. def _EvalModel(dataset):
  106. """Evaluate model perplexity using provided dataset.
  107. Args:
  108. dataset: LM1BDataset object.
  109. """
  110. sess, t = _LoadModel(FLAGS.pbtxt, FLAGS.ckpt)
  111. current_step = t['global_step'].eval(session=sess)
  112. sys.stderr.write('Loaded step %d.\n' % current_step)
  113. data_gen = dataset.get_batch(BATCH_SIZE, NUM_TIMESTEPS, forever=False)
  114. sum_num = 0.0
  115. sum_den = 0.0
  116. perplexity = 0.0
  117. for i, (inputs, char_inputs, _, targets, weights) in enumerate(data_gen):
  118. input_dict = {t['inputs_in']: inputs,
  119. t['targets_in']: targets,
  120. t['target_weights_in']: weights}
  121. if 'char_inputs_in' in t:
  122. input_dict[t['char_inputs_in']] = char_inputs
  123. log_perp = sess.run(t['log_perplexity_out'], feed_dict=input_dict)
  124. if np.isnan(log_perp):
  125. sys.stderr.error('log_perplexity is Nan.\n')
  126. else:
  127. sum_num += log_perp * weights.mean()
  128. sum_den += weights.mean()
  129. if sum_den > 0:
  130. perplexity = np.exp(sum_num / sum_den)
  131. sys.stderr.write('Eval Step: %d, Average Perplexity: %f.\n' %
  132. (i, perplexity))
  133. if i > FLAGS.max_eval_steps:
  134. break
  135. def _SampleSoftmax(softmax):
  136. return min(np.sum(np.cumsum(softmax) < np.random.rand()), len(softmax) - 1)
  137. def _SampleModel(prefix_words, vocab):
  138. """Predict next words using the given prefix words.
  139. Args:
  140. prefix_words: Prefix words.
  141. vocab: Vocabulary. Contains max word chard id length and converts between
  142. words and ids.
  143. """
  144. targets = np.zeros([BATCH_SIZE, NUM_TIMESTEPS], np.int32)
  145. weights = np.ones([BATCH_SIZE, NUM_TIMESTEPS], np.float32)
  146. sess, t = _LoadModel(FLAGS.pbtxt, FLAGS.ckpt)
  147. if prefix_words.find('<S>') != 0:
  148. prefix_words = '<S> ' + prefix_words
  149. prefix = [vocab.word_to_id(w) for w in prefix_words.split()]
  150. prefix_char_ids = [vocab.word_to_char_ids(w) for w in prefix_words.split()]
  151. for _ in xrange(FLAGS.num_samples):
  152. inputs = np.zeros([BATCH_SIZE, NUM_TIMESTEPS], np.int32)
  153. char_ids_inputs = np.zeros(
  154. [BATCH_SIZE, NUM_TIMESTEPS, vocab.max_word_length], np.int32)
  155. samples = prefix[:]
  156. char_ids_samples = prefix_char_ids[:]
  157. sent = ''
  158. while True:
  159. inputs[0, 0] = samples[0]
  160. char_ids_inputs[0, 0, :] = char_ids_samples[0]
  161. samples = samples[1:]
  162. char_ids_samples = char_ids_samples[1:]
  163. softmax = sess.run(t['softmax_out'],
  164. feed_dict={t['char_inputs_in']: char_ids_inputs,
  165. t['inputs_in']: inputs,
  166. t['targets_in']: targets,
  167. t['target_weights_in']: weights})
  168. sample = _SampleSoftmax(softmax[0])
  169. sample_char_ids = vocab.word_to_char_ids(vocab.id_to_word(sample))
  170. if not samples:
  171. samples = [sample]
  172. char_ids_samples = [sample_char_ids]
  173. sent += vocab.id_to_word(samples[0]) + ' '
  174. sys.stderr.write('%s\n' % sent)
  175. if (vocab.id_to_word(samples[0]) == '</S>' or
  176. len(sent) > FLAGS.max_sample_words):
  177. break
  178. def _DumpEmb(vocab):
  179. """Dump the softmax weights and word embeddings to files.
  180. Args:
  181. vocab: Vocabulary. Contains vocabulary size and converts word to ids.
  182. """
  183. assert FLAGS.save_dir, 'Must specify FLAGS.save_dir for dump_emb.'
  184. inputs = np.zeros([BATCH_SIZE, NUM_TIMESTEPS], np.int32)
  185. targets = np.zeros([BATCH_SIZE, NUM_TIMESTEPS], np.int32)
  186. weights = np.ones([BATCH_SIZE, NUM_TIMESTEPS], np.float32)
  187. sess, t = _LoadModel(FLAGS.pbtxt, FLAGS.ckpt)
  188. softmax_weights = sess.run(t['softmax_weights'])
  189. fname = FLAGS.save_dir + '/embeddings_softmax.npy'
  190. with tf.gfile.Open(fname, mode='w') as f:
  191. np.save(f, softmax_weights)
  192. sys.stderr.write('Finished softmax weights\n')
  193. all_embs = np.zeros([vocab.size, 1024])
  194. for i in range(vocab.size):
  195. input_dict = {t['inputs_in']: inputs,
  196. t['targets_in']: targets,
  197. t['target_weights_in']: weights}
  198. if 'char_inputs_in' in t:
  199. input_dict[t['char_inputs_in']] = (
  200. vocab.word_char_ids[i].reshape([-1, 1, MAX_WORD_LEN]))
  201. embs = sess.run(t['all_embs'], input_dict)
  202. all_embs[i, :] = embs
  203. sys.stderr.write('Finished word embedding %d/%d\n' % (i, vocab.size))
  204. fname = FLAGS.save_dir + '/embeddings_char_cnn.npy'
  205. with tf.gfile.Open(fname, mode='w') as f:
  206. np.save(f, all_embs)
  207. sys.stderr.write('Embedding file saved\n')
  208. def _DumpSentenceEmbedding(sentence, vocab):
  209. """Predict next words using the given prefix words.
  210. Args:
  211. sentence: Sentence words.
  212. vocab: Vocabulary. Contains max word chard id length and converts between
  213. words and ids.
  214. """
  215. targets = np.zeros([BATCH_SIZE, NUM_TIMESTEPS], np.int32)
  216. weights = np.ones([BATCH_SIZE, NUM_TIMESTEPS], np.float32)
  217. sess, t = _LoadModel(FLAGS.pbtxt, FLAGS.ckpt)
  218. if sentence.find('<S>') != 0:
  219. sentence = '<S> ' + sentence
  220. word_ids = [vocab.word_to_id(w) for w in sentence.split()]
  221. char_ids = [vocab.word_to_char_ids(w) for w in sentence.split()]
  222. inputs = np.zeros([BATCH_SIZE, NUM_TIMESTEPS], np.int32)
  223. char_ids_inputs = np.zeros(
  224. [BATCH_SIZE, NUM_TIMESTEPS, vocab.max_word_length], np.int32)
  225. for i in xrange(len(word_ids)):
  226. inputs[0, 0] = word_ids[i]
  227. char_ids_inputs[0, 0, :] = char_ids[i]
  228. # Add 'lstm/lstm_0/control_dependency' if you want to dump previous layer
  229. # LSTM.
  230. lstm_emb = sess.run(t['lstm/lstm_1/control_dependency'],
  231. feed_dict={t['char_inputs_in']: char_ids_inputs,
  232. t['inputs_in']: inputs,
  233. t['targets_in']: targets,
  234. t['target_weights_in']: weights})
  235. fname = os.path.join(FLAGS.save_dir, 'lstm_emb_step_%d.npy' % i)
  236. with tf.gfile.Open(fname, mode='w') as f:
  237. np.save(f, lstm_emb)
  238. sys.stderr.write('LSTM embedding step %d file saved\n' % i)
  239. def main(unused_argv):
  240. vocab = data_utils.CharsVocabulary(FLAGS.vocab_file, MAX_WORD_LEN)
  241. if FLAGS.mode == 'eval':
  242. dataset = data_utils.LM1BDataset(FLAGS.input_data, vocab)
  243. _EvalModel(dataset)
  244. elif FLAGS.mode == 'sample':
  245. _SampleModel(FLAGS.prefix, vocab)
  246. elif FLAGS.mode == 'dump_emb':
  247. _DumpEmb(vocab)
  248. elif FLAGS.mode == 'dump_lstm_emb':
  249. _DumpSentenceEmbedding(FLAGS.sentence, vocab)
  250. else:
  251. raise Exception('Mode not supported.')
  252. if __name__ == '__main__':
  253. tf.app.run()