

'''simple docstring'''



import subprocess
import sys
import warnings
from argparse import ArgumentParser
from pathlib import Path

from packaging import version

from .. import AutoFeatureExtractor, AutoImageProcessor, AutoProcessor, AutoTokenizer
from ..utils import logging
from ..utils.import_utils import is_optimum_available
from .convert import export, validate_model_outputs
from .features import FeaturesManager
from .utils import get_preprocessor


UpperCAmelCase				: int         =  """1.5.0"""

UpperCAmelCase				: Optional[Any]         =  ["""vision-encoder-decoder"""]







def      a__ (						a__		):




     """simple docstring"""


     if is_optimum_available():
          from optimum.version import __version__ as optimum_version

          __SCREAMING_SNAKE_CASE						     =   version.parse(a__		)
          if parsed_optimum_version < version.parse(a__		):
               raise RuntimeError(
                   F'transformers.onnx requires optimum >= {MIN_OPTIMUM_VERSION} but {optimum_version} is installed. You '
                   """can upgrade optimum by running: pip install -U optimum[exporters]"""		)
     else:
          raise RuntimeError(
              """transformers.onnx requires optimum to run, you can install the library by running: pip install """
              """optimum[exporters]"""		)
     __SCREAMING_SNAKE_CASE						     =   [
         sys.executable,
         "-m",
         "optimum.exporters.onnx",
         F'--model {args.model}',
         F'--task {args.feature}',
         F'--framework {args.framework}' if args.framework is not None else "",
         F'{args.output}',
     ]
     __SCREAMING_SNAKE_CASE						     =   subprocess.Popen(""" """.join(a__		)   ,					stdout=subprocess.PIPE   ,					shell=a__		)
     proc.wait()

     logger.info(
         """The export was done by optimum.exporters.onnx. We recommend using to use this package directly in future, as """
         """transformers.onnx is deprecated, and will be removed in v5. You can find more information here: """
         """https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model."""		)







def      a__ (						a__		):




     """simple docstring"""


     __SCREAMING_SNAKE_CASE						     =   args.output if args.output.is_file() else args.output.joinpath("""model.onnx"""		)
     if not args.output.parent.exists():
          args.output.parent.mkdir(parents=a__		)

     # Allocate the model
     __SCREAMING_SNAKE_CASE						     =   FeaturesManager.get_model_from_feature(
         args.feature   ,					args.model   ,					framework=args.framework   ,					cache_dir=args.cache_dir		)

     __SCREAMING_SNAKE_CASE						     =   FeaturesManager.check_supported_model_or_raise(a__   ,					feature=args.feature		)
     __SCREAMING_SNAKE_CASE						     =   model_onnx_config(model.config		)

     if model_kind in ENCODER_DECODER_MODELS:
          __SCREAMING_SNAKE_CASE						     =   model.get_encoder()
          __SCREAMING_SNAKE_CASE						     =   model.get_decoder()

          __SCREAMING_SNAKE_CASE						     =   onnx_config.get_encoder_config(encoder_model.config		)
          __SCREAMING_SNAKE_CASE						     =   onnx_config.get_decoder_config(
              encoder_model.config   ,					decoder_model.config   ,					feature=args.feature		)

          if args.opset is None:
               __SCREAMING_SNAKE_CASE						     =   max(encoder_onnx_config.default_onnx_opset   ,					decoder_onnx_config.default_onnx_opset		)

          if args.opset < min(encoder_onnx_config.default_onnx_opset   ,					decoder_onnx_config.default_onnx_opset		):
               raise ValueError(
                   F'Opset {args.opset} is not sufficient to export {model_kind}. At least '
                   F' {min(encoder_onnx_config.default_onnx_opset   ,					decoder_onnx_config.default_onnx_opset		)} is required.'		)

          __SCREAMING_SNAKE_CASE						     =   AutoFeatureExtractor.from_pretrained(args.model		)

          __SCREAMING_SNAKE_CASE						     =   export(
              a__   ,					a__   ,					a__   ,					args.opset   ,					args.output.parent.joinpath("""encoder_model.onnx"""		)   ,					)

          validate_model_outputs(
              a__   ,					a__   ,					a__   ,					args.output.parent.joinpath("""encoder_model.onnx"""		)   ,					a__   ,					args.atol if args.atol else encoder_onnx_config.atol_for_validation   ,					)

          __SCREAMING_SNAKE_CASE						     =   AutoTokenizer.from_pretrained(args.model		)

          __SCREAMING_SNAKE_CASE						     =   export(
              a__   ,					a__   ,					a__   ,					args.opset   ,					args.output.parent.joinpath("""decoder_model.onnx"""		)   ,					)

          validate_model_outputs(
              a__   ,					a__   ,					a__   ,					args.output.parent.joinpath("""decoder_model.onnx"""		)   ,					a__   ,					args.atol if args.atol else decoder_onnx_config.atol_for_validation   ,					)
          logger.info(
              F'All good, model saved at: {args.output.parent.joinpath("encoder_model.onnx"		).as_posix()},'
              F' {args.output.parent.joinpath("decoder_model.onnx"		).as_posix()}'		)

     else:
          # Instantiate the appropriate preprocessor
          if args.preprocessor == "auto":
               __SCREAMING_SNAKE_CASE						     =   get_preprocessor(args.model		)
          elif args.preprocessor == "tokenizer":
               __SCREAMING_SNAKE_CASE						     =   AutoTokenizer.from_pretrained(args.model		)
          elif args.preprocessor == "image_processor":
               __SCREAMING_SNAKE_CASE						     =   AutoImageProcessor.from_pretrained(args.model		)
          elif args.preprocessor == "feature_extractor":
               __SCREAMING_SNAKE_CASE						     =   AutoFeatureExtractor.from_pretrained(args.model		)
          elif args.preprocessor == "processor":
               __SCREAMING_SNAKE_CASE						     =   AutoProcessor.from_pretrained(args.model		)
          else:
               raise ValueError(F'Unknown preprocessor type \'{args.preprocessor}\''		)

          # Ensure the requested opset is sufficient
          if args.opset is None:
               __SCREAMING_SNAKE_CASE						     =   onnx_config.default_onnx_opset

          if args.opset < onnx_config.default_onnx_opset:
               raise ValueError(
                   F'Opset {args.opset} is not sufficient to export {model_kind}. '
                   F'At least  {onnx_config.default_onnx_opset} is required.'		)

          __SCREAMING_SNAKE_CASE						     =   export(
              a__   ,					a__   ,					a__   ,					args.opset   ,					args.output   ,					)

          if args.atol is None:
               __SCREAMING_SNAKE_CASE						     =   onnx_config.atol_for_validation

          validate_model_outputs(a__   ,					a__   ,					a__   ,					args.output   ,					a__   ,					args.atol		)
          logger.info(F'All good, model saved at: {args.output.as_posix()}'		)
          warnings.warn(
              """The export was done by transformers.onnx which is deprecated and will be removed in v5. We recommend"""
              """ using optimum.exporters.onnx in future. You can find more information here:"""
              """ https://huggingface.co/docs/optimum/exporters/onnx/usage_guides/export_a_model."""   ,					a__   ,					)







def      a__ (						):




     """simple docstring"""


     __SCREAMING_SNAKE_CASE						     =   ArgumentParser("""Hugging Face Transformers ONNX exporter"""		)
     parser.add_argument(
         """-m"""   ,					"""--model"""   ,					type=a__   ,					required=a__   ,					help="""Model ID on huggingface.co or path on disk to load model from."""		)
     parser.add_argument(
         """--feature"""   ,					default="""default"""   ,					help="""The type of features to export the model with."""   ,					)
     parser.add_argument("""--opset"""   ,					type=a__   ,					default=a__   ,					help="""ONNX opset version to export the model with."""		)
     parser.add_argument(
         """--atol"""   ,					type=a__   ,					default=a__   ,					help="""Absolute difference tolerance when validating the model."""		)
     parser.add_argument(
         """--framework"""   ,					type=a__   ,					choices=["""pt""", """tf"""]   ,					default=a__   ,					help=(
             """The framework to use for the ONNX export."""
             """ If not provided, will attempt to use the local checkpoint's original framework"""
             """ or what is available in the environment."""
         )   ,					)
     parser.add_argument("""output"""   ,					type=a__   ,					help="""Path indicating where to store generated ONNX model."""		)
     parser.add_argument("""--cache_dir"""   ,					type=a__   ,					default=a__   ,					help="""Path indicating where to store cache."""		)
     parser.add_argument(
         """--preprocessor"""   ,					type=a__   ,					choices=["""auto""", """tokenizer""", """feature_extractor""", """image_processor""", """processor"""]   ,					default="""auto"""   ,					help="""Which type of preprocessor to use. 'auto' tries to automatically detect it."""   ,					)
     parser.add_argument(
         """--export_with_transformers"""   ,					action="""store_true"""   ,					help=(
             """Whether to use transformers.onnx instead of optimum.exporters.onnx to perform the ONNX export. It can be """
             """useful when exporting a model supported in transformers but not in optimum, otherwise it is not """
             """recommended."""
         )   ,					)

     __SCREAMING_SNAKE_CASE						     =   parser.parse_args()
     if args.export_with_transformers or not is_optimum_available():
          export_with_transformers(a__		)
     else:
          export_with_optimum(a__		)


if __name__ == "__main__":
  UpperCAmelCase				: int         =  logging.get_logger('transformers.onnx')  # pylint: disable=invalid-name
  logger.setLevel(logging.INFO)
  main()








'''simple docstring'''



import inspect
import warnings

import torch

from .state import AcceleratorState, GradientState
from .utils import DistributedType, honor_type, is_tpu_available


if is_tpu_available(check_device=False):
  import torch_xla.core.xla_model as xm







def      a__ (						a__   ,					a__		):




     """simple docstring"""


     if isinstance(a__   ,					(list, tuple)		):
          return honor_type(a__   ,					(move_to_device(a__   ,					a__		) for t in state)		)
     elif isinstance(a__   ,					a__		):
          return type(a__		)({k: move_to_device(a__   ,					a__		) for k, v in state.items()}		)
     elif isinstance(a__   ,					torch.Tensor		):
          return state.to(a__		)
     return state







class 		lowerCAmelCase__     (   torch.optim.Optimizer      ):



 """simple docstring"""



 def __init__(	self      : Tuple      ,							__SCREAMING_SNAKE_CASE      : Union[str, Any]      ,							__SCREAMING_SNAKE_CASE      : Dict=True      ,							__SCREAMING_SNAKE_CASE      : List[Any]=None    )						->				str:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   optimizer
      __SCREAMING_SNAKE_CASE						     =   scaler
      __SCREAMING_SNAKE_CASE						     =   AcceleratorState()
      __SCREAMING_SNAKE_CASE						     =   GradientState()
      __SCREAMING_SNAKE_CASE						     =   device_placement
      __SCREAMING_SNAKE_CASE						     =   False
      __SCREAMING_SNAKE_CASE						     =   None

      # Handle device placement
      if device_placement:
           __SCREAMING_SNAKE_CASE						     =   self.optimizer.state_dict()
           if self.accelerator_state.distributed_type == DistributedType.TPU:
                xm.send_cpu_data_to_device(__SCREAMING_SNAKE_CASE      ,							self.accelerator_state.device    )
           else:
                __SCREAMING_SNAKE_CASE						     =   move_to_device(__SCREAMING_SNAKE_CASE      ,							self.accelerator_state.device    )
           self.optimizer.load_state_dict(__SCREAMING_SNAKE_CASE    )
 @property
 def    UpperCAmelCase__	(	self      : str    )						->				Union[str, Any]:


      """simple docstring"""




      return self.optimizer.state
 @state.setter
 def    UpperCAmelCase__	(	self      : List[str]      ,							__SCREAMING_SNAKE_CASE      : Optional[Any]    )						->				List[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   state
 @property
 def    UpperCAmelCase__	(	self      : Optional[int]    )						->				str:


      """simple docstring"""




      return self.optimizer.param_groups
 @param_groups.setter
 def    UpperCAmelCase__	(	self      : Dict      ,							__SCREAMING_SNAKE_CASE      : str    )						->				List[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   param_groups
 @property
 def    UpperCAmelCase__	(	self      : List[Any]    )						->				Any:


      """simple docstring"""




      return self.optimizer.defaults
 @defaults.setter
 def    UpperCAmelCase__	(	self      : Any      ,							__SCREAMING_SNAKE_CASE      : Dict    )						->				Optional[Any]:


      """simple docstring"""




      __SCREAMING_SNAKE_CASE						     =   defaults
 def    UpperCAmelCase__	(	self      : Any      ,							__SCREAMING_SNAKE_CASE      : Any    )						->				List[str]:


      """simple docstring"""




      self.optimizer.add_param_group(__SCREAMING_SNAKE_CASE    )
 def    UpperCAmelCase__	(	self      : List[str]      ,							__SCREAMING_SNAKE_CASE      : List[str]    )						->				Dict:


      """simple docstring"""




      if self.accelerator_state.distributed_type == DistributedType.TPU and self.device_placement:
           xm.send_cpu_data_to_device(__SCREAMING_SNAKE_CASE      ,							self.accelerator_state.device    )
      self.optimizer.load_state_dict(__SCREAMING_SNAKE_CASE    )
 def    UpperCAmelCase__	(	self      : Union[str, Any]    )						->				Union[str, Any]:


      """simple docstring"""




      return self.optimizer.state_dict()
 def    UpperCAmelCase__	(	self      : List[str]      ,							__SCREAMING_SNAKE_CASE      : List[str]=None    )						->				Any:


      """simple docstring"""




      if self.gradient_state.sync_gradients:
           __SCREAMING_SNAKE_CASE						     =   """set_to_none""" in inspect.signature(self.optimizer.zero_grad    ).parameters
           if accept_arg:
                if set_to_none is None:
                     __SCREAMING_SNAKE_CASE						     =   False
                self.optimizer.zero_grad(set_to_none=__SCREAMING_SNAKE_CASE    )
           else:
                if set_to_none is not None:
                     raise ValueError("""`set_to_none` for Optimizer.zero_grad` is not supported by this optimizer."""    )
                self.optimizer.zero_grad()
 def    UpperCAmelCase__	(	self      : List[str]      ,							__SCREAMING_SNAKE_CASE      : List[Any]=None    )						->				Dict:


      """simple docstring"""




      if self.gradient_state.sync_gradients:
           if self.accelerator_state.distributed_type == DistributedType.TPU:
                __SCREAMING_SNAKE_CASE						     =   {"""closure""": closure} if closure is not None else {}
                xm.optimizer_step(self.optimizer      ,							optimizer_args=__SCREAMING_SNAKE_CASE    )
           elif self.scaler is not None:
                __SCREAMING_SNAKE_CASE						     =   False
                if self._last_scale is None:
                     # `get_scale` is an async operation requiring full synchronization
                     # on CPU and GPUs before finishing. As a result, we store away
                     # the prior one to reduce the call overhead
                     __SCREAMING_SNAKE_CASE						     =   self.scaler.get_scale()
                     __SCREAMING_SNAKE_CASE						     =   True
                self.scaler.step(self.optimizer      ,							__SCREAMING_SNAKE_CASE    )
                self.scaler.update()
                __SCREAMING_SNAKE_CASE						     =   self.scaler.get_scale()
                if not new_scale:
                     # If we reduced the loss scale, it means the optimizer step was skipped because of gradient overflow.
                     __SCREAMING_SNAKE_CASE						     =   scale_after < self._last_scale
                __SCREAMING_SNAKE_CASE						     =   scale_after

           else:
                self.optimizer.step(__SCREAMING_SNAKE_CASE    )
 def    UpperCAmelCase__	(	self      : Union[str, Any]      ,							__SCREAMING_SNAKE_CASE      : Any    )						->				Any:


      """simple docstring"""




      for param_group in self.optimizer.param_groups:
           __SCREAMING_SNAKE_CASE						     =   [parameters_map.get(__SCREAMING_SNAKE_CASE      ,							__SCREAMING_SNAKE_CASE    ) for p in param_group["""params"""]]
 @property
 def    UpperCAmelCase__	(	self      : int    )						->				Any:


      """simple docstring"""




      warnings.warn(
          """The `is_overflow` property is deprecated and will be removed in version 1.0 of Accelerate use """
          """`optimizer.step_was_skipped` instead."""      ,							__SCREAMING_SNAKE_CASE      ,							)
      return self._is_overflow
 @property
 def    UpperCAmelCase__	(	self      : Union[str, Any]    )						->				Optional[int]:


      """simple docstring"""




      return self._is_overflow
 def __getstate__(	self      : Tuple    )						->				str:


      """simple docstring"""




      return self.__dict__.copy()


 def __setstate__(	self      : str      ,							__SCREAMING_SNAKE_CASE      : Optional[int]    )						->				Any:


      """simple docstring"""




      self.__dict__.update(__SCREAMING_SNAKE_CASE    )






