convert.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. # Copyright 2021 The HuggingFace Team. 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. import warnings
  15. from collections.abc import Iterable
  16. from inspect import signature
  17. from itertools import chain
  18. from pathlib import Path
  19. from typing import TYPE_CHECKING, Optional, Union
  20. import numpy as np
  21. from packaging.version import Version, parse
  22. from ..tokenization_utils_base import PreTrainedTokenizerBase
  23. from ..utils import (
  24. TensorType,
  25. is_tf_available,
  26. is_torch_available,
  27. logging,
  28. )
  29. from .config import OnnxConfig
  30. if is_torch_available():
  31. from ..modeling_utils import PreTrainedModel
  32. if is_tf_available():
  33. from ..modeling_tf_utils import TFPreTrainedModel
  34. if TYPE_CHECKING:
  35. from ..feature_extraction_utils import FeatureExtractionMixin
  36. from ..processing_utils import ProcessorMixin
  37. from ..tokenization_utils import PreTrainedTokenizer
  38. logger = logging.get_logger(__name__) # pylint: disable=invalid-name
  39. # This is the minimal required version to support some ONNX Runtime features
  40. ORT_QUANTIZE_MINIMUM_VERSION = parse("1.4.0")
  41. def check_onnxruntime_requirements(minimum_version: Version):
  42. """
  43. Check onnxruntime is installed and if the installed version match is recent enough
  44. Raises:
  45. ImportError: If onnxruntime is not installed or too old version is found
  46. """
  47. try:
  48. import onnxruntime
  49. # Parse the version of the installed onnxruntime
  50. ort_version = parse(onnxruntime.__version__)
  51. # We require 1.4.0 minimum
  52. if ort_version < ORT_QUANTIZE_MINIMUM_VERSION:
  53. raise ImportError(
  54. f"We found an older version of onnxruntime ({onnxruntime.__version__}) "
  55. f"but we require onnxruntime to be >= {minimum_version} to enable all the conversions options.\n"
  56. "Please update onnxruntime by running `pip install --upgrade onnxruntime`"
  57. )
  58. except ImportError:
  59. raise ImportError(
  60. "onnxruntime doesn't seem to be currently installed. "
  61. "Please install the onnxruntime by running `pip install onnxruntime`"
  62. " and relaunch the conversion."
  63. )
  64. def export_pytorch(
  65. preprocessor: Union["PreTrainedTokenizer", "FeatureExtractionMixin", "ProcessorMixin"],
  66. model: "PreTrainedModel",
  67. config: OnnxConfig,
  68. opset: int,
  69. output: Path,
  70. tokenizer: Optional["PreTrainedTokenizer"] = None,
  71. device: str = "cpu",
  72. ) -> tuple[list[str], list[str]]:
  73. """
  74. Export a PyTorch model to an ONNX Intermediate Representation (IR)
  75. Args:
  76. preprocessor: ([`PreTrainedTokenizer`], [`FeatureExtractionMixin`] or [`ProcessorMixin`]):
  77. The preprocessor used for encoding the data.
  78. model ([`PreTrainedModel`]):
  79. The model to export.
  80. config ([`~onnx.config.OnnxConfig`]):
  81. The ONNX configuration associated with the exported model.
  82. opset (`int`):
  83. The version of the ONNX operator set to use.
  84. output (`Path`):
  85. Directory to store the exported ONNX model.
  86. device (`str`, *optional*, defaults to `cpu`):
  87. The device on which the ONNX model will be exported. Either `cpu` or `cuda`.
  88. Returns:
  89. `tuple[list[str], list[str]]`: A tuple with an ordered list of the model's inputs, and the named inputs from
  90. the ONNX configuration.
  91. """
  92. if isinstance(preprocessor, PreTrainedTokenizerBase) and tokenizer is not None:
  93. raise ValueError("You cannot provide both a tokenizer and a preprocessor to export the model.")
  94. if tokenizer is not None:
  95. warnings.warn(
  96. "The `tokenizer` argument is deprecated and will be removed in version 5 of Transformers. Use"
  97. " `preprocessor` instead.",
  98. FutureWarning,
  99. )
  100. logger.info("Overwriting the `preprocessor` argument with `tokenizer` to generate dummy inputs.")
  101. preprocessor = tokenizer
  102. if issubclass(type(model), PreTrainedModel):
  103. import torch
  104. from torch.onnx import export as onnx_export
  105. logger.info(f"Using framework PyTorch: {torch.__version__}")
  106. with torch.no_grad():
  107. model.config.return_dict = True
  108. model.eval()
  109. # Check if we need to override certain configuration item
  110. if config.values_override is not None:
  111. logger.info(f"Overriding {len(config.values_override)} configuration item(s)")
  112. for override_config_key, override_config_value in config.values_override.items():
  113. logger.info(f"\t- {override_config_key} -> {override_config_value}")
  114. setattr(model.config, override_config_key, override_config_value)
  115. # Ensure inputs match
  116. # TODO: Check when exporting QA we provide "is_pair=True"
  117. model_inputs = config.generate_dummy_inputs(preprocessor, framework=TensorType.PYTORCH)
  118. device = torch.device(device)
  119. if device.type == "cuda" and torch.cuda.is_available():
  120. model.to(device)
  121. model_inputs_device = {}
  122. for k, v in model_inputs.items():
  123. if isinstance(v, tuple):
  124. model_inputs_device[k] = tuple(
  125. x.to(device) if isinstance(x, torch.Tensor) else None for x in v
  126. )
  127. elif isinstance(v, list):
  128. model_inputs_device[k] = [
  129. tuple(x.to(device) if isinstance(x, torch.Tensor) else None for x in t) for t in v
  130. ]
  131. else:
  132. model_inputs_device[k] = v.to(device)
  133. model_inputs = model_inputs_device
  134. inputs_match, matched_inputs = ensure_model_and_config_inputs_match(model, model_inputs.keys())
  135. onnx_outputs = list(config.outputs.keys())
  136. if not inputs_match:
  137. raise ValueError("Model and config inputs doesn't match")
  138. config.patch_ops()
  139. onnx_export(
  140. model,
  141. (model_inputs,),
  142. f=output.as_posix(),
  143. input_names=list(config.inputs.keys()),
  144. output_names=onnx_outputs,
  145. dynamic_axes=dict(chain(config.inputs.items(), config.outputs.items())),
  146. do_constant_folding=True,
  147. opset_version=opset,
  148. )
  149. config.restore_ops()
  150. return matched_inputs, onnx_outputs
  151. def export_tensorflow(
  152. preprocessor: Union["PreTrainedTokenizer", "FeatureExtractionMixin"],
  153. model: "TFPreTrainedModel",
  154. config: OnnxConfig,
  155. opset: int,
  156. output: Path,
  157. tokenizer: Optional["PreTrainedTokenizer"] = None,
  158. ) -> tuple[list[str], list[str]]:
  159. """
  160. Export a TensorFlow model to an ONNX Intermediate Representation (IR)
  161. Args:
  162. preprocessor: ([`PreTrainedTokenizer`] or [`FeatureExtractionMixin`]):
  163. The preprocessor used for encoding the data.
  164. model ([`TFPreTrainedModel`]):
  165. The model to export.
  166. config ([`~onnx.config.OnnxConfig`]):
  167. The ONNX configuration associated with the exported model.
  168. opset (`int`):
  169. The version of the ONNX operator set to use.
  170. output (`Path`):
  171. Directory to store the exported ONNX model.
  172. Returns:
  173. `tuple[list[str], list[str]]`: A tuple with an ordered list of the model's inputs, and the named inputs from
  174. the ONNX configuration.
  175. """
  176. import onnx
  177. import tensorflow as tf
  178. import tf2onnx
  179. if isinstance(preprocessor, PreTrainedTokenizerBase) and tokenizer is not None:
  180. raise ValueError("You cannot provide both a tokenizer and preprocessor to export the model.")
  181. if tokenizer is not None:
  182. warnings.warn(
  183. "The `tokenizer` argument is deprecated and will be removed in version 5 of Transformers. Use"
  184. " `preprocessor` instead.",
  185. FutureWarning,
  186. )
  187. logger.info("Overwriting the `preprocessor` argument with `tokenizer` to generate dummy inputs.")
  188. preprocessor = tokenizer
  189. model.config.return_dict = True
  190. # Check if we need to override certain configuration item
  191. if config.values_override is not None:
  192. logger.info(f"Overriding {len(config.values_override)} configuration item(s)")
  193. for override_config_key, override_config_value in config.values_override.items():
  194. logger.info(f"\t- {override_config_key} -> {override_config_value}")
  195. setattr(model.config, override_config_key, override_config_value)
  196. # Ensure inputs match
  197. model_inputs = config.generate_dummy_inputs(preprocessor, framework=TensorType.TENSORFLOW)
  198. inputs_match, matched_inputs = ensure_model_and_config_inputs_match(model, model_inputs.keys())
  199. onnx_outputs = list(config.outputs.keys())
  200. input_signature = [
  201. tf.TensorSpec([None] * tensor.ndim, dtype=tensor.dtype, name=key) for key, tensor in model_inputs.items()
  202. ]
  203. onnx_model, _ = tf2onnx.convert.from_keras(model, input_signature, opset=opset)
  204. onnx.save(onnx_model, output.as_posix())
  205. config.restore_ops()
  206. return matched_inputs, onnx_outputs
  207. def export(
  208. preprocessor: Union["PreTrainedTokenizer", "FeatureExtractionMixin", "ProcessorMixin"],
  209. model: Union["PreTrainedModel", "TFPreTrainedModel"],
  210. config: OnnxConfig,
  211. opset: int,
  212. output: Path,
  213. tokenizer: Optional["PreTrainedTokenizer"] = None,
  214. device: str = "cpu",
  215. ) -> tuple[list[str], list[str]]:
  216. """
  217. Export a Pytorch or TensorFlow model to an ONNX Intermediate Representation (IR)
  218. Args:
  219. preprocessor: ([`PreTrainedTokenizer`], [`FeatureExtractionMixin`] or [`ProcessorMixin`]):
  220. The preprocessor used for encoding the data.
  221. model ([`PreTrainedModel`] or [`TFPreTrainedModel`]):
  222. The model to export.
  223. config ([`~onnx.config.OnnxConfig`]):
  224. The ONNX configuration associated with the exported model.
  225. opset (`int`):
  226. The version of the ONNX operator set to use.
  227. output (`Path`):
  228. Directory to store the exported ONNX model.
  229. device (`str`, *optional*, defaults to `cpu`):
  230. The device on which the ONNX model will be exported. Either `cpu` or `cuda`. Only PyTorch is supported for
  231. export on CUDA devices.
  232. Returns:
  233. `tuple[list[str], list[str]]`: A tuple with an ordered list of the model's inputs, and the named inputs from
  234. the ONNX configuration.
  235. """
  236. if not (is_torch_available() or is_tf_available()):
  237. raise ImportError(
  238. "Cannot convert because neither PyTorch nor TensorFlow are not installed. "
  239. "Please install torch or tensorflow first."
  240. )
  241. if is_tf_available() and isinstance(model, TFPreTrainedModel) and device == "cuda":
  242. raise RuntimeError("`tf2onnx` does not support export on CUDA device.")
  243. if isinstance(preprocessor, PreTrainedTokenizerBase) and tokenizer is not None:
  244. raise ValueError("You cannot provide both a tokenizer and a preprocessor to export the model.")
  245. if tokenizer is not None:
  246. warnings.warn(
  247. "The `tokenizer` argument is deprecated and will be removed in version 5 of Transformers. Use"
  248. " `preprocessor` instead.",
  249. FutureWarning,
  250. )
  251. logger.info("Overwriting the `preprocessor` argument with `tokenizer` to generate dummy inputs.")
  252. preprocessor = tokenizer
  253. if is_torch_available():
  254. from ..utils import get_torch_version
  255. if not config.is_torch_support_available:
  256. logger.warning(
  257. f"Unsupported PyTorch version for this model. Minimum required is {config.torch_onnx_minimum_version},"
  258. f" got: {get_torch_version()}"
  259. )
  260. if is_torch_available() and issubclass(type(model), PreTrainedModel):
  261. return export_pytorch(preprocessor, model, config, opset, output, tokenizer=tokenizer, device=device)
  262. elif is_tf_available() and issubclass(type(model), TFPreTrainedModel):
  263. return export_tensorflow(preprocessor, model, config, opset, output, tokenizer=tokenizer)
  264. def validate_model_outputs(
  265. config: OnnxConfig,
  266. preprocessor: Union["PreTrainedTokenizer", "FeatureExtractionMixin", "ProcessorMixin"],
  267. reference_model: Union["PreTrainedModel", "TFPreTrainedModel"],
  268. onnx_model: Path,
  269. onnx_named_outputs: list[str],
  270. atol: float,
  271. tokenizer: Optional["PreTrainedTokenizer"] = None,
  272. ):
  273. from onnxruntime import InferenceSession, SessionOptions
  274. logger.info("Validating ONNX model...")
  275. if isinstance(preprocessor, PreTrainedTokenizerBase) and tokenizer is not None:
  276. raise ValueError("You cannot provide both a tokenizer and a preprocessor to validate the model outputs.")
  277. if tokenizer is not None:
  278. warnings.warn(
  279. "The `tokenizer` argument is deprecated and will be removed in version 5 of Transformers. Use"
  280. " `preprocessor` instead.",
  281. FutureWarning,
  282. )
  283. logger.info("Overwriting the `preprocessor` argument with `tokenizer` to generate dummy inputs.")
  284. preprocessor = tokenizer
  285. # generate inputs with a different batch_size and seq_len that was used for conversion to properly test
  286. # dynamic input shapes.
  287. if is_torch_available() and issubclass(type(reference_model), PreTrainedModel):
  288. reference_model_inputs = config.generate_dummy_inputs(
  289. preprocessor,
  290. batch_size=config.default_fixed_batch + 1,
  291. seq_length=config.default_fixed_sequence + 1,
  292. framework=TensorType.PYTORCH,
  293. )
  294. else:
  295. reference_model_inputs = config.generate_dummy_inputs(
  296. preprocessor,
  297. batch_size=config.default_fixed_batch + 1,
  298. seq_length=config.default_fixed_sequence + 1,
  299. framework=TensorType.TENSORFLOW,
  300. )
  301. # Create ONNX Runtime session
  302. options = SessionOptions()
  303. session = InferenceSession(onnx_model.as_posix(), options, providers=["CPUExecutionProvider"])
  304. # Compute outputs from the reference model
  305. if is_torch_available() and issubclass(type(reference_model), PreTrainedModel):
  306. reference_model.to("cpu")
  307. ref_outputs = reference_model(**reference_model_inputs)
  308. ref_outputs_dict = {}
  309. # We flatten potential collection of outputs (i.e. past_keys) to a flat structure
  310. for name, value in ref_outputs.items():
  311. # Overwriting the output name as "present" since it is the name used for the ONNX outputs
  312. # ("past_key_values" being taken for the ONNX inputs)
  313. if name == "past_key_values":
  314. name = "present"
  315. if isinstance(value, (list, tuple)):
  316. value = config.flatten_output_collection_property(name, value)
  317. ref_outputs_dict.update(value)
  318. else:
  319. ref_outputs_dict[name] = value
  320. # Create onnxruntime inputs from the reference model inputs
  321. reference_model_inputs_onnxruntime = config.generate_dummy_inputs_onnxruntime(reference_model_inputs)
  322. # We flatten potential collection of inputs (i.e. past_keys)
  323. onnx_inputs = {}
  324. for name, value in reference_model_inputs_onnxruntime.items():
  325. if isinstance(value, (list, tuple)):
  326. value = config.flatten_output_collection_property(name, value)
  327. onnx_inputs.update({tensor_name: pt_tensor.numpy() for tensor_name, pt_tensor in value.items()})
  328. else:
  329. onnx_inputs[name] = value.numpy()
  330. # Compute outputs from the ONNX model
  331. onnx_outputs = session.run(onnx_named_outputs, onnx_inputs)
  332. # Check we have a subset of the keys into onnx_outputs against ref_outputs
  333. ref_outputs_set, onnx_outputs_set = set(ref_outputs_dict.keys()), set(onnx_named_outputs)
  334. if not onnx_outputs_set.issubset(ref_outputs_set):
  335. logger.info(
  336. f"\t-[x] ONNX model output names {onnx_outputs_set} do not match reference model {ref_outputs_set}"
  337. )
  338. raise ValueError(
  339. "Outputs doesn't match between reference model and ONNX exported model: "
  340. f"{onnx_outputs_set.difference(ref_outputs_set)}"
  341. )
  342. else:
  343. logger.info(f"\t-[✓] ONNX model output names match reference model ({onnx_outputs_set})")
  344. # Check the shape and values match
  345. for name, ort_value in zip(onnx_named_outputs, onnx_outputs):
  346. if is_torch_available() and issubclass(type(reference_model), PreTrainedModel):
  347. ref_value = ref_outputs_dict[name].detach().numpy()
  348. else:
  349. ref_value = ref_outputs_dict[name].numpy()
  350. logger.info(f'\t- Validating ONNX Model output "{name}":')
  351. # Shape
  352. if ort_value.shape != ref_value.shape:
  353. logger.info(f"\t\t-[x] shape {ort_value.shape} doesn't match {ref_value.shape}")
  354. raise ValueError(
  355. "Outputs shape doesn't match between reference model and ONNX exported model: "
  356. f"Got {ref_value.shape} (reference) and {ort_value.shape} (ONNX)"
  357. )
  358. else:
  359. logger.info(f"\t\t-[✓] {ort_value.shape} matches {ref_value.shape}")
  360. # Values
  361. if not np.allclose(ref_value, ort_value, atol=atol):
  362. bad_indices = np.logical_not(np.isclose(ref_value, ort_value, atol=atol))
  363. logger.info(f"\t\t-[x] values not close enough (atol: {atol})")
  364. raise ValueError(
  365. "Outputs values doesn't match between reference model and ONNX exported model: "
  366. f"Got max absolute difference of: {np.amax(np.abs(ref_value - ort_value))} for "
  367. f"{ref_value[bad_indices]} vs {ort_value[bad_indices]}"
  368. )
  369. else:
  370. logger.info(f"\t\t-[✓] all values close (atol: {atol})")
  371. def ensure_model_and_config_inputs_match(
  372. model: Union["PreTrainedModel", "TFPreTrainedModel"], model_inputs: Iterable[str]
  373. ) -> tuple[bool, list[str]]:
  374. """
  375. :param model_inputs: :param config_inputs: :return:
  376. """
  377. if is_torch_available() and issubclass(type(model), PreTrainedModel):
  378. forward_parameters = signature(model.forward).parameters
  379. else:
  380. forward_parameters = signature(model.call).parameters
  381. model_inputs_set = set(model_inputs)
  382. # We are fine if config_inputs has more keys than model_inputs
  383. forward_inputs_set = set(forward_parameters.keys())
  384. is_ok = model_inputs_set.issubset(forward_inputs_set)
  385. # Make sure the input order match (VERY IMPORTANT !!!!)
  386. matching_inputs = forward_inputs_set.intersection(model_inputs_set)
  387. ordered_inputs = [parameter for parameter in forward_parameters if parameter in matching_inputs]
  388. return is_ok, ordered_inputs