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