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. tf.logging.set_verbosity(tf.logging.INFO)
  48. # Parse the flags containint lists, using regular expressions.
  49. # This matches and extracts key=value pairs.
  50. component_beam_sizes = re.findall(r'([^=,]+)=(\d+)',
  51. FLAGS.inference_beam_size)
  52. # This matches strings separated by a comma. Does not return any empty
  53. # strings.
  54. components_to_locally_normalize = re.findall(r'[^,]+',
  55. FLAGS.locally_normalize)
  56. # Reads master spec.
  57. master_spec = spec_pb2.MasterSpec()
  58. with gfile.FastGFile(FLAGS.master_spec) as fin:
  59. text_format.Parse(fin.read(), master_spec)
  60. # Rewrite resource locations.
  61. if FLAGS.resource_dir:
  62. for component in master_spec.component:
  63. for resource in component.resource:
  64. for part in resource.part:
  65. part.file_pattern = os.path.join(FLAGS.resource_dir,
  66. part.file_pattern)
  67. if FLAGS.complete_master_spec:
  68. spec_builder.complete_master_spec(master_spec, None, FLAGS.resource_dir)
  69. # Graph building.
  70. tf.logging.info('Building the graph')
  71. g = tf.Graph()
  72. with g.as_default(), tf.device('/device:CPU:0'):
  73. hyperparam_config = spec_pb2.GridPoint()
  74. hyperparam_config.use_moving_average = True
  75. builder = graph_builder.MasterBuilder(master_spec, hyperparam_config)
  76. annotator = builder.add_annotation()
  77. builder.add_saver()
  78. tf.logging.info('Reading documents...')
  79. input_corpus = sentence_io.ConllSentenceReader(FLAGS.input_file).corpus()
  80. session_config = tf.ConfigProto(
  81. log_device_placement=False,
  82. intra_op_parallelism_threads=FLAGS.threads,
  83. inter_op_parallelism_threads=FLAGS.threads)
  84. with tf.Session(graph=g, config=session_config) as sess:
  85. tf.logging.info('Initializing variables...')
  86. sess.run(tf.global_variables_initializer())
  87. tf.logging.info('Loading from checkpoint...')
  88. sess.run('save/restore_all', {'save/Const:0': FLAGS.checkpoint_file})
  89. tf.logging.info('Processing sentences...')
  90. processed = []
  91. start_time = time.time()
  92. run_metadata = tf.RunMetadata()
  93. for start in range(0, len(input_corpus), FLAGS.max_batch_size):
  94. end = min(start + FLAGS.max_batch_size, len(input_corpus))
  95. feed_dict = {annotator['input_batch']: input_corpus[start:end]}
  96. for comp, beam_size in component_beam_sizes:
  97. feed_dict['%s/InferenceBeamSize:0' % comp] = beam_size
  98. for comp in components_to_locally_normalize:
  99. feed_dict['%s/LocallyNormalize:0' % comp] = True
  100. if FLAGS.timeline_output_file and end == len(input_corpus):
  101. serialized_annotations = sess.run(
  102. annotator['annotations'], feed_dict=feed_dict,
  103. options=tf.RunOptions(trace_level=tf.RunOptions.FULL_TRACE),
  104. run_metadata=run_metadata)
  105. trace = timeline.Timeline(step_stats=run_metadata.step_stats)
  106. with open(FLAGS.timeline_output_file, 'w') as trace_file:
  107. trace_file.write(trace.generate_chrome_trace_format())
  108. else:
  109. serialized_annotations = sess.run(
  110. annotator['annotations'], feed_dict=feed_dict)
  111. processed.extend(serialized_annotations)
  112. tf.logging.info('Processed %d documents in %.2f seconds.',
  113. len(input_corpus), time.time() - start_time)
  114. pos, uas, las = evaluation.calculate_parse_metrics(input_corpus, processed)
  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()