evaluator.py 6.8 KB

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