

import collections
import inspect
import unittest

from transformers import NatConfig
from transformers.testing_utils import require_natten, require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_backbone_common import BackboneTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch
  from torch import nn

  from transformers import NatBackbone, NatForImageClassification, NatModel
  from transformers.models.nat.modeling_nat import NAT_PRETRAINED_MODEL_ARCHIVE_LIST

if is_vision_available():
  from PIL import Image

  from transformers import AutoImageProcessor







class     a__    :







  """simple docstring"""




  def __init__(     self      :	Union[str, Any]			,			UpperCAmelCase__      :	Union[str, Any]			,			UpperCAmelCase__      :	str=1_3			,			UpperCAmelCase__      :	List[Any]=6_4			,			UpperCAmelCase__      :	Optional[Any]=4			,			UpperCAmelCase__      :	Dict=3			,			UpperCAmelCase__      :	Any=1_6			,			UpperCAmelCase__      :	Optional[int]=[1, 2, 1]			,			UpperCAmelCase__      :	Dict=[2, 4, 8]			,			UpperCAmelCase__      :	Optional[int]=3			,			UpperCAmelCase__      :	Optional[int]=2.0			,			UpperCAmelCase__      :	Any=True			,			UpperCAmelCase__      :	Tuple=0.0			,			UpperCAmelCase__      :	List[str]=0.0			,			UpperCAmelCase__      :	List[str]=0.1			,			UpperCAmelCase__      :	Any="gelu"			,			UpperCAmelCase__      :	Any=True			,			UpperCAmelCase__      :	List[str]=0.02			,			UpperCAmelCase__      :	Optional[int]=1e-5			,			UpperCAmelCase__      :	Dict=True			,			UpperCAmelCase__      :	Optional[int]=None			,			UpperCAmelCase__      :	List[str]=True			,			UpperCAmelCase__      :	str=1_0			,			UpperCAmelCase__      :	Union[str, Any]=["stage1", "stage2"]			,			UpperCAmelCase__      :	Union[str, Any]=[1, 2]			,			)   ->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[int]					       =				parent
        SCREAMING_SNAKE_CASE	: int					       =				batch_size
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				image_size
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				patch_size
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				num_channels
        SCREAMING_SNAKE_CASE	: int					       =				embed_dim
        SCREAMING_SNAKE_CASE	: str					       =				depths
        SCREAMING_SNAKE_CASE	: Tuple					       =				num_heads
        SCREAMING_SNAKE_CASE	: Any					       =				kernel_size
        SCREAMING_SNAKE_CASE	: Any					       =				mlp_ratio
        SCREAMING_SNAKE_CASE	: Dict					       =				qkv_bias
        SCREAMING_SNAKE_CASE	: Any					       =				hidden_dropout_prob
        SCREAMING_SNAKE_CASE	: List[str]					       =				attention_probs_dropout_prob
        SCREAMING_SNAKE_CASE	: Any					       =				drop_path_rate
        SCREAMING_SNAKE_CASE	: Dict					       =				hidden_act
        SCREAMING_SNAKE_CASE	: int					       =				patch_norm
        SCREAMING_SNAKE_CASE	: List[str]					       =				layer_norm_eps
        SCREAMING_SNAKE_CASE	: Tuple					       =				initializer_range
        SCREAMING_SNAKE_CASE	: List[str]					       =				is_training
        SCREAMING_SNAKE_CASE	: Any					       =				scope
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				use_labels
        SCREAMING_SNAKE_CASE	: Any					       =				num_labels
        SCREAMING_SNAKE_CASE	: str					       =				out_features
        SCREAMING_SNAKE_CASE	: List[str]					       =				out_indices


  def 	_lowercase (     self      :	str						)   ->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Tuple					       =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

        SCREAMING_SNAKE_CASE	: List[str]					       =				None
        if self.use_labels:
              SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				ids_tensor([self.batch_size]			,			self.num_labels						)

        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				self.get_config()

        return config, pixel_values, labels


  def 	_lowercase (     self      :	Dict						)   ->List[str]:
        """simple docstring"""







        return NatConfig(
            num_labels=self.num_labels			,			image_size=self.image_size			,			patch_size=self.patch_size			,			num_channels=self.num_channels			,			embed_dim=self.embed_dim			,			depths=self.depths			,			num_heads=self.num_heads			,			kernel_size=self.kernel_size			,			mlp_ratio=self.mlp_ratio			,			qkv_bias=self.qkv_bias			,			hidden_dropout_prob=self.hidden_dropout_prob			,			attention_probs_dropout_prob=self.attention_probs_dropout_prob			,			drop_path_rate=self.drop_path_rate			,			hidden_act=self.hidden_act			,			patch_norm=self.patch_norm			,			layer_norm_eps=self.layer_norm_eps			,			initializer_range=self.initializer_range			,			out_features=self.out_features			,			out_indices=self.out_indices			,			)


  def 	_lowercase (     self      :	int			,			UpperCAmelCase__      :	Optional[int]			,			UpperCAmelCase__      :	str			,			UpperCAmelCase__      :	Tuple						)   ->List[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: List[str]					       =				NatModel(config=UpperCAmelCase__						)
        model.to(UpperCAmelCase__						)
        model.eval()
        SCREAMING_SNAKE_CASE	: Dict					       =				model(UpperCAmelCase__						)

        SCREAMING_SNAKE_CASE	: Tuple					       =				(config.image_size // config.patch_size) // (2 ** (len(config.depths						) - 1))
        SCREAMING_SNAKE_CASE	: str					       =				int(config.embed_dim * 2 ** (len(config.depths						) - 1)						)

        self.parent.assertEqual(
            result.last_hidden_state.shape			,			(self.batch_size, expected_height, expected_width, expected_dim)						)


  def 	_lowercase (     self      :	List[Any]			,			UpperCAmelCase__      :	str			,			UpperCAmelCase__      :	Dict			,			UpperCAmelCase__      :	int						)   ->List[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Dict					       =				NatForImageClassification(UpperCAmelCase__						)
        model.to(UpperCAmelCase__						)
        model.eval()
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				model(UpperCAmelCase__			,			labels=UpperCAmelCase__						)
        self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.num_labels)						)

        # test greyscale images
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				1
        SCREAMING_SNAKE_CASE	: List[Any]					       =				NatForImageClassification(UpperCAmelCase__						)
        model.to(UpperCAmelCase__						)
        model.eval()

        SCREAMING_SNAKE_CASE	: List[str]					       =				floats_tensor([self.batch_size, 1, self.image_size, self.image_size]						)
        SCREAMING_SNAKE_CASE	: int					       =				model(UpperCAmelCase__						)
        self.parent.assertEqual(result.logits.shape			,			(self.batch_size, self.num_labels)						)


  def 	_lowercase (     self      :	Any			,			UpperCAmelCase__      :	Optional[Any]			,			UpperCAmelCase__      :	List[str]			,			UpperCAmelCase__      :	Optional[Any]						)   ->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: int					       =				NatBackbone(config=UpperCAmelCase__						)
        model.to(UpperCAmelCase__						)
        model.eval()
        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				model(UpperCAmelCase__						)

        # verify hidden states
        self.parent.assertEqual(len(result.feature_maps						)			,			len(config.out_features						)						)
        self.parent.assertListEqual(list(result.feature_maps[0].shape						)			,			[self.batch_size, model.channels[0], 1_6, 1_6]						)

        # verify channels
        self.parent.assertEqual(len(model.channels						)			,			len(config.out_features						)						)

        # verify backbone works with out_features=None
        SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				None
        SCREAMING_SNAKE_CASE	: str					       =				NatBackbone(config=UpperCAmelCase__						)
        model.to(UpperCAmelCase__						)
        model.eval()
        SCREAMING_SNAKE_CASE	: Optional[int]					       =				model(UpperCAmelCase__						)

        # verify feature maps
        self.parent.assertEqual(len(result.feature_maps						)			,			1						)
        self.parent.assertListEqual(list(result.feature_maps[0].shape						)			,			[self.batch_size, model.channels[-1], 4, 4]						)

        # verify channels
        self.parent.assertEqual(len(model.channels						)			,			1						)




  def 	_lowercase (     self      :	Tuple						)   ->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: int					       =				self.prepare_config_and_inputs()
        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: str					       =				config_and_inputs
        SCREAMING_SNAKE_CASE	: List[str]					       =				{"""pixel_values""": pixel_values}
        return config, inputs_dict







@require_natten
@require_torch
class     a__    (				UpperCAmelCase		,     UpperCAmelCase		,     unittest.TestCase    ):







  """simple docstring"""




  UpperCAmelCase__ :	List[str]         =(
      (
          NatModel,
          NatForImageClassification,
          NatBackbone,
      )
      if is_torch_available()
      else ()
  )
  UpperCAmelCase__ :	Any         =(
      {"""feature-extraction""": NatModel, """image-classification""": NatForImageClassification}
      if is_torch_available()
      else {}
  )
  UpperCAmelCase__ :	Optional[int]         =False

  UpperCAmelCase__ :	Optional[Any]         =False
  UpperCAmelCase__ :	Optional[int]         =False
  UpperCAmelCase__ :	Union[str, Any]         =False
  UpperCAmelCase__ :	List[Any]         =False


  def 	_lowercase (     self      :	List[str]						)   ->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[int]					       =				NatModelTester(self						)
        SCREAMING_SNAKE_CASE	: Any					       =				ConfigTester(self			,			config_class=UpperCAmelCase__			,			embed_dim=3_7						)


  def 	_lowercase (     self      :	Tuple						)   ->int:
        """simple docstring"""







        self.create_and_test_config_common_properties()
        self.config_tester.create_and_test_config_to_json_string()
        self.config_tester.create_and_test_config_to_json_file()
        self.config_tester.create_and_test_config_from_and_save_pretrained()
        self.config_tester.create_and_test_config_with_num_labels()
        self.config_tester.check_config_can_be_init_without_params()
        self.config_tester.check_config_arguments_init()


  def 	_lowercase (     self      :	List[Any]						)   ->List[str]:
        """simple docstring"""







        return


  def 	_lowercase (     self      :	Optional[int]						)   ->Optional[int]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: List[Any]					       =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*UpperCAmelCase__						)


  def 	_lowercase (     self      :	Any						)   ->List[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[int]					       =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__						)


  def 	_lowercase (     self      :	Union[str, Any]						)   ->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: str					       =				self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_backbone(*UpperCAmelCase__						)


  @unittest.skip(reason="""Nat does not use inputs_embeds"""						)
  def 	_lowercase (     self      :	str						)   ->Optional[int]:
        """simple docstring"""







        pass


  @unittest.skip(reason="""Nat does not use feedforward chunking"""						)
  def 	_lowercase (     self      :	int						)   ->Optional[int]:
        """simple docstring"""







        pass


  def 	_lowercase (     self      :	Any						)   ->Union[str, Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: str					       =				self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE	: Optional[int]					       =				model_class(UpperCAmelCase__						)
              self.assertIsInstance(model.get_input_embeddings()			,			(nn.Module)						)
              SCREAMING_SNAKE_CASE	: Optional[Any]					       =				model.get_output_embeddings()
              self.assertTrue(x is None or isinstance(UpperCAmelCase__			,			nn.Linear						)						)


  def 	_lowercase (     self      :	Union[str, Any]						)   ->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Dict					       =				self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE	: Tuple					       =				model_class(UpperCAmelCase__						)
              SCREAMING_SNAKE_CASE	: Optional[int]					       =				inspect.signature(model.forward						)
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              SCREAMING_SNAKE_CASE	: Dict					       =				[*signature.parameters.keys()]

              SCREAMING_SNAKE_CASE	: int					       =				["""pixel_values"""]
              self.assertListEqual(arg_names[:1]			,			UpperCAmelCase__						)


  def 	_lowercase (     self      :	List[Any]						)   ->Optional[Any]:
        """simple docstring"""







        self.skipTest("""Nat's attention operation is handled entirely by NATTEN."""						)


  def 	_lowercase (     self      :	Optional[int]			,			UpperCAmelCase__      :	Optional[Any]			,			UpperCAmelCase__      :	Union[str, Any]			,			UpperCAmelCase__      :	Optional[Any]			,			UpperCAmelCase__      :	str						)   ->Union[str, Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Dict					       =				model_class(UpperCAmelCase__						)
        model.to(UpperCAmelCase__						)
        model.eval()

        with torch.no_grad():
              SCREAMING_SNAKE_CASE	: Tuple					       =				model(**self._prepare_for_class(UpperCAmelCase__			,			UpperCAmelCase__						)						)

        SCREAMING_SNAKE_CASE	: List[str]					       =				outputs.hidden_states

        SCREAMING_SNAKE_CASE	: Tuple					       =				getattr(
            self.model_tester			,			"""expected_num_hidden_layers"""			,			len(self.model_tester.depths						) + 1						)
        self.assertEqual(len(UpperCAmelCase__						)			,			UpperCAmelCase__						)

        # Nat has a different seq_length
        SCREAMING_SNAKE_CASE	: Any					       =				(
            config.patch_size
            if isinstance(config.patch_size			,			collections.abc.Iterable						)
            else (config.patch_size, config.patch_size)
        )

        SCREAMING_SNAKE_CASE	: int					       =				image_size[0] // patch_size[0]
        SCREAMING_SNAKE_CASE	: int					       =				image_size[1] // patch_size[1]

        self.assertListEqual(
            list(hidden_states[0].shape[-3:]						)			,			[height, width, self.model_tester.embed_dim]			,			)

        if model_class.__name__ != "NatBackbone":
              SCREAMING_SNAKE_CASE	: str					       =				outputs.reshaped_hidden_states
              self.assertEqual(len(UpperCAmelCase__						)			,			UpperCAmelCase__						)

              SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Optional[Any]					       =				reshaped_hidden_states[0].shape
              SCREAMING_SNAKE_CASE	: str					       =				(
                  reshaped_hidden_states[0].view(UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__						).permute(0			,			2			,			3			,			1						)
              )
              self.assertListEqual(
                  list(reshaped_hidden_states.shape[-3:]						)			,			[height, width, self.model_tester.embed_dim]			,			)


  def 	_lowercase (     self      :	Union[str, Any]						)   ->Optional[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Tuple					       =				self.model_tester.prepare_config_and_inputs_for_common()

        SCREAMING_SNAKE_CASE	: Tuple					       =				(
            self.model_tester.image_size
            if isinstance(self.model_tester.image_size			,			collections.abc.Iterable						)
            else (self.model_tester.image_size, self.model_tester.image_size)
        )

        for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE	: str					       =				True
              self.check_hidden_states_output(UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__						)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              SCREAMING_SNAKE_CASE	: Tuple					       =				True

              self.check_hidden_states_output(UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__			,			UpperCAmelCase__						)


  @slow
  def 	_lowercase (     self      :	str						)   ->Dict:
        """simple docstring"""







        for model_name in NAT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              SCREAMING_SNAKE_CASE	: Tuple					       =				NatModel.from_pretrained(UpperCAmelCase__						)
              self.assertIsNotNone(UpperCAmelCase__						)




  def 	_lowercase (     self      :	Dict						)   ->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Optional[int]					       =				self.model_tester.prepare_config_and_inputs_for_common()

        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				_config_zero_init(UpperCAmelCase__						)
        for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE	: Dict					       =				model_class(config=UpperCAmelCase__						)
              for name, param in model.named_parameters():
                    if "embeddings" not in name and param.requires_grad:
                          self.assertIn(
                              ((param.data.mean() * 1e9).round() / 1e9).item()			,			[0.0, 1.0]			,			msg=f"Parameter {name} of model {model_class} seems not properly initialized"			,			)







@require_natten
@require_vision
@require_torch
class     a__    (				unittest.TestCase    ):







  """simple docstring"""




  @cached_property
  def 	_lowercase (     self      :	int						)   ->Union[str, Any]:
        """simple docstring"""







        return AutoImageProcessor.from_pretrained("""shi-labs/nat-mini-in1k-224"""						) if is_vision_available() else None




  @slow
  def 	_lowercase (     self      :	List[str]						)   ->List[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: str					       =				NatForImageClassification.from_pretrained("""shi-labs/nat-mini-in1k-224"""						).to(UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: Any					       =				self.default_image_processor

        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""						)
        SCREAMING_SNAKE_CASE	: Any					       =				image_processor(images=UpperCAmelCase__			,			return_tensors="""pt"""						).to(UpperCAmelCase__						)

        # forward pass
        with torch.no_grad():
              SCREAMING_SNAKE_CASE	: Tuple					       =				model(**UpperCAmelCase__						)

        # verify the logits
        SCREAMING_SNAKE_CASE	: int					       =				torch.Size((1, 1_0_0_0)						)
        self.assertEqual(outputs.logits.shape			,			UpperCAmelCase__						)
        SCREAMING_SNAKE_CASE	: List[str]					       =				torch.tensor([0.38_05, -0.86_76, -0.39_12]						).to(UpperCAmelCase__						)
        self.assertTrue(torch.allclose(outputs.logits[0, :3]			,			UpperCAmelCase__			,			atol=1e-4						)						)







@require_torch
@require_natten
class     a__    (				unittest.TestCase		,     UpperCAmelCase    ):







  """simple docstring"""




  UpperCAmelCase__ :	Any         =(NatBackbone,) if is_torch_available() else ()
  UpperCAmelCase__ :	Any         =NatConfig


  def 	_lowercase (     self      :	int						)   ->str:
        """simple docstring"""







        SCREAMING_SNAKE_CASE	: Optional[Any]					       =				NatModelTester(self						)







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__	:       Any			      =      ["""vision-encoder-decoder"""]






def    __lowercase (       _A     )       ->  Any:
      if is_optimum_available():
            from optimum.version import __version__ as optimum_version

            SCREAMING_SNAKE_CASE	: int					       =				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	: List[str]					       =				[
          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	: Dict					       =				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    __lowercase (       _A     )       ->  Any:
      SCREAMING_SNAKE_CASE	: List[str]					       =				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	: Optional[int]					       =				FeaturesManager.get_model_from_feature(
          args.feature  ,      args.model  ,      framework=args.framework  ,      cache_dir=args.cache_dir     )

      SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Any					       =				FeaturesManager.check_supported_model_or_raise(_A  ,      feature=args.feature     )
      SCREAMING_SNAKE_CASE	: str					       =				model_onnx_config(model.config     )

      if model_kind in ENCODER_DECODER_MODELS:
            SCREAMING_SNAKE_CASE	: str					       =				model.get_encoder()
            SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				model.get_decoder()

            SCREAMING_SNAKE_CASE	: Optional[int]					       =				onnx_config.get_encoder_config(encoder_model.config     )
            SCREAMING_SNAKE_CASE	: Optional[int]					       =				onnx_config.get_decoder_config(
                encoder_model.config  ,      decoder_model.config  ,      feature=args.feature     )

            if args.opset is None:
                  SCREAMING_SNAKE_CASE	: Optional[int]					       =				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	: List[str]					       =				AutoFeatureExtractor.from_pretrained(args.model     )

            SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: Optional[int]					       =				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	: Optional[int]					       =				AutoTokenizer.from_pretrained(args.model     )

            SCREAMING_SNAKE_CASE       ,		SCREAMING_SNAKE_CASE	: List[Any]					       =				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	: List[Any]					       =				get_preprocessor(args.model     )
            elif args.preprocessor == "tokenizer":
                  SCREAMING_SNAKE_CASE	: Optional[Any]					       =				AutoTokenizer.from_pretrained(args.model     )
            elif args.preprocessor == "image_processor":
                  SCREAMING_SNAKE_CASE	: Union[str, Any]					       =				AutoImageProcessor.from_pretrained(args.model     )
            elif args.preprocessor == "feature_extractor":
                  SCREAMING_SNAKE_CASE	: int					       =				AutoFeatureExtractor.from_pretrained(args.model     )
            elif args.preprocessor == "processor":
                  SCREAMING_SNAKE_CASE	: List[Any]					       =				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	: Dict					       =				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       ,		SCREAMING_SNAKE_CASE	: Optional[Any]					       =				export(
                _A  ,      _A  ,      _A  ,      args.opset  ,      args.output  ,      )

            if args.atol is None:
                  SCREAMING_SNAKE_CASE	: List[Any]					       =				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    __lowercase (       )       ->  List[str]:
      SCREAMING_SNAKE_CASE	: List[Any]					       =				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	: Tuple					       =				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__	:       Optional[Any]			      =      logging.get_logger("""transformers.onnx""")  # pylint: disable=invalid-name
  logger.setLevel(logging.INFO)
  main()




