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.

1043 lines
40 KiB

6 months ago
  1. # -------------------------------------------------------------------------
  2. # Copyright (c) Microsoft Corporation. All rights reserved.
  3. # Licensed under the MIT License. See License.txt in the project root for
  4. # license information.
  5. # --------------------------------------------------------------------------
  6. # This script helps onnx conversion and validation for GPT2 model with past state.
  7. import logging
  8. import os
  9. import pickle
  10. import random
  11. import shutil
  12. import sys
  13. import tempfile
  14. import time
  15. from pathlib import Path
  16. from typing import Dict, List, Tuple, Union
  17. import numpy
  18. import onnx
  19. import torch
  20. from transformers import GPT2Config, GPT2LMHeadModel, GPT2Model, TFGPT2Model
  21. sys.path.append(os.path.join(os.path.dirname(__file__), "..", ".."))
  22. from benchmark_helper import Precision
  23. from float16 import float_to_float16_max_diff
  24. from io_binding_helper import IOBindingHelper
  25. from onnx_model import OnnxModel
  26. from torch_onnx_export_helper import torch_onnx_export
  27. logger = logging.getLogger(__name__)
  28. PRETRAINED_GPT2_MODELS = ["distilgpt2", "gpt2", "gpt2-medium", "gpt2-large", "gpt2-xl"]
  29. DEFAULT_TOLERANCE = {
  30. Precision.FLOAT32: 0.0005,
  31. Precision.FLOAT16: 0.2,
  32. Precision.INT8: 3.0,
  33. }
  34. class GPT2ModelNoPastState(GPT2Model):
  35. """Here we wrap a class to disable past state output."""
  36. def __init__(self, config):
  37. super().__init__(config)
  38. def forward(self, input_ids):
  39. return super().forward(input_ids, use_cache=False, return_dict=False)
  40. class TFGPT2ModelNoPastState(TFGPT2Model):
  41. """Here we wrap a class to disable past state output."""
  42. def __init__(self, config):
  43. config.use_cache = False
  44. super().__init__(config)
  45. def forward(self, input_ids):
  46. return super().call(input_ids, use_cache=False)
  47. class MyGPT2Model(GPT2Model):
  48. """Here we wrap a class for Onnx model conversion for GPT2Model with past state."""
  49. def __init__(self, config):
  50. super().__init__(config)
  51. @staticmethod
  52. def post_process(result, num_layer):
  53. if isinstance(result[1][0], tuple) or isinstance(result[1][0], list):
  54. assert len(result[1]) == num_layer and len(result[1][0]) == 2
  55. # assert len(result[1][0][0].shape) == 4 and result[1][0][0].shape == result[1][0][1].shape
  56. present = []
  57. for i in range(num_layer):
  58. # Since transformers v4.*, past key and values are separated outputs.
  59. # Here we concate them into one tensor to be compatible with Attention operator.
  60. present.append(
  61. torch.cat(
  62. (result[1][i][0].unsqueeze(0), result[1][i][1].unsqueeze(0)),
  63. dim=0,
  64. )
  65. )
  66. return (result[0], tuple(present))
  67. return result
  68. def forward(self, input_ids, position_ids, attention_mask, *past):
  69. result = super().forward(
  70. input_ids,
  71. position_ids=position_ids,
  72. attention_mask=attention_mask,
  73. past_key_values=past,
  74. return_dict=False,
  75. )
  76. return MyGPT2Model.post_process(result, self.config.n_layer)
  77. class MyGPT2LMHeadModel(GPT2LMHeadModel):
  78. """Here we wrap a class for Onnx model conversion for GPT2LMHeadModel with past state."""
  79. def __init__(self, config):
  80. super().__init__(config)
  81. def forward(self, input_ids, position_ids, attention_mask, *past):
  82. result = super().forward(
  83. input_ids,
  84. position_ids=position_ids,
  85. attention_mask=attention_mask,
  86. past_key_values=past,
  87. return_dict=False,
  88. )
  89. return MyGPT2Model.post_process(result, self.config.n_layer)
  90. class MyGPT2LMHeadModel_NoPadding(GPT2LMHeadModel):
  91. """Here we wrap a class for Onnx model conversion for GPT2LMHeadModel with past state and no padding.
  92. When you always use batch_size=1 in inference, there is no padding in inputs. In such case, position_ids
  93. and attention_mask need no be in inputs.
  94. """
  95. def __init__(self, config):
  96. super().__init__(config)
  97. def forward(self, input_ids, *past):
  98. result = super().forward(input_ids, past_key_values=past, return_dict=False)
  99. return MyGPT2Model.post_process(result, self.config.n_layer)
  100. # Maps model class name to a tuple of model class, name of first output and use padding or not
  101. MODEL_CLASSES = {
  102. "GPT2LMHeadModel": (MyGPT2LMHeadModel, "logits", True),
  103. "GPT2LMHeadModel_NoPadding": (MyGPT2LMHeadModel_NoPadding, "logits", False),
  104. "GPT2Model": (MyGPT2Model, "last_state", True),
  105. }
  106. class Gpt2Inputs:
  107. def __init__(self, input_ids, position_ids, attention_mask, past):
  108. self.input_ids: torch.LongTensor = input_ids
  109. self.position_ids: torch.LongTensor = position_ids
  110. self.attention_mask: Union[torch.LongTensor, torch.FloatTensor, torch.HalfTensor] = attention_mask
  111. self.past: Union[List[torch.FloatTensor], List[torch.HalfTensor]] = past
  112. def to_list(self) -> List:
  113. input_list = [v for v in [self.input_ids, self.position_ids, self.attention_mask] if v is not None]
  114. if self.past:
  115. input_list.extend(self.past)
  116. return input_list
  117. def to_tuple(self) -> Tuple:
  118. return tuple(v for v in [self.input_ids, self.position_ids, self.attention_mask, self.past] if v is not None)
  119. def to_fp32(self):
  120. # For attention mask, only convert fp16 to fp32, and keep the original type if it is integer.
  121. attention_mask = None
  122. if self.attention_mask is not None:
  123. attention_mask = (
  124. self.attention_mask.to(dtype=torch.float32)
  125. if (self.attention_mask.dtype == torch.float16)
  126. else self.attention_mask
  127. )
  128. past = [p.to(dtype=torch.float32) for p in self.past]
  129. return Gpt2Inputs(self.input_ids, self.position_ids, attention_mask, past)
  130. class Gpt2Helper:
  131. """A helper class for Gpt2 model conversion, inference and verification."""
  132. @staticmethod
  133. def get_dummy_inputs(
  134. batch_size: int,
  135. past_sequence_length: int,
  136. sequence_length: int,
  137. num_attention_heads: int,
  138. hidden_size: int,
  139. num_layer: int,
  140. vocab_size: int,
  141. device: torch.device,
  142. float16: bool = False,
  143. has_position_ids: bool = True,
  144. has_attention_mask: bool = True,
  145. input_ids_dtype: torch.dtype = torch.int32,
  146. position_ids_dtype: torch.dtype = torch.int32,
  147. attention_mask_dtype: torch.dtype = torch.int32,
  148. left_side_padding: bool = True,
  149. ) -> Gpt2Inputs:
  150. """Create random inputs for GPT2 model.
  151. Returns torch tensors of input_ids, position_ids, attention_mask and a list of past state tensors.
  152. """
  153. float_type = torch.float16 if float16 else torch.float32
  154. past_shape = [
  155. 2,
  156. batch_size,
  157. num_attention_heads,
  158. past_sequence_length,
  159. int(hidden_size / num_attention_heads),
  160. ]
  161. past = [(torch.rand(past_shape, dtype=float_type, device=device) * 2.0 - 1.0) for _ in range(num_layer)]
  162. input_ids = torch.randint(
  163. low=0,
  164. high=vocab_size - 1,
  165. size=(batch_size, sequence_length),
  166. dtype=input_ids_dtype,
  167. device=device,
  168. )
  169. attention_mask = None
  170. if has_attention_mask:
  171. total_sequence_length = past_sequence_length + sequence_length
  172. attention_mask = torch.ones(
  173. [batch_size, total_sequence_length],
  174. dtype=attention_mask_dtype,
  175. device=device,
  176. )
  177. if total_sequence_length >= 2:
  178. for i in range(batch_size):
  179. padding_length = random.randint(0, total_sequence_length - 1)
  180. if left_side_padding:
  181. attention_mask[i, :padding_length] = 0
  182. else: # right side padding
  183. attention_mask[i, total_sequence_length - padding_length :] = 0
  184. # Deduce position_ids from attention mask
  185. position_ids = None
  186. if has_position_ids:
  187. position_ids = attention_mask.long().cumsum(-1) - 1
  188. position_ids.masked_fill_(position_ids < 0, 0)
  189. position_ids = position_ids[:, past_sequence_length:].to(position_ids_dtype)
  190. return Gpt2Inputs(input_ids, position_ids, attention_mask, past)
  191. @staticmethod
  192. def get_output_shapes(
  193. batch_size: int,
  194. past_sequence_length: int,
  195. sequence_length: int,
  196. config: GPT2Config,
  197. model_class: str = "GPT2LMHeadModel",
  198. ) -> Dict[str, List[int]]:
  199. """Returns a dictionary with output name as key, and shape as value."""
  200. num_attention_heads = config.num_attention_heads
  201. hidden_size = config.hidden_size
  202. num_layer = config.num_hidden_layers
  203. vocab_size = config.vocab_size
  204. output_name = MODEL_CLASSES[model_class][1]
  205. last_state_shape = [
  206. batch_size,
  207. sequence_length,
  208. vocab_size if output_name == "logits" else hidden_size,
  209. ]
  210. present_state_shape = [
  211. 2,
  212. batch_size,
  213. num_attention_heads,
  214. past_sequence_length + sequence_length,
  215. int(hidden_size / num_attention_heads),
  216. ]
  217. output_shapes = {output_name: last_state_shape}
  218. for i in range(num_layer):
  219. output_shapes["present_" + str(i)] = present_state_shape
  220. return output_shapes
  221. @staticmethod
  222. def auto_increase_buffer_size(output_buffers, output_shapes):
  223. for key in output_shapes:
  224. assert key in output_buffers
  225. buffer = output_buffers[key]
  226. if numpy.prod(output_shapes[key]) > buffer.nelement():
  227. output_buffers[key] = torch.empty(
  228. numpy.prod(output_shapes[key]),
  229. dtype=buffer.dtype,
  230. device=buffer.device,
  231. )
  232. @staticmethod
  233. def get_output_buffers(output_shapes, device, is_float16=False):
  234. """Returns a dictionary of output name as key, and 1D tensor as value. The tensor has enough space for given shape."""
  235. data_type = torch.float16 if is_float16 else torch.float32
  236. output_buffers = {}
  237. for name, shape in output_shapes.items():
  238. output_buffers[name] = torch.empty(numpy.prod(shape), dtype=data_type, device=device)
  239. return output_buffers
  240. @staticmethod
  241. def diff_outputs(torch_outputs, ort_outputs, relative=False):
  242. """Returns the maximum difference between PyTorch and OnnxRuntime outputs."""
  243. expected_outputs = torch_outputs[0].cpu().numpy()
  244. diff = numpy.abs(expected_outputs - ort_outputs[0])
  245. if relative:
  246. return numpy.amax(diff / (numpy.abs(expected_outputs) + 1e-6))
  247. else:
  248. return numpy.amax(diff)
  249. @staticmethod
  250. def compare_outputs(torch_outputs, ort_outputs, rtol=1e-03, atol=1e-03, **kwargs):
  251. """Returns True if torch and ORT outputs are close for given thresholds, and False otherwise.
  252. Note: need kwargs since Gpt2BeamSearchHelper.compare_outputs has an extra parameter model_class
  253. """
  254. is_close = numpy.allclose(ort_outputs[0], torch_outputs[0].cpu().numpy(), rtol=rtol, atol=atol)
  255. logger.debug(f"PyTorch and OnnxRuntime output 0 (last_state) are close: {is_close}")
  256. is_all_close = is_close
  257. num_layers = len(ort_outputs) - 1
  258. for layer in range(num_layers):
  259. is_close = numpy.allclose(
  260. ort_outputs[1 + layer],
  261. torch_outputs[1][layer].cpu().numpy(),
  262. rtol=rtol,
  263. atol=atol,
  264. )
  265. logger.debug(f"PyTorch and OnnxRuntime layer {layer} state (present_{layer}) are close:{is_close}")
  266. is_all_close = is_all_close and is_close
  267. if not is_all_close:
  268. max_abs_diff = Gpt2Helper.diff_outputs(torch_outputs, ort_outputs)
  269. logger.info(f"PyTorch and OnnxRuntime results are not all close: max_abs_diff={max_abs_diff:.5f}")
  270. return is_all_close
  271. @staticmethod
  272. def compare_outputs_v2(torch_outputs, ort_outputs, atol=1e-06):
  273. """Compare outputs from PyTorch and OnnxRuntime
  274. Args:
  275. torch_outputs (Tuple[Torch.Tensor]): PyTorch model output
  276. ort_outputs (List[numpy.ndarray]): OnnxRuntime output
  277. atol (float, optional): Absolute tollerance. Defaults to 1e-06.
  278. Returns:
  279. is_all_close(bool): whether all elements are close.
  280. max_abs_diff(float): maximum absolute difference.
  281. messages(str): a list of debug message for each output
  282. """
  283. is_all_close = True
  284. is_top1_matched = False
  285. max_diffs = []
  286. messages = []
  287. for i in range(len(ort_outputs)):
  288. ort_output = ort_outputs[i]
  289. torch_output = (torch_outputs[0] if i == 0 else torch_outputs[1][i - 1]).cpu().numpy()
  290. is_close = numpy.allclose(ort_output, torch_output, atol=atol, rtol=0)
  291. max_diffs.append(numpy.amax(numpy.abs(torch_output - ort_output)))
  292. is_all_close = is_all_close and is_close
  293. if numpy.isnan(torch_output).any():
  294. logger.debug(f"PyTorch output {i} has nan")
  295. if numpy.isinf(torch_output).any():
  296. logger.debug(f"PyTorch output {i} has inf")
  297. if numpy.isnan(ort_output).any():
  298. logger.debug(f"ORT output {i} has nan")
  299. if numpy.isinf(ort_output).any():
  300. logger.debug(f"ORT output {i} has inf")
  301. diff = numpy.fabs(ort_output - torch_output)
  302. idx = numpy.unravel_index(diff.argmax(), diff.shape)
  303. messages.append(
  304. f"diff={diff[idx]:.9f} index={idx} ort={ort_output[idx]:.9f} torch={float(torch_output[idx]):.9f}"
  305. )
  306. if i == 0: # logits
  307. ort_max_index = numpy.unravel_index(numpy.argmax(ort_output, axis=None), ort_output.shape)
  308. torch_max_index = numpy.unravel_index(numpy.argmax(torch_output, axis=None), torch_output.shape)
  309. is_top1_matched = numpy.array_equal(ort_max_index, torch_max_index)
  310. max_diff_output_index = max_diffs.index(max(max_diffs))
  311. return (
  312. is_all_close,
  313. max(max_diffs),
  314. max_diff_output_index,
  315. messages,
  316. is_top1_matched,
  317. )
  318. @staticmethod
  319. def export_onnx(
  320. model,
  321. device,
  322. onnx_model_path: str,
  323. verbose: bool = False,
  324. use_external_data_format: bool = False,
  325. has_position_ids: bool = True,
  326. has_attention_mask: bool = True,
  327. input_ids_dtype: torch.dtype = torch.int32,
  328. position_ids_dtype: torch.dtype = torch.int32,
  329. attention_mask_dtype: torch.dtype = torch.int32,
  330. ):
  331. """Export GPT-2 model with past state to ONNX model."""
  332. config: GPT2Config = model.config
  333. num_layer = config.n_layer
  334. dummy_inputs = Gpt2Helper.get_dummy_inputs(
  335. batch_size=1,
  336. past_sequence_length=1,
  337. sequence_length=1,
  338. num_attention_heads=config.num_attention_heads,
  339. hidden_size=config.hidden_size,
  340. num_layer=num_layer,
  341. vocab_size=config.vocab_size,
  342. device=device,
  343. float16=False,
  344. has_position_ids=has_position_ids,
  345. has_attention_mask=has_attention_mask,
  346. input_ids_dtype=input_ids_dtype,
  347. position_ids_dtype=position_ids_dtype,
  348. attention_mask_dtype=attention_mask_dtype,
  349. )
  350. input_list = dummy_inputs.to_list()
  351. with torch.no_grad():
  352. outputs = model(*input_list)
  353. past_names = [f"past_{i}" for i in range(num_layer)]
  354. present_names = [f"present_{i}" for i in range(num_layer)]
  355. # GPT2Model outputs last_state; GPT2LMHeadModel outputs logits (prediction_scores)
  356. assert outputs[0].shape[2] == config.vocab_size or outputs[0].shape[2] == config.hidden_size
  357. output_names = ["logits" if outputs[0].shape[2] == config.vocab_size else "last_state"] + present_names
  358. # Shape of input tensors:
  359. # input_ids: (batch_size, seq_len)
  360. # past_{i}: (2, batch_size, num_heads, past_seq_len, hidden_size/num_heads)
  361. # attention_mask: (batch_size, past_seq_len + seq_len)
  362. # Shape of output tensors:
  363. # last_state: (batch_size, seq_len, hidden_size)
  364. # or logits: (batch_size, seq_len, vocab_size)
  365. # present_{i}: (2, batch_size, num_heads, past_seq_len + seq_len, hidden_size/num_heads)
  366. dynamic_axes = {
  367. "input_ids": {0: "batch_size", 1: "seq_len"},
  368. output_names[0]: {0: "batch_size", 1: "seq_len"},
  369. }
  370. for name in past_names:
  371. dynamic_axes[name] = {1: "batch_size", 3: "past_seq_len"}
  372. for name in present_names:
  373. dynamic_axes[name] = {1: "batch_size", 3: "total_seq_len"}
  374. input_names = ["input_ids"]
  375. if has_position_ids:
  376. dynamic_axes["position_ids"] = {0: "batch_size", 1: "seq_len"}
  377. input_names.append("position_ids")
  378. if has_attention_mask:
  379. dynamic_axes["attention_mask"] = {0: "batch_size", 1: "total_seq_len"}
  380. input_names.append("attention_mask")
  381. input_names.extend(past_names)
  382. assert len(outputs) == 2 and len(outputs[1]) == num_layer
  383. logger.info(
  384. f"Shapes: input_ids={dummy_inputs.input_ids.shape} past={dummy_inputs.past[0].shape} output={outputs[0].shape} present={outputs[1][0].shape}"
  385. )
  386. Path(onnx_model_path).parent.mkdir(parents=True, exist_ok=True)
  387. if use_external_data_format:
  388. # We let PyTorch export onnx to a temp directory first, then convert external data to one file.
  389. with tempfile.TemporaryDirectory() as tmp_dir_name:
  390. temp_onnx_model_path = os.path.join(tmp_dir_name, "gpt2.onnx")
  391. Path(temp_onnx_model_path).parent.mkdir(parents=True, exist_ok=True)
  392. torch_onnx_export(
  393. model,
  394. args=tuple(input_list),
  395. f=temp_onnx_model_path,
  396. export_params=True,
  397. input_names=input_names,
  398. output_names=output_names,
  399. dynamic_axes=dynamic_axes,
  400. opset_version=11,
  401. do_constant_folding=True,
  402. use_external_data_format=True,
  403. verbose=verbose,
  404. )
  405. model = onnx.load_model(temp_onnx_model_path, load_external_data=True)
  406. OnnxModel.save(
  407. model,
  408. onnx_model_path,
  409. save_as_external_data=True,
  410. all_tensors_to_one_file=True,
  411. )
  412. else:
  413. torch_onnx_export(
  414. model,
  415. args=tuple(input_list),
  416. f=onnx_model_path,
  417. export_params=True,
  418. input_names=input_names,
  419. output_names=output_names,
  420. dynamic_axes=dynamic_axes,
  421. opset_version=11,
  422. do_constant_folding=True,
  423. use_external_data_format=False,
  424. verbose=verbose,
  425. )
  426. @staticmethod
  427. def optimize_onnx(
  428. onnx_model_path,
  429. optimized_model_path,
  430. is_float16,
  431. num_attention_heads,
  432. hidden_size,
  433. use_external_data_format=False,
  434. auto_mixed_precision=False,
  435. stage=0,
  436. **kwargs,
  437. ):
  438. """Optimize ONNX model with an option to convert it to use mixed precision."""
  439. from fusion_options import FusionOptions
  440. from optimizer import optimize_model
  441. optimization_options = FusionOptions("gpt2")
  442. # TODO(hasesh): Investigate parity issue for GPT-2 fp16 when SkipLayerNormalization
  443. # is enabled
  444. if is_float16:
  445. optimization_options.enable_skip_layer_norm = False
  446. m = optimize_model(
  447. onnx_model_path,
  448. model_type="gpt2",
  449. num_heads=num_attention_heads,
  450. hidden_size=hidden_size,
  451. opt_level=0,
  452. optimization_options=optimization_options,
  453. use_gpu=False,
  454. )
  455. if is_float16:
  456. if auto_mixed_precision:
  457. Gpt2Helper.auto_mixed_precision(m)
  458. else:
  459. if "keep_io_types" not in kwargs:
  460. kwargs["keep_io_types"] = False
  461. m.convert_float_to_float16(use_symbolic_shape_infer=True, **kwargs)
  462. m.save_model_to_file(optimized_model_path, use_external_data_format)
  463. return m
  464. @staticmethod
  465. def auto_mixed_precision(
  466. onnx_model: OnnxModel,
  467. op_block_list: List[str] = [
  468. "Add",
  469. "LayerNormalization",
  470. "SkipLayerNormalization",
  471. "FastGelu",
  472. "EmbedLayerNormalization",
  473. ],
  474. ):
  475. """Convert GPT-2 model to mixed precision.
  476. It detects whether original model has fp16 weights, and set parameters for float16 conversion automatically.
  477. Args:
  478. onnx_model (OnnxModel): optimized ONNX model
  479. op_block_list (List[str], optional): operators to compute in fp32. Defaults to ["Add", "LayerNormalization",
  480. "SkipLayerNormalization", "FastGelu", "EmbedLayerNormalization"]
  481. Returns:
  482. parameters(dict): a dictionary of parameters used in float16 conversion
  483. """
  484. op_full_set = set([node.op_type for node in onnx_model.nodes()])
  485. fp32_op_set = set(op_block_list)
  486. fp16_op_set = op_full_set.difference(fp32_op_set)
  487. logger.info(f"fp32 op: {fp32_op_set} fp16 op: {fp16_op_set}")
  488. # logits is the first output
  489. logits_output_name = onnx_model.graph().output[0].name
  490. # We use the weight in last MatMul node to detect whether the model is stored with float16 weights from training.
  491. is_weight_fp16_precision = False
  492. output_name_to_node = onnx_model.output_name_to_node()
  493. assert logits_output_name in output_name_to_node
  494. node = output_name_to_node[logits_output_name]
  495. last_matmul_node = None
  496. if node.op_type == "MatMul":
  497. last_matmul_node = node
  498. logger.info(f"Found last MatMul node for logits: {node.name}")
  499. initializer = None
  500. for input in node.input:
  501. initializer = onnx_model.get_initializer(input)
  502. if initializer is not None:
  503. break
  504. # when the max difference of value after converting float to float16 is lower than a threshold (1e-6),
  505. # we can deduce that the weights are stored in float16 precision.
  506. max_diff = float_to_float16_max_diff(initializer)
  507. logger.debug(f"max diff of converting weights in last MatMul node {node.name}: {max_diff}")
  508. is_weight_fp16_precision = max_diff < 1e-6
  509. else:
  510. logger.warning(f"Failed to find MatMul node for logits. Found {node.op_type} of node {node.name}")
  511. keep_io_types = []
  512. node_block_list = []
  513. if (not is_weight_fp16_precision) and (last_matmul_node is not None):
  514. # When original weight is float32 precision, keep logits and last MatMul in float32 could get better precision.
  515. keep_io_types = [logits_output_name]
  516. node_block_list = [last_matmul_node.name]
  517. parameters = {
  518. "keep_io_types": keep_io_types,
  519. "op_block_list": op_block_list,
  520. "node_block_list": node_block_list,
  521. "force_fp16_initializers": is_weight_fp16_precision,
  522. }
  523. logger.info(f"auto_mixed_precision parameters: {parameters}")
  524. onnx_model.convert_float_to_float16(use_symbolic_shape_infer=True, **parameters)
  525. return parameters
  526. @staticmethod
  527. def pytorch_inference(model, inputs: Gpt2Inputs, total_runs: int = 0):
  528. """Run inference of PyTorch model, and returns average latency in ms when total_runs > 0 besides outputs."""
  529. logger.debug("start pytorch_inference")
  530. # Convert it to fp32 as the PyTroch model cannot deal with half input.
  531. input_list = inputs.to_fp32().to_list()
  532. with torch.no_grad():
  533. outputs = model(*input_list)
  534. if total_runs == 0:
  535. return outputs
  536. latency = []
  537. with torch.no_grad():
  538. for _ in range(total_runs):
  539. start = time.time()
  540. outputs = model(*input_list)
  541. latency.append(time.time() - start)
  542. average_latency = sum(latency) * 1000 / len(latency)
  543. logger.debug("PyTorch inference time = {} ms".format(format(average_latency, ".2f")))
  544. return outputs, average_latency
  545. @staticmethod
  546. def onnxruntime_inference(ort_session, inputs: Gpt2Inputs, total_runs: int = 0):
  547. """Run inference of ONNX model, and returns average latency in ms when total_runs > 0 besides outputs."""
  548. logger.debug(f"start onnxruntime_inference")
  549. ort_inputs = {"input_ids": numpy.ascontiguousarray(inputs.input_ids.cpu().numpy())}
  550. if inputs.past is not None:
  551. for i, past_i in enumerate(inputs.past):
  552. ort_inputs[f"past_{i}"] = numpy.ascontiguousarray(past_i.cpu().numpy())
  553. if inputs.attention_mask is not None:
  554. ort_inputs["attention_mask"] = numpy.ascontiguousarray(inputs.attention_mask.cpu().numpy())
  555. if inputs.position_ids is not None:
  556. ort_inputs["position_ids"] = numpy.ascontiguousarray(inputs.position_ids.cpu().numpy())
  557. ort_outputs = ort_session.run(None, ort_inputs)
  558. if total_runs == 0:
  559. return ort_outputs
  560. latency = []
  561. for _ in range(total_runs):
  562. start = time.time()
  563. ort_outputs = ort_session.run(None, ort_inputs)
  564. latency.append(time.time() - start)
  565. average_latency = sum(latency) * 1000 / len(latency)
  566. logger.debug("OnnxRuntime Inference time = {} ms".format(format(average_latency, ".2f")))
  567. return ort_outputs, average_latency
  568. @staticmethod
  569. def prepare_io_binding(
  570. ort_session,
  571. input_ids,
  572. position_ids,
  573. attention_mask,
  574. past,
  575. output_buffers,
  576. output_shapes,
  577. ):
  578. """Returnas IO binding object for a session."""
  579. return IOBindingHelper.prepare_io_binding(
  580. ort_session,
  581. input_ids,
  582. position_ids,
  583. attention_mask,
  584. past,
  585. output_buffers,
  586. output_shapes,
  587. )
  588. @staticmethod
  589. def get_outputs_from_io_binding_buffer(ort_session, output_buffers, output_shapes, return_numpy=True):
  590. """Copy results to cpu. Returns a list of numpy array."""
  591. return IOBindingHelper.get_outputs_from_io_binding_buffer(
  592. ort_session, output_buffers, output_shapes, return_numpy
  593. )
  594. @staticmethod
  595. def onnxruntime_inference_with_binded_io(
  596. ort_session,
  597. inputs: Gpt2Inputs,
  598. output_buffers: Dict[str, torch.Tensor],
  599. output_shapes: Dict[str, List[int]],
  600. total_runs: int = 0,
  601. return_numpy: bool = True,
  602. include_copy_output_latency: bool = False,
  603. ):
  604. """Inference with IO binding. Returns outputs, and optional latency when total_runs > 0."""
  605. logger.debug(f"start onnxruntime_inference_with_binded_io")
  606. # Bind inputs and outputs to onnxruntime session
  607. io_binding = Gpt2Helper.prepare_io_binding(
  608. ort_session,
  609. inputs.input_ids,
  610. inputs.position_ids,
  611. inputs.attention_mask,
  612. inputs.past,
  613. output_buffers,
  614. output_shapes,
  615. )
  616. # Run onnxruntime with io binding
  617. ort_session.run_with_iobinding(io_binding)
  618. # Copy results to cpu for verification
  619. ort_outputs = Gpt2Helper.get_outputs_from_io_binding_buffer(
  620. ort_session, output_buffers, output_shapes, return_numpy
  621. )
  622. if total_runs == 0:
  623. return ort_outputs
  624. latency = []
  625. for _ in range(total_runs):
  626. start = time.time()
  627. # Run onnxruntime with io binding
  628. ort_session.run_with_iobinding(io_binding)
  629. if include_copy_output_latency:
  630. _ = Gpt2Helper.get_outputs_from_io_binding_buffer(
  631. ort_session, output_buffers, output_shapes, return_numpy
  632. )
  633. latency.append(time.time() - start)
  634. average_latency = sum(latency) * 1000 / len(latency)
  635. logger.debug("OnnxRuntime with IO binding inference time = {} ms".format(format(average_latency, ".2f")))
  636. return ort_outputs, average_latency
  637. @staticmethod
  638. def save_outputs(i, ort_outputs, torch_outputs):
  639. with open(f"ort_outputs_{i}.pickle", "wb") as f:
  640. pickle.dump(ort_outputs, f)
  641. logger.info(f"ORT output are saved to ort_outputs_{i}.pickle")
  642. with open(f"torch_outputs_{i}.pickle", "wb") as f:
  643. pickle.dump(torch_outputs, f)
  644. logger.info(f"Torch output are saved to torch_outputs_{i}.pickle")
  645. @staticmethod
  646. def save_inputs(i, dummy_inputs, ort_outputs, torch_outputs):
  647. with open(f"dummy_inputs_{i}.pickle", "wb") as f:
  648. pickle.dump(dummy_inputs, f)
  649. logger.info(f"inputs are saved to dummy_inputs_{i}.pickle")
  650. @staticmethod
  651. def test_parity(
  652. ort_session,
  653. model,
  654. device,
  655. is_float16=False,
  656. rtol=5e-4,
  657. atol=5e-4,
  658. test_cases_per_run=10000,
  659. total_runs=1,
  660. use_io_binding=True,
  661. model_class="GPT2LMHeadModel",
  662. has_position_ids=True,
  663. has_attention_mask=True,
  664. input_ids_dtype=torch.int32,
  665. position_ids_dtype=torch.int32,
  666. attention_mask_dtype=torch.int32,
  667. stage=0,
  668. verbose=False,
  669. enable_pickle_output=False,
  670. ):
  671. """Generate random inputs and compare the results of PyTorch and Onnx Runtime."""
  672. config: GPT2Config = model.config
  673. logger.info(
  674. f"Running parity test (atol={atol}, test_cases={test_cases_per_run}, runs={total_runs}, use_io_binding={use_io_binding}, model_class={model_class}, is_float16={is_float16}) ..."
  675. )
  676. max_batch_size = 8
  677. max_past_seq_len = 4 # Do not use large number here for higher chance of hitting empty past (past_seq_len=0)
  678. max_seq_len = 2
  679. output_buffers = None
  680. if use_io_binding:
  681. max_output_shapes = Gpt2Helper.get_output_shapes(
  682. max_batch_size, max_past_seq_len, max_seq_len, config, model_class
  683. )
  684. output_buffers = Gpt2Helper.get_output_buffers(max_output_shapes, device, is_float16)
  685. passed_test_cases = 0
  686. top1_matched_cases = 0
  687. max_abs_diff_list = []
  688. top1_matched_cases_per_run = [0] * total_runs
  689. total_test_cases = test_cases_per_run * total_runs
  690. for i in range(total_test_cases):
  691. run_id = int(i / test_cases_per_run)
  692. sequence_length = random.randint(1, max_seq_len)
  693. past_sequence_length = 0 if (stage == 1) else random.randint(0, max_past_seq_len)
  694. batch_size = random.randint(1, max_batch_size)
  695. logger.debug(
  696. f"Running parity test for batch_size={batch_size} past_sequence_length={past_sequence_length}..."
  697. )
  698. dummy_inputs = Gpt2Helper.get_dummy_inputs(
  699. batch_size,
  700. past_sequence_length,
  701. sequence_length,
  702. config.num_attention_heads,
  703. config.hidden_size,
  704. config.n_layer,
  705. config.vocab_size,
  706. device,
  707. is_float16,
  708. has_position_ids,
  709. has_attention_mask,
  710. input_ids_dtype=input_ids_dtype,
  711. position_ids_dtype=position_ids_dtype,
  712. attention_mask_dtype=attention_mask_dtype,
  713. left_side_padding=True,
  714. )
  715. outputs = Gpt2Helper.pytorch_inference(model, dummy_inputs)
  716. if use_io_binding:
  717. ort_outputs = Gpt2Helper.onnxruntime_inference(ort_session, dummy_inputs)
  718. else:
  719. output_shapes = Gpt2Helper.get_output_shapes(
  720. batch_size,
  721. past_sequence_length,
  722. sequence_length,
  723. config,
  724. model_class,
  725. )
  726. ort_outputs = Gpt2Helper.onnxruntime_inference_with_binded_io(
  727. ort_session, dummy_inputs, output_buffers, output_shapes
  728. )
  729. (
  730. is_all_close,
  731. max_abs_diff,
  732. max_diff_output_index,
  733. messages,
  734. is_top1_matched,
  735. ) = Gpt2Helper.compare_outputs_v2(outputs, ort_outputs, atol=atol)
  736. if not numpy.isnan(max_abs_diff):
  737. max_abs_diff_list.append(max_abs_diff)
  738. if is_all_close:
  739. passed_test_cases += 1
  740. if is_top1_matched:
  741. top1_matched_cases += 1
  742. top1_matched_cases_per_run[run_id] += 1
  743. if verbose and not is_all_close:
  744. logger.info(
  745. f"test_case={i} batch_size={batch_size} past_sequence_length={past_sequence_length} sequence_length={sequence_length} MaxDiff={max_abs_diff}"
  746. )
  747. for i, message in enumerate(messages):
  748. logger.info(f"\t{i}: Name={ort_session.get_outputs()[i].name}, {message}")
  749. # Collect data for debugging
  750. if enable_pickle_output and (numpy.isnan(max_abs_diff) or max_abs_diff > 100 * atol):
  751. Gpt2Helper.save_inputs(i, dummy_inputs)
  752. Gpt2Helper.save_outputs(i, ort_outputs, outputs)
  753. if max_abs_diff_list:
  754. result = {
  755. f"max_diff_percentile_{p}": "{:.5f}".format(numpy.percentile(max_abs_diff_list, p))
  756. for p in [50, 90, 95, 99]
  757. }
  758. else:
  759. result = {f"max_diff_percentile_{p}": "nan" for p in [50, 90, 95, 99]}
  760. result["top1_match_rate"] = top1_matched_cases * 1.0 / total_test_cases
  761. result["top1_match_rate_per_run"] = [x * 1.0 / test_cases_per_run for x in top1_matched_cases_per_run]
  762. result["diff_pass_rate"] = passed_test_cases * 1.0 / total_test_cases
  763. result["nan_rate"] = (total_test_cases - len(max_abs_diff_list)) * 1.0 / total_test_cases
  764. logger.info(
  765. f"Parity Test Cases={total_test_cases}; Passed={passed_test_cases}; Nan={total_test_cases-len(max_abs_diff_list)}; Top1_Matched={top1_matched_cases}"
  766. )
  767. if passed_test_cases > 0.95 * total_test_cases:
  768. logger.info(f"Parity is good: passed rate={int(passed_test_cases*100/total_test_cases):.0f}%")
  769. return result
  770. @staticmethod
  771. def test_performance(
  772. ort_session,
  773. model,
  774. device,
  775. is_float16=False,
  776. total_runs=100,
  777. use_io_binding=True,
  778. model_class="GPT2LMHeadModel",
  779. has_position_ids=True,
  780. has_attention_mask=True,
  781. input_ids_dtype=torch.int32,
  782. position_ids_dtype=torch.int32,
  783. attention_mask_dtype=torch.int32,
  784. batch_size=8,
  785. sequence_length=1,
  786. past_sequence_length=32,
  787. ):
  788. """Generate random inputs and measure average latency of Onnx Runtime."""
  789. config: GPT2Config = model.config
  790. output_buffers = None
  791. if use_io_binding:
  792. output_shapes = Gpt2Helper.get_output_shapes(
  793. batch_size, past_sequence_length, sequence_length, config, model_class
  794. )
  795. output_buffers = Gpt2Helper.get_output_buffers(output_shapes, device, is_float16)
  796. dummy_inputs = Gpt2Helper.get_dummy_inputs(
  797. batch_size,
  798. past_sequence_length,
  799. sequence_length,
  800. config.num_attention_heads,
  801. config.hidden_size,
  802. config.n_layer,
  803. config.vocab_size,
  804. device,
  805. is_float16,
  806. has_position_ids,
  807. has_attention_mask,
  808. input_ids_dtype=input_ids_dtype,
  809. position_ids_dtype=position_ids_dtype,
  810. attention_mask_dtype=attention_mask_dtype,
  811. )
  812. if use_io_binding:
  813. _, latency = Gpt2Helper.onnxruntime_inference(ort_session, dummy_inputs, total_runs)
  814. else:
  815. _, latency = Gpt2Helper.onnxruntime_inference_with_binded_io(
  816. ort_session, dummy_inputs, output_buffers, output_shapes, total_runs
  817. )
  818. return latency
  819. @staticmethod
  820. def torchscript(model, config, device, has_position_ids=True, has_attention_mask=True):
  821. """JIT trace for TorchScript."""
  822. input_list = Gpt2Helper.get_dummy_inputs(
  823. batch_size=1,
  824. past_sequence_length=1,
  825. sequence_length=1,
  826. num_attention_heads=config.num_attention_heads,
  827. hidden_size=config.hidden_size,
  828. num_layer=config.n_layer,
  829. vocab_size=config.vocab_size,
  830. device=device,
  831. float16=False,
  832. has_position_ids=has_position_ids,
  833. has_attention_mask=has_attention_mask,
  834. ).to_list()
  835. return torch.jit.trace(model, input_list)
  836. @staticmethod
  837. def get_onnx_paths(
  838. output_dir,
  839. model_name_or_path,
  840. model_class: str = "GPT2LMHeadModel",
  841. has_past=True,
  842. new_folder=False,
  843. remove_existing=["raw", "fp32", "fp16", "int8"],
  844. ):
  845. """Build a path name for given model based on given attributes."""
  846. model_name = model_name_or_path
  847. if os.path.isdir(model_name_or_path):
  848. model_name = Path(model_name_or_path).parts[-1]
  849. else:
  850. model_name.split("/")[-1]
  851. if model_class != "GPT2LMHeadModel":
  852. model_name += "_" + model_class
  853. if has_past:
  854. model_name += "_past"
  855. if new_folder:
  856. suffix = {"raw": "", "fp32": "_fp32", "fp16": "_fp16", "int8": "_int8"}
  857. # Remove the directories if existed.
  858. for model_type in ["raw", "fp32", "fp16", "int8"]:
  859. new_dir = os.path.join(output_dir, model_name + suffix[model_type])
  860. if os.path.exists(new_dir):
  861. if model_type in remove_existing:
  862. try:
  863. shutil.rmtree(new_dir)
  864. logger.info(f"Removed the existed directory: {new_dir}")
  865. except OSError as e:
  866. logger.info(f"Failed to remove the directory {new_dir}: {e.strerror}")
  867. else:
  868. logger.info(f"Directory for {model_type} existed: {new_dir}")
  869. # store each model to its own directory (for external data format).
  870. return {
  871. "raw": os.path.join(os.path.join(output_dir, model_name), model_name + ".onnx"),
  872. "fp32": os.path.join(
  873. os.path.join(output_dir, model_name + "_fp32"),
  874. model_name + "_fp32.onnx",
  875. ),
  876. "fp16": os.path.join(
  877. os.path.join(output_dir, model_name + "_fp16"),
  878. model_name + "_fp16.onnx",
  879. ),
  880. "int8": os.path.join(
  881. os.path.join(output_dir, model_name + "_int8"),
  882. model_name + "_int8.onnx",
  883. ),
  884. }
  885. return {
  886. "raw": os.path.join(output_dir, model_name + ".onnx"),
  887. "fp32": os.path.join(output_dir, model_name + "_fp32.onnx"),
  888. "fp16": os.path.join(output_dir, model_name + "_fp16.onnx"),
  889. "int8": os.path.join(output_dir, model_name + "_int8.onnx"),
  890. }