evaluator.py 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  1. r"""Runs a DRAGNN model on a given set of CoNLL-formatted sentences.
  2. Sample invocation:
  3. bazel run -c opt <...>:dragnn_eval -- \
  4. --master_spec="/path/to/master-spec" \
  5. --checkpoint_file="/path/to/model/name.checkpoint" \
  6. --input_file="/path/to/input/documents/test.connlu"
  7. """
  8. import os
  9. import re
  10. import time
  11. import tensorflow as tf
  12. from google.protobuf import text_format
  13. from tensorflow.python.client import timeline
  14. from tensorflow.python.platform import gfile
  15. from dragnn.protos import spec_pb2
  16. from dragnn.python import evaluation
  17. from dragnn.python import graph_builder
  18. from dragnn.python import sentence_io
  19. from dragnn.python import spec_builder
  20. from syntaxnet import sentence_pb2
  21. import dragnn.python.load_dragnn_cc_impl
  22. import syntaxnet.load_parser_ops
  23. flags = tf.app.flags
  24. FLAGS = flags.FLAGS
  25. flags.DEFINE_string('master_spec', '',
  26. 'Path to text file containing a DRAGNN master spec to run.')
  27. flags.DEFINE_string('resource_dir', '',
  28. 'Optional base directory for resources in the master spec.')
  29. flags.DEFINE_bool('complete_master_spec', False, 'Whether the master_spec '
  30. 'needs the lexicon and other resources added to it.')
  31. flags.DEFINE_string('checkpoint_file', '', 'Path to trained model checkpoint.')
  32. flags.DEFINE_string('input_file', '',
  33. 'File of CoNLL-formatted sentences to read from.')
  34. flags.DEFINE_string('output_file', '',
  35. 'File path to write annotated sentences to.')
  36. flags.DEFINE_integer('max_batch_size', 2048, 'Maximum batch size to support.')
  37. flags.DEFINE_string('inference_beam_size', '', 'Comma separated list of '
  38. 'component_name=beam_size pairs.')
  39. flags.DEFINE_string('locally_normalize', '', 'Comma separated list of '
  40. 'component names to do local normalization on.')
  41. flags.DEFINE_integer('threads', 10, 'Number of threads used for intra- and '
  42. 'inter-op parallelism.')
  43. flags.DEFINE_string('timeline_output_file', '', 'Path to save timeline to. '
  44. 'If specified, the final iteration of the evaluation loop '
  45. 'will capture and save a TensorFlow timeline.')
  46. def main(unused_argv):
  47. # Parse the flags containint lists, using regular expressions.
  48. # This matches and extracts key=value pairs.
  49. component_beam_sizes = re.findall(r'([^=,]+)=(\d+)',
  50. FLAGS.inference_beam_size)
  51. # This matches strings separated by a comma. Does not return any empty
  52. # strings.
  53. components_to_locally_normalize = re.findall(r'[^,]+',
  54. FLAGS.locally_normalize)
  55. # Reads master spec.
  56. master_spec = spec_pb2.MasterSpec()
  57. with gfile.FastGFile(FLAGS.master_spec) as fin:
  58. text_format.Parse(fin.read(), master_spec)
  59. # Rewrite resource locations.
  60. if FLAGS.resource_dir:
  61. for component in master_spec.component:
  62. for resource in component.resource:
  63. for part in resource.part:
  64. part.file_pattern = os.path.join(FLAGS.resource_dir,
  65. part.file_pattern)
  66. if FLAGS.complete_master_spec:
  67. spec_builder.complete_master_spec(master_spec, None, FLAGS.resource_dir)
  68. # Graph building.
  69. tf.logging.info('Building the graph')
  70. g = tf.Graph()
  71. with g.as_default(), tf.device('/device:CPU:0'):
  72. hyperparam_config = spec_pb2.GridPoint()
  73. hyperparam_config.use_moving_average = True
  74. builder = graph_builder.MasterBuilder(master_spec, hyperparam_config)
  75. annotator = builder.add_annotation()
  76. builder.add_saver()
  77. tf.logging.info('Reading documents...')
  78. input_corpus = sentence_io.ConllSentenceReader(FLAGS.input_file).corpus()
  79. session_config = tf.ConfigProto(
  80. log_device_placement=False,
  81. intra_op_parallelism_threads=FLAGS.threads,
  82. inter_op_parallelism_threads=FLAGS.threads)
  83. with tf.Session(graph=g, config=session_config) as sess:
  84. tf.logging.info('Initializing variables...')
  85. sess.run(tf.global_variables_initializer())
  86. tf.logging.info('Loading from checkpoint...')
  87. sess.run('save/restore_all', {'save/Const:0': FLAGS.checkpoint_file})
  88. tf.logging.info('Processing sentences...')
  89. processed = []
  90. start_time = time.time()
  91. run_metadata = tf.RunMetadata()
  92. for start in range(0, len(input_corpus), FLAGS.max_batch_size):
  93. end = min(start + FLAGS.max_batch_size, len(input_corpus))
  94. feed_dict = {annotator['input_batch']: input_corpus[start:end]}
  95. for comp, beam_size in component_beam_sizes:
  96. feed_dict['%s/InferenceBeamSize:0' % comp] = beam_size
  97. for comp in components_to_locally_normalize:
  98. feed_dict['%s/LocallyNormalize:0' % comp] = True
  99. if FLAGS.timeline_output_file and end == len(input_corpus):
  100. serialized_annotations = sess.run(
  101. annotator['annotations'], feed_dict=feed_dict,
  102. options=tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE),
  103. run_metadata=run_metadata)
  104. trace = timeline.Timeline(step_stats=run_metadata.step_stats)
  105. with open(FLAGS.timeline_output_file, 'w') as trace_file:
  106. trace_file.write(trace.generate_chrome_trace_format())
  107. else:
  108. serialized_annotations = sess.run(
  109. annotator['annotations'], feed_dict=feed_dict)
  110. processed.extend(serialized_annotations)
  111. tf.logging.info('Processed %d documents in %.2f seconds.',
  112. len(input_corpus), time.time() - start_time)
  113. pos, uas, las = evaluation.calculate_parse_metrics(input_corpus, processed)
  114. print 'POS %.2f UAS %.2f LAS %.2f' % (pos, uas, las)
  115. if FLAGS.output_file:
  116. with gfile.GFile(FLAGS.output_file, 'w') as f:
  117. for serialized_sentence in processed:
  118. sentence = sentence_pb2.Sentence()
  119. sentence.ParseFromString(serialized_sentence)
  120. f.write(text_format.MessageToString(sentence) + '\n\n')
  121. if __name__ == '__main__':
  122. tf.app.run()