m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

404 lines
15 KiB

6 months ago
  1. # -------------------------------------------------------------------------
  2. # Copyright (c) Microsoft Corporation. All rights reserved.
  3. # Licensed under the MIT License.
  4. # --------------------------------------------------------------------------
  5. # This tool is not used directly in bert optimization. It could assist developing the optimization script on the following senarios:
  6. # (1) It could simplify graph by removing many sub-graphs related to reshape.
  7. # (2) It could reduce extra inputs and outputs to fit other tools. The script compare_bert_results.py or bert_perf_test.py requires 3 inputs.
  8. import argparse
  9. import logging
  10. import os
  11. import re
  12. import sys
  13. import tempfile
  14. from collections import deque
  15. from datetime import datetime
  16. from pathlib import Path
  17. from typing import List
  18. import numpy as np
  19. import onnx
  20. from onnx import ModelProto, TensorProto, numpy_helper
  21. from onnx_model import OnnxModel
  22. import onnxruntime
  23. logger = logging.getLogger(__name__)
  24. CONSTANT_SHAPE_NAME_PREFIX = "constant_shape_opt__"
  25. RESHAPE_INPUT_SHAPE_PREFIX = "reshape_input_shape__"
  26. class BertOnnxModelShapeOptimizer(OnnxModel):
  27. """
  28. This optimizer will replace Shape output or the shape input of Reshape node by initializer. Currently, it requires
  29. model inputs to have static shape.
  30. """
  31. def __init__(self, onnx_model):
  32. super().__init__(onnx_model.model)
  33. def add_shape_initializer(self, shape):
  34. """
  35. Add an initializer for constant shape.
  36. """
  37. shape_value = np.asarray(shape, dtype=np.int64)
  38. constant_shape_name = self.create_node_name("Constant", CONSTANT_SHAPE_NAME_PREFIX)
  39. tensor = onnx.helper.make_tensor(
  40. name=constant_shape_name,
  41. data_type=TensorProto.INT64,
  42. dims=shape_value.shape,
  43. vals=shape_value,
  44. )
  45. self.add_initializer(tensor)
  46. return tensor
  47. def get_shape_outputs(self):
  48. """
  49. Returns a list of output names of all Shape nodes.
  50. """
  51. input_name_to_nodes = self.input_name_to_nodes()
  52. outputs = []
  53. for node in self.model.graph.node:
  54. if node.op_type == "Shape":
  55. if node.output[0] in input_name_to_nodes:
  56. outputs.append(node.output[0])
  57. return outputs
  58. def get_reshape_shape_inputs(self):
  59. """
  60. Returns a list of shape input names of Reshape nodes.
  61. """
  62. output_name_to_node = self.output_name_to_node()
  63. shape_inputs = []
  64. for node in self.model.graph.node:
  65. if node.op_type == "Reshape":
  66. shape_inputs.append(node.input[1])
  67. return shape_inputs
  68. def add_shape_for_reshape_input(self):
  69. """
  70. For each Reshape node, create a Shape node for its first input.
  71. Returns the output names of these Shape nodes.
  72. """
  73. output_names = []
  74. nodes_to_add = []
  75. for node in self.model.graph.node:
  76. if node.op_type == "Reshape":
  77. input = node.input[0]
  78. output_name = self.create_node_name("Reshape_Input", RESHAPE_INPUT_SHAPE_PREFIX)
  79. shape_node = onnx.helper.make_node("Shape", inputs=[input], outputs=[output_name])
  80. nodes_to_add.append(shape_node)
  81. output_names.append(output_name)
  82. self.add_nodes(nodes_to_add)
  83. return output_names
  84. def add_extra_graph_output(self, extra_outputs):
  85. """
  86. Add a list of output names to graph output.
  87. """
  88. names_to_evaluate = []
  89. output_names = [output.name for output in self.model.graph.output]
  90. for name in extra_outputs:
  91. if self.get_initializer(name) is not None: # already a constant
  92. continue
  93. names_to_evaluate.append(name)
  94. if name not in output_names:
  95. output_info = onnx.helper.ValueInfoProto()
  96. output_info.name = name
  97. self.model.graph.output.extend([output_info])
  98. output_names.append(name)
  99. return names_to_evaluate
  100. # Update input and output shape to be static
  101. def use_static_input(self, inputs, batch_size=1, max_seq_len=128):
  102. """
  103. Update the model to use static axes instead of dynamic axes for graph inputs.
  104. """
  105. for input in self.model.graph.input:
  106. if input.name in inputs:
  107. dim_proto = input.type.tensor_type.shape.dim[0]
  108. dim_proto.dim_value = batch_size
  109. dim_proto = input.type.tensor_type.shape.dim[1]
  110. if dim_proto.HasField("dim_param"):
  111. dim_proto.dim_value = max_seq_len
  112. elif dim_proto.HasField("dim_value") and dim_proto.dim_value != max_seq_len:
  113. raise ValueError(
  114. "Unable to set dimension value to {} for axis {} of {}. Contradicts existing dimension value {}.".format(
  115. max_seq_len, 1, input.name, dim_proto.dim_value
  116. )
  117. )
  118. def create_dummy_inputs(
  119. self,
  120. input_ids,
  121. segment_ids,
  122. input_mask,
  123. batch_size,
  124. sequence_length,
  125. elem_type,
  126. dictionary_size=8,
  127. ):
  128. """
  129. Create dummy data for model inputs. If the model has more than 3 inputs, please update this function accordingly before running the tool.
  130. """
  131. assert elem_type in [1, 6, 7] # only int32, int64 and float32 are supported.
  132. # Create dummy inputs
  133. input_1 = np.random.randint(dictionary_size, size=(batch_size, sequence_length), dtype=np.int32)
  134. input_2 = np.ones((batch_size, sequence_length), dtype=np.int32)
  135. input_3 = np.zeros((batch_size, sequence_length), dtype=np.int32)
  136. # Here we assume that 3 inputs have same data type
  137. if elem_type == 1: # float32
  138. input_1 = np.float32(input_1)
  139. input_2 = np.float32(input_2)
  140. input_3 = np.float32(input_3)
  141. elif elem_type == 7: # int64
  142. input_1 = np.int64(input_1)
  143. input_2 = np.int64(input_2)
  144. input_3 = np.int64(input_3)
  145. inputs = {input_ids: input_1, input_mask: input_2, segment_ids: input_3}
  146. return inputs
  147. def shape_optimization(
  148. self,
  149. temp_model_path,
  150. input_ids,
  151. segment_ids,
  152. input_mask,
  153. output_names,
  154. batch_size,
  155. sequence_length,
  156. enable_shape_opt,
  157. enable_reshape_opt,
  158. verbose,
  159. ):
  160. self.bert_inputs = [input_ids, segment_ids, input_mask]
  161. extra_outputs = []
  162. if enable_shape_opt:
  163. extra_outputs.extend(self.get_shape_outputs())
  164. if enable_reshape_opt:
  165. reshape_shape_inputs = self.get_reshape_shape_inputs()
  166. reshape_input_shapes = self.add_shape_for_reshape_input()
  167. extra_outputs.extend(reshape_shape_inputs)
  168. extra_outputs.extend(reshape_input_shapes)
  169. if len(extra_outputs) == 0:
  170. return
  171. names_to_evaluate = self.add_extra_graph_output(extra_outputs)
  172. # This tool does not support dynamic axes right now.
  173. self.use_static_input(self.bert_inputs, batch_size, sequence_length)
  174. with open(temp_model_path, "wb") as out:
  175. out.write(self.model.SerializeToString())
  176. sess_options = onnxruntime.SessionOptions()
  177. sess_options.graph_optimization_level = onnxruntime.GraphOptimizationLevel.ORT_DISABLE_ALL
  178. session = onnxruntime.InferenceSession(
  179. temp_model_path,
  180. sess_options,
  181. providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
  182. )
  183. elem_type = 7
  184. for input in self.model.graph.input:
  185. if input.name == input_ids:
  186. elem_type = input.type.tensor_type.elem_type
  187. inputs = self.create_dummy_inputs(input_ids, segment_ids, input_mask, batch_size, sequence_length, elem_type)
  188. outputs = session.run(names_to_evaluate, inputs)
  189. shapes = {}
  190. for i, name in enumerate(names_to_evaluate):
  191. shapes[name] = outputs[i]
  192. logger.debug(f"shapes={shapes}")
  193. if enable_reshape_opt:
  194. for i, shape_input in enumerate(reshape_shape_inputs):
  195. input_shape = reshape_input_shapes[i]
  196. self.update_target_shape(shapes, shape_input, input_shape, verbose)
  197. for name, shape in shapes.items():
  198. tensor = self.add_shape_initializer(shape)
  199. self.replace_input_of_all_nodes(name, tensor.name)
  200. # Remove extra outputs, and prune all nodes not linked to output.
  201. self.prune_graph(output_names)
  202. def update_target_shape(self, shapes, shape_input, input_shape, verbose):
  203. """
  204. Update the target shape to use 0 to represent that dimension value does not change.
  205. For example, shape of source data is (2, 5, 8) and target shape is (2, 5, 4, 2), the target shape will be updated to (0, 0, 4, 2).
  206. """
  207. if shape_input in shapes:
  208. target_shape = shapes[shape_input]
  209. else:
  210. initializer = self.get_initializer(shape_input)
  211. assert initializer is not None
  212. target_shape = numpy_helper.to_array(initializer)
  213. if input_shape in shapes:
  214. source_shape = shapes[input_shape]
  215. else:
  216. initializer = self.get_initializer(input_shape)
  217. assert initializer is not None
  218. source_shape = numpy_helper.to_array(initializer)
  219. new_target_shape = []
  220. for i, dim_value in enumerate(target_shape):
  221. if i < len(source_shape) and source_shape[i] == dim_value:
  222. new_target_shape.append(0)
  223. else:
  224. new_target_shape.append(dim_value)
  225. shapes[shape_input] = new_target_shape
  226. logger.debug(f"source_shape={source_shape}, target_shape={target_shape}, new_target_shape={new_target_shape}")
  227. def validate_input(self, input: str):
  228. if not self.find_graph_input(input):
  229. valid_names = [input.name for input in self.model.graph.input]
  230. raise Exception("Input {} does not exist in the graph inputs: {}".format(input, valid_names))
  231. def validate_outputs(self, output_names: List[str]):
  232. valid_names = [output.name for output in self.model.graph.output]
  233. for name in output_names:
  234. if name not in valid_names:
  235. raise Exception("Output {} does not exist in the graph outputs: {}".format(name, valid_names))
  236. def optimize(
  237. self,
  238. output_path: str,
  239. input_ids: str,
  240. segment_ids: str,
  241. input_mask: str,
  242. enable_shape_opt: bool,
  243. enable_reshape_opt: bool,
  244. output_names: List[str] = None,
  245. batch_size=1,
  246. sequence_length=128,
  247. verbose=False,
  248. ):
  249. # Skip if shape optimization has been done before.
  250. for tensor in self.model.graph.initializer:
  251. if tensor.name.startswith(CONSTANT_SHAPE_NAME_PREFIX):
  252. logger.info("Skip shape optimization since it has been done before")
  253. return
  254. self.validate_input(input_ids)
  255. self.validate_input(segment_ids)
  256. self.validate_input(input_mask)
  257. if output_names is not None:
  258. self.validate_outputs(output_names)
  259. self.prune_graph(output_names)
  260. remaining_outputs = [output.name for output in self.model.graph.output]
  261. if enable_shape_opt or enable_reshape_opt:
  262. if len(self.get_graph_inputs_excluding_initializers()) != 3:
  263. logger.info("Skip shape optimization since graph input number is not 3")
  264. return
  265. with tempfile.TemporaryDirectory() as temp_dir:
  266. temp_file_name = "temp_{}.onnx".format(datetime.now().strftime("%m_%d-%H_%M_%S"))
  267. dir = "." if verbose else temp_dir
  268. temp_file = os.path.join(dir, temp_file_name)
  269. self.shape_optimization(
  270. temp_file,
  271. input_ids,
  272. segment_ids,
  273. input_mask,
  274. remaining_outputs,
  275. batch_size,
  276. sequence_length,
  277. enable_shape_opt,
  278. enable_reshape_opt,
  279. verbose,
  280. )
  281. logger.debug(f"Temp model with additional outputs: {temp_file}")
  282. logger.warning(
  283. f"Shape optimization is done. The optimized model might only work for input with batch_size={batch_size} sequence_length={sequence_length}"
  284. )
  285. if output_path is not None:
  286. with open(output_path, "wb") as out:
  287. out.write(self.model.SerializeToString())
  288. def parse_arguments():
  289. parser = argparse.ArgumentParser()
  290. parser.add_argument("--input", required=True, type=str)
  291. parser.add_argument("--output", required=True, type=str)
  292. parser.add_argument("--input_ids", required=True, type=str)
  293. parser.add_argument("--segment_ids", required=True, type=str)
  294. parser.add_argument("--input_mask", required=True, type=str)
  295. parser.add_argument("--output_names", required=False, type=str, default=None)
  296. parser.add_argument("--batch_size", required=False, type=int, default=1)
  297. parser.add_argument("--sequence_length", required=False, type=int, default=128)
  298. parser.add_argument("--enable_shape_opt", required=False, action="store_true")
  299. parser.set_defaults(enable_shape_opt=False)
  300. parser.add_argument("--enable_reshape_opt", required=False, action="store_true")
  301. parser.set_defaults(enable_reshape_opt=False)
  302. parser.add_argument("--verbose", required=False, action="store_true")
  303. parser.set_defaults(verbose=False)
  304. args = parser.parse_args()
  305. return args
  306. def setup_logging(verbose):
  307. log_handler = logging.StreamHandler(sys.stdout)
  308. if verbose:
  309. log_handler.setFormatter(logging.Formatter("[%(filename)s:%(lineno)s - %(funcName)20s()] %(message)s"))
  310. logging_level = logging.DEBUG
  311. else:
  312. log_handler.setFormatter(logging.Formatter("%(filename)20s: %(message)s"))
  313. logging_level = logging.INFO
  314. log_handler.setLevel(logging_level)
  315. logger.addHandler(log_handler)
  316. logger.setLevel(logging_level)
  317. def main():
  318. args = parse_arguments()
  319. setup_logging(args.verbose)
  320. output_names = None if args.output_names is None else args.output_names.split(";")
  321. model = ModelProto()
  322. with open(args.input, "rb") as input_file:
  323. model.ParseFromString(input_file.read())
  324. onnx_model = OnnxModel(model)
  325. optimizer = BertOnnxModelShapeOptimizer(onnx_model)
  326. optimizer.optimize(
  327. args.output,
  328. args.input_ids,
  329. args.segment_ids,
  330. args.input_mask,
  331. args.enable_shape_opt,
  332. args.enable_reshape_opt,
  333. output_names,
  334. args.batch_size,
  335. args.sequence_length,
  336. args.verbose,
  337. )
  338. if __name__ == "__main__":
  339. main()