convert_graph_to_onnx.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551
  1. # Copyright 2020 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 argparse import ArgumentParser
  16. from os import listdir, makedirs
  17. from pathlib import Path
  18. from typing import Optional
  19. from packaging.version import Version, parse
  20. from transformers.pipelines import Pipeline, pipeline
  21. from transformers.tokenization_utils import BatchEncoding
  22. from transformers.utils import ModelOutput, is_tf_available, is_torch_available
  23. # This is the minimal required version to
  24. # support some ONNX Runtime features
  25. ORT_QUANTIZE_MINIMUM_VERSION = parse("1.4.0")
  26. SUPPORTED_PIPELINES = [
  27. "feature-extraction",
  28. "ner",
  29. "sentiment-analysis",
  30. "fill-mask",
  31. "question-answering",
  32. "text-generation",
  33. "translation_en_to_fr",
  34. "translation_en_to_de",
  35. "translation_en_to_ro",
  36. ]
  37. class OnnxConverterArgumentParser(ArgumentParser):
  38. """
  39. Wraps all the script arguments supported to export transformers models to ONNX IR
  40. """
  41. def __init__(self):
  42. super().__init__("ONNX Converter")
  43. self.add_argument(
  44. "--pipeline",
  45. type=str,
  46. choices=SUPPORTED_PIPELINES,
  47. default="feature-extraction",
  48. )
  49. self.add_argument(
  50. "--model",
  51. type=str,
  52. required=True,
  53. help="Model's id or path (ex: google-bert/bert-base-cased)",
  54. )
  55. self.add_argument("--tokenizer", type=str, help="Tokenizer's id or path (ex: google-bert/bert-base-cased)")
  56. self.add_argument(
  57. "--framework",
  58. type=str,
  59. choices=["pt", "tf"],
  60. help="Framework for loading the model",
  61. )
  62. self.add_argument("--opset", type=int, default=11, help="ONNX opset to use")
  63. self.add_argument(
  64. "--check-loading",
  65. action="store_true",
  66. help="Check ONNX is able to load the model",
  67. )
  68. self.add_argument(
  69. "--use-external-format",
  70. action="store_true",
  71. help="Allow exporting model >= than 2Gb",
  72. )
  73. self.add_argument(
  74. "--quantize",
  75. action="store_true",
  76. help="Quantize the neural network to be run with int8",
  77. )
  78. self.add_argument("output")
  79. def generate_identified_filename(filename: Path, identifier: str) -> Path:
  80. """
  81. Append a string-identifier at the end (before the extension, if any) to the provided filepath
  82. Args:
  83. filename: pathlib.Path The actual path object we would like to add an identifier suffix
  84. identifier: The suffix to add
  85. Returns: String with concatenated identifier at the end of the filename
  86. """
  87. return filename.parent.joinpath(filename.stem + identifier).with_suffix(filename.suffix)
  88. def check_onnxruntime_requirements(minimum_version: Version):
  89. """
  90. Check onnxruntime is installed and if the installed version match is recent enough
  91. Raises:
  92. ImportError: If onnxruntime is not installed or too old version is found
  93. """
  94. try:
  95. import onnxruntime
  96. # Parse the version of the installed onnxruntime
  97. ort_version = parse(onnxruntime.__version__)
  98. # We require 1.4.0 minimum
  99. if ort_version < ORT_QUANTIZE_MINIMUM_VERSION:
  100. raise ImportError(
  101. f"We found an older version of onnxruntime ({onnxruntime.__version__}) "
  102. f"but we require onnxruntime to be >= {minimum_version} to enable all the conversions options.\n"
  103. "Please update onnxruntime by running `pip install --upgrade onnxruntime`"
  104. )
  105. except ImportError:
  106. raise ImportError(
  107. "onnxruntime doesn't seem to be currently installed. "
  108. "Please install the onnxruntime by running `pip install onnxruntime`"
  109. " and relaunch the conversion."
  110. )
  111. def ensure_valid_input(model, tokens, input_names):
  112. """
  113. Ensure inputs are presented in the correct order, without any Non
  114. Args:
  115. model: The model used to forward the input data
  116. tokens: BatchEncoding holding the input data
  117. input_names: The name of the inputs
  118. Returns: Tuple
  119. """
  120. print("Ensuring inputs are in correct order")
  121. model_args_name = model.forward.__code__.co_varnames
  122. model_args, ordered_input_names = [], []
  123. for arg_name in model_args_name[1:]: # start at index 1 to skip "self" argument
  124. if arg_name in input_names:
  125. ordered_input_names.append(arg_name)
  126. model_args.append(tokens[arg_name])
  127. else:
  128. print(f"{arg_name} is not present in the generated input list.")
  129. break
  130. print(f"Generated inputs order: {ordered_input_names}")
  131. return ordered_input_names, tuple(model_args)
  132. def infer_shapes(nlp: Pipeline, framework: str) -> tuple[list[str], list[str], dict, BatchEncoding]:
  133. """
  134. Attempt to infer the static vs dynamic axes for each input and output tensors for a specific model
  135. Args:
  136. nlp: The pipeline object holding the model to be exported
  137. framework: The framework identifier to dispatch to the correct inference scheme (pt/tf)
  138. Returns:
  139. - List of the inferred input variable names
  140. - List of the inferred output variable names
  141. - Dictionary with input/output variables names as key and shape tensor as value
  142. - a BatchEncoding reference which was used to infer all the above information
  143. """
  144. def build_shape_dict(name: str, tensor, is_input: bool, seq_len: int):
  145. if isinstance(tensor, (tuple, list)):
  146. return [build_shape_dict(name, t, is_input, seq_len) for t in tensor]
  147. else:
  148. # Let's assume batch is the first axis with only 1 element (~~ might not be always true ...)
  149. axes = {[axis for axis, numel in enumerate(tensor.shape) if numel == 1][0]: "batch"}
  150. if is_input:
  151. if len(tensor.shape) == 2:
  152. axes[1] = "sequence"
  153. else:
  154. raise ValueError(f"Unable to infer tensor axes ({len(tensor.shape)})")
  155. else:
  156. seq_axes = [dim for dim, shape in enumerate(tensor.shape) if shape == seq_len]
  157. axes.update(dict.fromkeys(seq_axes, "sequence"))
  158. print(f"Found {'input' if is_input else 'output'} {name} with shape: {axes}")
  159. return axes
  160. tokens = nlp.tokenizer("This is a sample output", return_tensors=framework)
  161. seq_len = tokens.input_ids.shape[-1]
  162. outputs = nlp.model(**tokens) if framework == "pt" else nlp.model(tokens)
  163. if isinstance(outputs, ModelOutput):
  164. outputs = outputs.to_tuple()
  165. if not isinstance(outputs, (list, tuple)):
  166. outputs = (outputs,)
  167. # Generate input names & axes
  168. input_vars = list(tokens.keys())
  169. input_dynamic_axes = {k: build_shape_dict(k, v, True, seq_len) for k, v in tokens.items()}
  170. # flatten potentially grouped outputs (past for gpt2, attentions)
  171. outputs_flat = []
  172. for output in outputs:
  173. if isinstance(output, (tuple, list)):
  174. outputs_flat.extend(output)
  175. else:
  176. outputs_flat.append(output)
  177. # Generate output names & axes
  178. output_names = [f"output_{i}" for i in range(len(outputs_flat))]
  179. output_dynamic_axes = {k: build_shape_dict(k, v, False, seq_len) for k, v in zip(output_names, outputs_flat)}
  180. # Create the aggregated axes representation
  181. dynamic_axes = dict(input_dynamic_axes, **output_dynamic_axes)
  182. return input_vars, output_names, dynamic_axes, tokens
  183. def load_graph_from_args(
  184. pipeline_name: str, framework: str, model: str, tokenizer: Optional[str] = None, **models_kwargs
  185. ) -> Pipeline:
  186. """
  187. Convert the set of arguments provided through the CLI to an actual pipeline reference (tokenizer + model
  188. Args:
  189. pipeline_name: The kind of pipeline to use (ner, question-answering, etc.)
  190. framework: The actual model to convert the pipeline from ("pt" or "tf")
  191. model: The model name which will be loaded by the pipeline
  192. tokenizer: The tokenizer name which will be loaded by the pipeline, default to the model's value
  193. Returns: Pipeline object
  194. """
  195. # If no tokenizer provided
  196. if tokenizer is None:
  197. tokenizer = model
  198. # Check the wanted framework is available
  199. if framework == "pt" and not is_torch_available():
  200. raise Exception("Cannot convert because PyTorch is not installed. Please install torch first.")
  201. if framework == "tf" and not is_tf_available():
  202. raise Exception("Cannot convert because TF is not installed. Please install tensorflow first.")
  203. print(f"Loading pipeline (model: {model}, tokenizer: {tokenizer})")
  204. # Allocate tokenizer and model
  205. return pipeline(pipeline_name, model=model, tokenizer=tokenizer, framework=framework, model_kwargs=models_kwargs)
  206. def convert_pytorch(nlp: Pipeline, opset: int, output: Path, use_external_format: bool):
  207. """
  208. Export a PyTorch backed pipeline to ONNX Intermediate Representation (IR
  209. Args:
  210. nlp: The pipeline to be exported
  211. opset: The actual version of the ONNX operator set to use
  212. output: Path where will be stored the generated ONNX model
  213. use_external_format: Split the model definition from its parameters to allow model bigger than 2GB
  214. Returns:
  215. """
  216. if not is_torch_available():
  217. raise Exception("Cannot convert because PyTorch is not installed. Please install torch first.")
  218. import torch
  219. from torch.onnx import export
  220. print(f"Using framework PyTorch: {torch.__version__}")
  221. with torch.no_grad():
  222. input_names, output_names, dynamic_axes, tokens = infer_shapes(nlp, "pt")
  223. ordered_input_names, model_args = ensure_valid_input(nlp.model, tokens, input_names)
  224. export(
  225. nlp.model,
  226. model_args,
  227. f=output.as_posix(),
  228. input_names=ordered_input_names,
  229. output_names=output_names,
  230. dynamic_axes=dynamic_axes,
  231. do_constant_folding=True,
  232. opset_version=opset,
  233. )
  234. def convert_tensorflow(nlp: Pipeline, opset: int, output: Path):
  235. """
  236. Export a TensorFlow backed pipeline to ONNX Intermediate Representation (IR)
  237. Args:
  238. nlp: The pipeline to be exported
  239. opset: The actual version of the ONNX operator set to use
  240. output: Path where will be stored the generated ONNX model
  241. Notes: TensorFlow cannot export model bigger than 2GB due to internal constraint from TensorFlow
  242. """
  243. if not is_tf_available():
  244. raise Exception("Cannot convert because TF is not installed. Please install tensorflow first.")
  245. print("/!\\ Please note TensorFlow doesn't support exporting model > 2Gb /!\\")
  246. try:
  247. import tensorflow as tf
  248. import tf2onnx
  249. from tf2onnx import __version__ as t2ov
  250. print(f"Using framework TensorFlow: {tf.version.VERSION}, tf2onnx: {t2ov}")
  251. # Build
  252. input_names, output_names, dynamic_axes, tokens = infer_shapes(nlp, "tf")
  253. # Forward
  254. nlp.model.predict(tokens.data)
  255. input_signature = [tf.TensorSpec.from_tensor(tensor, name=key) for key, tensor in tokens.items()]
  256. model_proto, _ = tf2onnx.convert.from_keras(
  257. nlp.model, input_signature, opset=opset, output_path=output.as_posix()
  258. )
  259. except ImportError as e:
  260. raise Exception(
  261. f"Cannot import {e.name} required to convert TF model to ONNX. Please install {e.name} first. {e}"
  262. )
  263. def convert(
  264. framework: str,
  265. model: str,
  266. output: Path,
  267. opset: int,
  268. tokenizer: Optional[str] = None,
  269. use_external_format: bool = False,
  270. pipeline_name: str = "feature-extraction",
  271. **model_kwargs,
  272. ):
  273. """
  274. Convert the pipeline object to the ONNX Intermediate Representation (IR) format
  275. Args:
  276. framework: The framework the pipeline is backed by ("pt" or "tf")
  277. model: The name of the model to load for the pipeline
  278. output: The path where the ONNX graph will be stored
  279. opset: The actual version of the ONNX operator set to use
  280. tokenizer: The name of the model to load for the pipeline, default to the model's name if not provided
  281. use_external_format:
  282. Split the model definition from its parameters to allow model bigger than 2GB (PyTorch only)
  283. pipeline_name: The kind of pipeline to instantiate (ner, question-answering, etc.)
  284. model_kwargs: Keyword arguments to be forwarded to the model constructor
  285. Returns:
  286. """
  287. warnings.warn(
  288. "The `transformers.convert_graph_to_onnx` package is deprecated and will be removed in version 5 of"
  289. " Transformers",
  290. FutureWarning,
  291. )
  292. print(f"ONNX opset version set to: {opset}")
  293. # Load the pipeline
  294. nlp = load_graph_from_args(pipeline_name, framework, model, tokenizer, **model_kwargs)
  295. if not output.parent.exists():
  296. print(f"Creating folder {output.parent}")
  297. makedirs(output.parent.as_posix())
  298. elif len(listdir(output.parent.as_posix())) > 0:
  299. raise Exception(f"Folder {output.parent.as_posix()} is not empty, aborting conversion")
  300. # Export the graph
  301. if framework == "pt":
  302. convert_pytorch(nlp, opset, output, use_external_format)
  303. else:
  304. convert_tensorflow(nlp, opset, output)
  305. def optimize(onnx_model_path: Path) -> Path:
  306. """
  307. Load the model at the specified path and let onnxruntime look at transformations on the graph to enable all the
  308. optimizations possible
  309. Args:
  310. onnx_model_path: filepath where the model binary description is stored
  311. Returns: Path where the optimized model binary description has been saved
  312. """
  313. from onnxruntime import InferenceSession, SessionOptions
  314. # Generate model name with suffix "optimized"
  315. opt_model_path = generate_identified_filename(onnx_model_path, "-optimized")
  316. sess_option = SessionOptions()
  317. sess_option.optimized_model_filepath = opt_model_path.as_posix()
  318. _ = InferenceSession(onnx_model_path.as_posix(), sess_option)
  319. print(f"Optimized model has been written at {opt_model_path}: \N{HEAVY CHECK MARK}")
  320. print("/!\\ Optimized model contains hardware specific operators which might not be portable. /!\\")
  321. return opt_model_path
  322. def quantize(onnx_model_path: Path) -> Path:
  323. """
  324. Quantize the weights of the model from float32 to in8 to allow very efficient inference on modern CPU
  325. Args:
  326. onnx_model_path: Path to location the exported ONNX model is stored
  327. Returns: The Path generated for the quantized
  328. """
  329. import onnx
  330. import onnxruntime
  331. from onnx.onnx_pb import ModelProto
  332. from onnxruntime.quantization import QuantizationMode
  333. from onnxruntime.quantization.onnx_quantizer import ONNXQuantizer
  334. from onnxruntime.quantization.registry import IntegerOpsRegistry
  335. # Load the ONNX model
  336. onnx_model = onnx.load(onnx_model_path.as_posix())
  337. if parse(onnx.__version__) < parse("1.5.0"):
  338. print(
  339. "Models larger than 2GB will fail to quantize due to protobuf constraint.\n"
  340. "Please upgrade to onnxruntime >= 1.5.0."
  341. )
  342. # Copy it
  343. copy_model = ModelProto()
  344. copy_model.CopyFrom(onnx_model)
  345. # Construct quantizer
  346. # onnxruntime renamed input_qType to activation_qType in v1.13.1, so we
  347. # check the onnxruntime version to ensure backward compatibility.
  348. # See also: https://github.com/microsoft/onnxruntime/pull/12873
  349. if parse(onnxruntime.__version__) < parse("1.13.1"):
  350. quantizer = ONNXQuantizer(
  351. model=copy_model,
  352. per_channel=False,
  353. reduce_range=False,
  354. mode=QuantizationMode.IntegerOps,
  355. static=False,
  356. weight_qType=True,
  357. input_qType=False,
  358. tensors_range=None,
  359. nodes_to_quantize=None,
  360. nodes_to_exclude=None,
  361. op_types_to_quantize=list(IntegerOpsRegistry),
  362. )
  363. else:
  364. quantizer = ONNXQuantizer(
  365. model=copy_model,
  366. per_channel=False,
  367. reduce_range=False,
  368. mode=QuantizationMode.IntegerOps,
  369. static=False,
  370. weight_qType=True,
  371. activation_qType=False,
  372. tensors_range=None,
  373. nodes_to_quantize=None,
  374. nodes_to_exclude=None,
  375. op_types_to_quantize=list(IntegerOpsRegistry),
  376. )
  377. # Quantize and export
  378. quantizer.quantize_model()
  379. # Append "-quantized" at the end of the model's name
  380. quantized_model_path = generate_identified_filename(onnx_model_path, "-quantized")
  381. # Save model
  382. print(f"Quantized model has been written at {quantized_model_path}: \N{HEAVY CHECK MARK}")
  383. onnx.save_model(quantizer.model.model, quantized_model_path.as_posix())
  384. return quantized_model_path
  385. def verify(path: Path):
  386. from onnxruntime import InferenceSession, SessionOptions
  387. from onnxruntime.capi.onnxruntime_pybind11_state import RuntimeException
  388. print(f"Checking ONNX model loading from: {path} ...")
  389. try:
  390. onnx_options = SessionOptions()
  391. _ = InferenceSession(path.as_posix(), onnx_options, providers=["CPUExecutionProvider"])
  392. print(f"Model {path} correctly loaded: \N{HEAVY CHECK MARK}")
  393. except RuntimeException as re:
  394. print(f"Error while loading the model {re}: \N{HEAVY BALLOT X}")
  395. if __name__ == "__main__":
  396. parser = OnnxConverterArgumentParser()
  397. args = parser.parse_args()
  398. # Make sure output is absolute path
  399. args.output = Path(args.output).absolute()
  400. try:
  401. print("\n====== Converting model to ONNX ======")
  402. # Convert
  403. convert(
  404. args.framework,
  405. args.model,
  406. args.output,
  407. args.opset,
  408. args.tokenizer,
  409. args.use_external_format,
  410. args.pipeline,
  411. )
  412. if args.quantize:
  413. # Ensure requirements for quantization on onnxruntime is met
  414. check_onnxruntime_requirements(ORT_QUANTIZE_MINIMUM_VERSION)
  415. # onnxruntime optimizations doesn't provide the same level of performances on TensorFlow than PyTorch
  416. if args.framework == "tf":
  417. print(
  418. "\t Using TensorFlow might not provide the same optimization level compared to PyTorch.\n"
  419. "\t For TensorFlow users you can try optimizing the model directly through onnxruntime_tools.\n"
  420. "\t For more information, please refer to the onnxruntime documentation:\n"
  421. "\t\thttps://github.com/microsoft/onnxruntime/tree/master/onnxruntime/python/tools/transformers\n"
  422. )
  423. print("\n====== Optimizing ONNX model ======")
  424. # Quantization works best when using the optimized version of the model
  425. args.optimized_output = optimize(args.output)
  426. # Do the quantization on the right graph
  427. args.quantized_output = quantize(args.optimized_output)
  428. # And verify
  429. if args.check_loading:
  430. print("\n====== Check exported ONNX model(s) ======")
  431. verify(args.output)
  432. if hasattr(args, "optimized_output"):
  433. verify(args.optimized_output)
  434. if hasattr(args, "quantized_output"):
  435. verify(args.quantized_output)
  436. except Exception as e:
  437. print(f"Error while converting the model: {e}")
  438. exit(1)