inference.py 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222
  1. #!/usr/bin/env python3
  2. # Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import time
  16. import json
  17. import ctypes
  18. import argparse
  19. import collections
  20. import numpy as np
  21. import tensorrt as trt
  22. import pycuda.driver as cuda
  23. import pycuda.autoinit
  24. import helpers.tokenization as tokenization
  25. import helpers.data_processing as dp
  26. TRT_LOGGER = trt.Logger(trt.Logger.INFO)
  27. def parse_args():
  28. """
  29. Parse command line arguments
  30. """
  31. parser = argparse.ArgumentParser(description='BERT QA Inference')
  32. parser.add_argument('-e', '--engine',
  33. help='Path to BERT TensorRT engine')
  34. parser.add_argument('-p', '--passage', nargs='*',
  35. help='Text for paragraph/passage for BERT QA',
  36. default='')
  37. parser.add_argument('-pf', '--passage-file',
  38. help='File containing input passage',
  39. default='')
  40. parser.add_argument('-q', '--question', nargs='*',
  41. help='Text for query/question for BERT QA',
  42. default='')
  43. parser.add_argument('-qf', '--question-file',
  44. help='File containiner input question',
  45. default='')
  46. parser.add_argument('-sq', '--squad-json',
  47. help='SQuAD json file',
  48. default='')
  49. parser.add_argument('-o', '--output-prediction-file',
  50. help='Output prediction file for SQuAD evaluation',
  51. default='./predictions.json')
  52. parser.add_argument('-v', '--vocab-file',
  53. help='Path to file containing entire understandable vocab')
  54. parser.add_argument('-s', '--sequence-length',
  55. help='The sequence length to use. Defaults to 128',
  56. default=128, type=int)
  57. parser.add_argument('--max-query-length',
  58. help='The maximum length of a query in number of tokens. Queries longer than this will be truncated',
  59. default=64, type=int)
  60. parser.add_argument('--max-answer-length',
  61. help='The maximum length of an answer that can be generated',
  62. default=30, type=int)
  63. parser.add_argument('--n-best-size',
  64. help='Total number of n-best predictions to generate in the nbest_predictions.json output file',
  65. default=20, type=int)
  66. args, _ = parser.parse_known_args()
  67. return args
  68. if __name__ == '__main__':
  69. args = parse_args()
  70. paragraph_text = None
  71. squad_examples = None
  72. output_prediction_file = None
  73. if not args.passage == '':
  74. paragraph_text = ' '.join(args.passage)
  75. elif not args.passage_file == '':
  76. f = open(args.passage_file, 'r')
  77. paragraph_text = f.read()
  78. elif not args.squad_json == '':
  79. squad_examples = dp.read_squad_json(args.squad_json)
  80. output_prediction_file = args.output_prediction_file
  81. else:
  82. paragraph_text = input("Paragraph: ")
  83. question_text = None
  84. if not args.question == '':
  85. question_text = ' '.join(args.question)
  86. elif not args.question_file == '':
  87. f = open(args.question_file, 'r')
  88. question_text = f.read()
  89. tokenizer = tokenization.FullTokenizer(vocab_file=args.vocab_file, do_lower_case=True)
  90. # When splitting up a long document into chunks, how much stride to take between chunks.
  91. doc_stride = 128
  92. # The maximum total input sequence length after WordPiece tokenization.
  93. # Sequences longer than this will be truncated, and sequences shorter
  94. max_seq_length = args.sequence_length
  95. def question_features(tokens, question):
  96. # Extract features from the paragraph and question
  97. return dp.convert_example_to_features(tokens, question, tokenizer, max_seq_length, doc_stride, args.max_query_length)
  98. # Import necessary plugins for BERT TensorRT
  99. ctypes.CDLL("libnvinfer_plugin.so", mode=ctypes.RTLD_GLOBAL)
  100. # The first context created will use the 0th profile. A new context must be created
  101. # for each additional profile needed. Here, we only use batch size 1, thus we only need the first profile.
  102. with open(args.engine, 'rb') as f, trt.Runtime(TRT_LOGGER) as runtime, \
  103. runtime.deserialize_cuda_engine(f.read()) as engine, engine.create_execution_context() as context:
  104. # We always use batch size 1.
  105. input_shape = (max_seq_length, 1)
  106. input_nbytes = trt.volume(input_shape) * trt.int32.itemsize
  107. # Specify input shapes. These must be within the min/max bounds of the active profile (0th profile in this case)
  108. # Note that input shapes can be specified on a per-inference basis, but in this case, we only have a single shape.
  109. for binding in range(3):
  110. context.set_binding_shape(binding, input_shape)
  111. assert context.all_binding_shapes_specified
  112. # Create a stream in which to copy inputs/outputs and run inference.
  113. stream = cuda.Stream()
  114. # Allocate device memory for inputs.
  115. d_inputs = [cuda.mem_alloc(input_nbytes) for binding in range(3)]
  116. # Allocate output buffer by querying the size from the context. This may be different for different input shapes.
  117. h_output = cuda.pagelocked_empty(tuple(context.get_binding_shape(3)), dtype=np.float32)
  118. d_output = cuda.mem_alloc(h_output.nbytes)
  119. def inference(features, tokens):
  120. global h_output
  121. _NetworkOutput = collections.namedtuple( # pylint: disable=invalid-name
  122. "NetworkOutput",
  123. ["start_logits", "end_logits", "feature_index"])
  124. networkOutputs = []
  125. eval_time_elapsed = 0
  126. for feature_index, feature in enumerate(features):
  127. # Copy inputs
  128. input_ids = cuda.register_host_memory(np.ascontiguousarray(feature.input_ids.ravel()))
  129. segment_ids = cuda.register_host_memory(np.ascontiguousarray(feature.segment_ids.ravel()))
  130. input_mask = cuda.register_host_memory(np.ascontiguousarray(feature.input_mask.ravel()))
  131. eval_start_time = time.time()
  132. cuda.memcpy_htod_async(d_inputs[0], input_ids, stream)
  133. cuda.memcpy_htod_async(d_inputs[1], segment_ids, stream)
  134. cuda.memcpy_htod_async(d_inputs[2], input_mask, stream)
  135. # Run inference
  136. context.execute_async_v2(bindings=[int(d_inp) for d_inp in d_inputs] + [int(d_output)], stream_handle=stream.handle)
  137. # Synchronize the stream
  138. stream.synchronize()
  139. eval_time_elapsed += (time.time() - eval_start_time)
  140. # Transfer predictions back from GPU
  141. cuda.memcpy_dtoh_async(h_output, d_output, stream)
  142. stream.synchronize()
  143. for index, batch in enumerate(h_output):
  144. # Data Post-processing
  145. networkOutputs.append(_NetworkOutput(
  146. start_logits = np.array(batch.squeeze()[:, 0]),
  147. end_logits = np.array(batch.squeeze()[:, 1]),
  148. feature_index = feature_index
  149. ))
  150. eval_time_elapsed /= len(features)
  151. prediction, nbest_json, scores_diff_json = dp.get_predictions(tokens, features,
  152. networkOutputs, args.n_best_size, args.max_answer_length)
  153. return eval_time_elapsed, prediction, nbest_json
  154. def print_single_query(eval_time_elapsed, prediction, nbest_json):
  155. print("------------------------")
  156. print("Running inference in {:.3f} Sentences/Sec".format(1.0/eval_time_elapsed))
  157. print("------------------------")
  158. print("Answer: '{}'".format(prediction))
  159. print("With probability: {:.3f}".format(nbest_json[0]['probability'] * 100.0))
  160. if squad_examples:
  161. all_predictions = collections.OrderedDict()
  162. for example in squad_examples:
  163. features = question_features(example.doc_tokens, example.question_text)
  164. eval_time_elapsed, prediction, nbest_json = inference(features, example.doc_tokens)
  165. all_predictions[example.id] = prediction
  166. with open(output_prediction_file, "w") as f:
  167. f.write(json.dumps(all_predictions, indent=4))
  168. print("\nOutput dump to {}".format(output_prediction_file))
  169. else:
  170. # Extract tokecs from the paragraph
  171. doc_tokens = dp.convert_doc_tokens(paragraph_text)
  172. if question_text:
  173. print("\nPassage: {}".format(paragraph_text))
  174. print("\nQuestion: {}".format(question_text))
  175. features = question_features(doc_tokens, question_text)
  176. eval_time_elapsed, prediction, nbest_json = inference(features, doc_tokens)
  177. print_single_query(eval_time_elapsed, prediction, nbest_json)
  178. else:
  179. # If no question text is provided, loop until the question is 'exit'
  180. EXIT_CMDS = ["exit", "quit"]
  181. question_text = input("Question (to exit, type one of {:}): ".format(EXIT_CMDS))
  182. while question_text.strip() not in EXIT_CMDS:
  183. features = question_features(doc_tokens, question_text)
  184. eval_time_elapsed, prediction, nbest_json = inference(features, doc_tokens)
  185. print_single_query(eval_time_elapsed, prediction, nbest_json)
  186. question_text = input("Question (to exit, type one of {:}): ".format(EXIT_CMDS))