__main__.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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 subprocess
  15. import sys
  16. import warnings
  17. from argparse import ArgumentParser
  18. from pathlib import Path
  19. from packaging import version
  20. from .. import AutoFeatureExtractor, AutoImageProcessor, AutoProcessor, AutoTokenizer
  21. from ..utils import logging
  22. from ..utils.import_utils import is_optimum_available
  23. from .convert import export, validate_model_outputs
  24. from .features import FeaturesManager
  25. from .utils import get_preprocessor
  26. MIN_OPTIMUM_VERSION = "1.5.0"
  27. ENCODER_DECODER_MODELS = ["vision-encoder-decoder"]
  28. def export_with_optimum(args):
  29. if is_optimum_available():
  30. from optimum.version import __version__ as optimum_version
  31. parsed_optimum_version = version.parse(optimum_version)
  32. if parsed_optimum_version < version.parse(MIN_OPTIMUM_VERSION):
  33. raise RuntimeError(
  34. f"transformers.onnx requires optimum >= {MIN_OPTIMUM_VERSION} but {optimum_version} is installed. You "
  35. "can upgrade optimum by running: pip install -U optimum[exporters]"
  36. )
  37. else:
  38. raise RuntimeError(
  39. "transformers.onnx requires optimum to run, you can install the library by running: pip install "
  40. "optimum[exporters]"
  41. )
  42. cmd_line = [
  43. sys.executable,
  44. "-m",
  45. "optimum.exporters.onnx",
  46. f"--model {args.model}",
  47. f"--task {args.feature}",
  48. f"--framework {args.framework}" if args.framework is not None else "",
  49. f"{args.output}",
  50. ]
  51. proc = subprocess.Popen(cmd_line, stdout=subprocess.PIPE)
  52. proc.wait()
  53. logger.info(
  54. "The export was done by optimum.exporters.onnx. We recommend using to use this package directly in future, as "
  55. "transformers.onnx is deprecated, and will be removed in v5. You can find more information here: "
  56. "https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model."
  57. )
  58. def export_with_transformers(args):
  59. args.output = args.output if args.output.is_file() else args.output.joinpath("model.onnx")
  60. if not args.output.parent.exists():
  61. args.output.parent.mkdir(parents=True)
  62. # Allocate the model
  63. model = FeaturesManager.get_model_from_feature(
  64. args.feature, args.model, framework=args.framework, cache_dir=args.cache_dir
  65. )
  66. model_kind, model_onnx_config = FeaturesManager.check_supported_model_or_raise(model, feature=args.feature)
  67. onnx_config = model_onnx_config(model.config)
  68. if model_kind in ENCODER_DECODER_MODELS:
  69. encoder_model = model.get_encoder()
  70. decoder_model = model.get_decoder()
  71. encoder_onnx_config = onnx_config.get_encoder_config(encoder_model.config)
  72. decoder_onnx_config = onnx_config.get_decoder_config(
  73. encoder_model.config, decoder_model.config, feature=args.feature
  74. )
  75. if args.opset is None:
  76. args.opset = max(encoder_onnx_config.default_onnx_opset, decoder_onnx_config.default_onnx_opset)
  77. if args.opset < min(encoder_onnx_config.default_onnx_opset, decoder_onnx_config.default_onnx_opset):
  78. raise ValueError(
  79. f"Opset {args.opset} is not sufficient to export {model_kind}. At least "
  80. f" {min(encoder_onnx_config.default_onnx_opset, decoder_onnx_config.default_onnx_opset)} is required."
  81. )
  82. preprocessor = AutoFeatureExtractor.from_pretrained(args.model)
  83. onnx_inputs, onnx_outputs = export(
  84. preprocessor,
  85. encoder_model,
  86. encoder_onnx_config,
  87. args.opset,
  88. args.output.parent.joinpath("encoder_model.onnx"),
  89. )
  90. validate_model_outputs(
  91. encoder_onnx_config,
  92. preprocessor,
  93. encoder_model,
  94. args.output.parent.joinpath("encoder_model.onnx"),
  95. onnx_outputs,
  96. args.atol if args.atol else encoder_onnx_config.atol_for_validation,
  97. )
  98. preprocessor = AutoTokenizer.from_pretrained(args.model)
  99. onnx_inputs, onnx_outputs = export(
  100. preprocessor,
  101. decoder_model,
  102. decoder_onnx_config,
  103. args.opset,
  104. args.output.parent.joinpath("decoder_model.onnx"),
  105. )
  106. validate_model_outputs(
  107. decoder_onnx_config,
  108. preprocessor,
  109. decoder_model,
  110. args.output.parent.joinpath("decoder_model.onnx"),
  111. onnx_outputs,
  112. args.atol if args.atol else decoder_onnx_config.atol_for_validation,
  113. )
  114. logger.info(
  115. f"All good, model saved at: {args.output.parent.joinpath('encoder_model.onnx').as_posix()},"
  116. f" {args.output.parent.joinpath('decoder_model.onnx').as_posix()}"
  117. )
  118. else:
  119. # Instantiate the appropriate preprocessor
  120. if args.preprocessor == "auto":
  121. preprocessor = get_preprocessor(args.model)
  122. elif args.preprocessor == "tokenizer":
  123. preprocessor = AutoTokenizer.from_pretrained(args.model)
  124. elif args.preprocessor == "image_processor":
  125. preprocessor = AutoImageProcessor.from_pretrained(args.model)
  126. elif args.preprocessor == "feature_extractor":
  127. preprocessor = AutoFeatureExtractor.from_pretrained(args.model)
  128. elif args.preprocessor == "processor":
  129. preprocessor = AutoProcessor.from_pretrained(args.model)
  130. else:
  131. raise ValueError(f"Unknown preprocessor type '{args.preprocessor}'")
  132. # Ensure the requested opset is sufficient
  133. if args.opset is None:
  134. args.opset = onnx_config.default_onnx_opset
  135. if args.opset < onnx_config.default_onnx_opset:
  136. raise ValueError(
  137. f"Opset {args.opset} is not sufficient to export {model_kind}. "
  138. f"At least {onnx_config.default_onnx_opset} is required."
  139. )
  140. onnx_inputs, onnx_outputs = export(
  141. preprocessor,
  142. model,
  143. onnx_config,
  144. args.opset,
  145. args.output,
  146. )
  147. if args.atol is None:
  148. args.atol = onnx_config.atol_for_validation
  149. validate_model_outputs(onnx_config, preprocessor, model, args.output, onnx_outputs, args.atol)
  150. logger.info(f"All good, model saved at: {args.output.as_posix()}")
  151. warnings.warn(
  152. "The export was done by transformers.onnx which is deprecated and will be removed in v5. We recommend"
  153. " using optimum.exporters.onnx in future. You can find more information here:"
  154. " https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model.",
  155. FutureWarning,
  156. )
  157. def main():
  158. parser = ArgumentParser("Hugging Face Transformers ONNX exporter")
  159. parser.add_argument(
  160. "-m", "--model", type=str, required=True, help="Model ID on huggingface.co or path on disk to load model from."
  161. )
  162. parser.add_argument(
  163. "--feature",
  164. default="default",
  165. help="The type of features to export the model with.",
  166. )
  167. parser.add_argument("--opset", type=int, default=None, help="ONNX opset version to export the model with.")
  168. parser.add_argument(
  169. "--atol", type=float, default=None, help="Absolute difference tolerance when validating the model."
  170. )
  171. parser.add_argument(
  172. "--framework",
  173. type=str,
  174. choices=["pt", "tf"],
  175. default=None,
  176. help=(
  177. "The framework to use for the ONNX export."
  178. " If not provided, will attempt to use the local checkpoint's original framework"
  179. " or what is available in the environment."
  180. ),
  181. )
  182. parser.add_argument("output", type=Path, help="Path indicating where to store generated ONNX model.")
  183. parser.add_argument("--cache_dir", type=str, default=None, help="Path indicating where to store cache.")
  184. parser.add_argument(
  185. "--preprocessor",
  186. type=str,
  187. choices=["auto", "tokenizer", "feature_extractor", "image_processor", "processor"],
  188. default="auto",
  189. help="Which type of preprocessor to use. 'auto' tries to automatically detect it.",
  190. )
  191. parser.add_argument(
  192. "--export_with_transformers",
  193. action="store_true",
  194. help=(
  195. "Whether to use transformers.onnx instead of optimum.exporters.onnx to perform the ONNX export. It can be "
  196. "useful when exporting a model supported in transformers but not in optimum, otherwise it is not "
  197. "recommended."
  198. ),
  199. )
  200. args = parser.parse_args()
  201. if args.export_with_transformers or not is_optimum_available():
  202. export_with_transformers(args)
  203. else:
  204. export_with_optimum(args)
  205. if __name__ == "__main__":
  206. logger = logging.get_logger("transformers.onnx") # pylint: disable=invalid-name
  207. logger.setLevel(logging.INFO)
  208. main()