
'''simple docstring'''







import inspect
import unittest

from transformers import EfficientNetConfig
from transformers.testing_utils import is_pipeline_test, require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

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


if is_torch_available():
							import torch

							from transformers import EfficientNetForImageClassification, EfficientNetModel
							from transformers.models.efficientnet.modeling_efficientnet import EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
							from PIL import Image

							from transformers import AutoImageProcessor






class 					lowerCAmelCase__  :






					def __init__(  self							,				__SCREAMING_SNAKE_CASE							,				__SCREAMING_SNAKE_CASE=13							,				__SCREAMING_SNAKE_CASE=32							,				__SCREAMING_SNAKE_CASE=3							,				__SCREAMING_SNAKE_CASE=[3, 3, 5]							,				__SCREAMING_SNAKE_CASE=[32, 16, 24]							,				__SCREAMING_SNAKE_CASE=[16, 24, 40]							,				__SCREAMING_SNAKE_CASE=[1, 1, 2]							,				__SCREAMING_SNAKE_CASE=[1, 1, 2]							,				__SCREAMING_SNAKE_CASE=[1, 6, 6]							,				__SCREAMING_SNAKE_CASE=True							,				__SCREAMING_SNAKE_CASE=True							,				__SCREAMING_SNAKE_CASE=37							,				__SCREAMING_SNAKE_CASE="gelu"							,				__SCREAMING_SNAKE_CASE=10							,				):


											"""simple docstring"""





											lowercase_      :	Union[str, Any]						=			parent
											lowercase_      :	Optional[Any]						=			batch_size
											lowercase_      :	List[str]						=			image_size
											lowercase_      :	int						=			num_channels
											lowercase_      :	Union[str, Any]						=			kernel_sizes
											lowercase_      :	Optional[int]						=			in_channels
											lowercase_      :	Optional[int]						=			out_channels
											lowercase_      :	List[str]						=			strides
											lowercase_      :	List[str]						=			num_block_repeats
											lowercase_      :	Union[str, Any]						=			expand_ratios
											lowercase_      :	Optional[Any]						=			is_training
											lowercase_      :	Optional[Any]						=			hidden_act
											lowercase_      :	int						=			num_labels
											lowercase_      :	List[Any]						=			use_labels






					def       _snake_case       (  self						):


											"""simple docstring"""





											lowercase_      :	Union[str, Any]						=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

											lowercase_      :	Optional[int]						=			None
											if self.use_labels:
																	lowercase_      :	Dict						=			ids_tensor([self.batch_size]							,				self.num_labels						)

											lowercase_      :	Any						=			self.get_config()
											return config, pixel_values, labels






					def       _snake_case       (  self						):


											"""simple docstring"""





											return EfficientNetConfig(
											    num_channels=self.num_channels							,				kernel_sizes=self.kernel_sizes							,				in_channels=self.in_channels							,				out_channels=self.out_channels							,				strides=self.strides							,				num_block_repeats=self.num_block_repeats							,				expand_ratios=self.expand_ratios							,				hidden_act=self.hidden_act							,				num_labels=self.num_labels							,				)






					def       _snake_case       (  self							,				__SCREAMING_SNAKE_CASE							,				__SCREAMING_SNAKE_CASE							,				__SCREAMING_SNAKE_CASE						):


											"""simple docstring"""





											lowercase_      :	Dict						=			EfficientNetModel(config=_lowercase						)
											model.to(_lowercase						)
											model.eval()
											lowercase_      :	Optional[Any]						=			model(_lowercase						)
											# expected last hidden states: B, C, H // 4, W // 4
											self.parent.assertEqual(
											    result.last_hidden_state.shape							,				(self.batch_size, config.hidden_dim, self.image_size // 4, self.image_size // 4)							,				)






					def       _snake_case       (  self							,				__SCREAMING_SNAKE_CASE							,				__SCREAMING_SNAKE_CASE							,				__SCREAMING_SNAKE_CASE						):


											"""simple docstring"""





											lowercase_      :	Tuple						=			EfficientNetForImageClassification(_lowercase						)
											model.to(_lowercase						)
											model.eval()
											lowercase_      :	int						=			model(_lowercase							,				labels=_lowercase						)
											self.parent.assertEqual(result.logits.shape							,				(self.batch_size, self.num_labels)						)






					def       _snake_case       (  self						):


											"""simple docstring"""





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







@require_torch
class 					lowerCAmelCase__  (    UpperCAmelCase_       ,		UpperCAmelCase_       ,		unittest.TestCase	):
					lowerCAmelCase_	  =	(EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
					lowerCAmelCase_	  =	(
					    {'feature-extraction': EfficientNetModel, 'image-classification': EfficientNetForImageClassification}
					    if is_torch_available()
					    else {}
					)

					lowerCAmelCase_	  =	False
					lowerCAmelCase_	  =	False
					lowerCAmelCase_	  =	False
					lowerCAmelCase_	  =	False
					lowerCAmelCase_	  =	False






					def       _snake_case       (  self						):


											"""simple docstring"""





											lowercase_      :	Optional[Any]						=			EfficientNetModelTester(self						)
											lowercase_      :	Union[str, Any]						=			ConfigTester(
											    self							,				config_class=_lowercase							,				has_text_modality=_lowercase							,				hidden_size=37						)






					def       _snake_case       (  self						):


											"""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       _snake_case       (  self						):


											"""simple docstring"""





											return






					@unittest.skip(reason='''EfficientNet does not use inputs_embeds'''						)
					def       _snake_case       (  self						):


											"""simple docstring"""





											pass






					@unittest.skip(reason='''EfficientNet does not support input and output embeddings'''						)
					def       _snake_case       (  self						):


											"""simple docstring"""





											pass






					@unittest.skip(reason='''EfficientNet does not use feedforward chunking'''						)
					def       _snake_case       (  self						):


											"""simple docstring"""





											pass






					def       _snake_case       (  self						):


											"""simple docstring"""





											lowercase_      :	Union[str, Any]						=			self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	lowercase_      :	Any						=			model_class(_lowercase						)
																	lowercase_      :	str						=			inspect.signature(model.forward						)
																	# signature.parameters is an OrderedDict => so arg_names order is deterministic
																	lowercase_      :	List[str]						=			[*signature.parameters.keys()]

																	lowercase_      :	Optional[int]						=			['pixel_values']
																	self.assertListEqual(arg_names[:1]							,				_lowercase						)






					def       _snake_case       (  self						):


											"""simple docstring"""





											lowercase_      :	Any						=			self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*_lowercase						)






					def       _snake_case       (  self						):


											"""simple docstring"""





											def check_hidden_states_output(__SCREAMING_SNAKE_CASE							,				__SCREAMING_SNAKE_CASE							,				__SCREAMING_SNAKE_CASE						):
																	lowercase_      :	Dict						=			model_class(_lowercase						)
																	model.to(_lowercase						)
																	model.eval()

																	with torch.no_grad():
																							lowercase_      :	List[Any]						=			model(**self._prepare_for_class(_lowercase							,				_lowercase						)						)

																	lowercase_      :	Dict						=			outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
																	lowercase_      :	List[Any]						=			sum(config.num_block_repeats						) * 4
																	self.assertEqual(len(_lowercase						)							,				_lowercase						)

																	# EfficientNet's feature maps are of shape (batch_size, num_channels, height, width)
																	self.assertListEqual(
																	    list(hidden_states[0].shape[-2:]						)							,				[self.model_tester.image_size // 2, self.model_tester.image_size // 2]							,				)

											lowercase_      :	List[Any]						=			self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																	lowercase_      :	Union[str, Any]						=			True
																	check_hidden_states_output(_lowercase							,				_lowercase							,				_lowercase						)

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

																	check_hidden_states_output(_lowercase							,				_lowercase							,				_lowercase						)






					def       _snake_case       (  self						):


											"""simple docstring"""





											lowercase_      :	Dict						=			self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*_lowercase						)






					@unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.'''						)
					def       _snake_case       (  self						):


											"""simple docstring"""





											pass






					@slow
					def       _snake_case       (  self						):


											"""simple docstring"""





											for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	lowercase_      :	Tuple						=			EfficientNetModel.from_pretrained(_lowercase						)
																	self.assertIsNotNone(_lowercase						)






					@is_pipeline_test
					@require_vision
					@slow
					def       _snake_case       (  self						):


											"""simple docstring"""





											super().test_pipeline_image_classification()







def    snake_case_						(							):



						"""simple docstring"""





						lowercase_      :	str						=			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
						return image






@require_torch
@require_vision
class 					lowerCAmelCase__  (    unittest.TestCase	):






					@cached_property
					def       _snake_case       (  self						):


											"""simple docstring"""





											return AutoImageProcessor.from_pretrained('''google/efficientnet-b7'''						) if is_vision_available() else None






					@slow
					def       _snake_case       (  self						):


											"""simple docstring"""





											lowercase_      :	Tuple						=			EfficientNetForImageClassification.from_pretrained('''google/efficientnet-b7'''						).to(_lowercase						)

											lowercase_      :	Union[str, Any]						=			self.default_image_processor
											lowercase_      :	Any						=			prepare_img()
											lowercase_      :	int						=			image_processor(images=_lowercase							,				return_tensors='''pt'''						).to(_lowercase						)

											# forward pass
											with torch.no_grad():
																	lowercase_      :	Optional[int]						=			model(**_lowercase						)

											# verify the logits
											lowercase_      :	str						=			torch.Size((1, 10_00)						)
											self.assertEqual(outputs.logits.shape							,				_lowercase						)

											lowercase_      :	Any						=			torch.tensor([0.0_001, 0.0_002, 0.0_002]						).to(_lowercase						)
											self.assertTrue(torch.allclose(outputs.logits[0, :3]							,				_lowercase							,				atol=1E-4						)						)











'''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


A:   List[str]						=					"1.5.0"

A:   Any						=					["vision-encoder-decoder"]






def 						_UpperCAmelCase     (	a		:						int				)      ->      List[str]:





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

												lowercase_   : List[Any]   	=      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]'				)
						lowercase_   : List[Any]   	=      [
						    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}",
						]
						lowercase_   : Tuple   	=      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 						_UpperCAmelCase     (	a		:						Dict				)      ->      Optional[Any]:





						"""simple docstring"""
						lowercase_   : Optional[int]   	=      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
						lowercase_   : int   	=      FeaturesManager.get_model_from_feature(
						    args.feature    ,      args.model    ,      framework=args.framework    ,      cache_dir=args.cache_dir				)

						lowercase_	,   lowercase_   : List[Any]   	=      FeaturesManager.check_supported_model_or_raise(a    ,      feature=args.feature				)
						lowercase_   : List[str]   	=      model_onnx_config(model.config				)

						if model_kind in ENCODER_DECODER_MODELS:
												lowercase_   : List[Any]   	=      model.get_encoder()
												lowercase_   : Any   	=      model.get_decoder()

												lowercase_   : List[str]   	=      onnx_config.get_encoder_config(encoder_model.config				)
												lowercase_   : int   	=      onnx_config.get_decoder_config(
												    encoder_model.config    ,      decoder_model.config    ,      feature=args.feature				)

												if args.opset is None:
																		lowercase_   : 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."				)

												lowercase_   : str   	=      AutoFeatureExtractor.from_pretrained(args.model				)

												lowercase_	,   lowercase_   : str   	=      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    ,      )

												lowercase_   : Optional[Any]   	=      AutoTokenizer.from_pretrained(args.model				)

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

												lowercase_	,   lowercase_   : str   	=      export(
												    a    ,      a    ,      a    ,      args.opset    ,      args.output    ,      )

												if args.atol is None:
																		lowercase_   : Dict   	=      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 						_UpperCAmelCase     (	)      ->      List[Any]:





						"""simple docstring"""
						lowercase_   : Optional[int]   	=      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.'
						    )    ,      )

						lowercase_   : int   	=      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__":
						A:   Union[str, Any]						=					logging.get_logger("transformers.onnx")  # pylint: disable=invalid-name
						logger.setLevel(logging.INFO)
						main()
