


'''simple docstring'''
import inspect
import unittest

from transformers import ResNetConfig
from transformers.testing_utils import 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, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
     import torch
     from torch import nn

     from transformers import ResNetBackbone, ResNetForImageClassification, ResNetModel
     from transformers.models.resnet.modeling_resnet import RESNET_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
     from PIL import Image

     from transformers import AutoImageProcessor







class 					_A						:



   '''simple docstring'''






   def __init__(	self	:					Tuple					, lowerCamelCase	:					Optional[int]					, lowerCamelCase	:					List[Any]=3					, lowerCamelCase	:					Optional[Any]=32					, lowerCamelCase	:					Optional[Any]=3					, lowerCamelCase	:					List[Any]=10					, lowerCamelCase	:					Optional[Any]=[10, 20, 30, 40]					, lowerCamelCase	:					Optional[int]=[1, 1, 2, 1]					, lowerCamelCase	:					Any=True					, lowerCamelCase	:					Any=True					, lowerCamelCase	:					List[str]="relu"					, lowerCamelCase	:					List[Any]=3					, lowerCamelCase	:					List[Any]=None					, lowerCamelCase	:					Any=["stage2", "stage3", "stage4"]					, lowerCamelCase	:					Any=[2, 3, 4]					, )->	Optional[int]:
          snake_case__					:	List[Any]          =					parent
          snake_case__					:	List[Any]          =					batch_size
          snake_case__					:	int          =					image_size
          snake_case__					:	str          =					num_channels
          snake_case__					:	str          =					embeddings_size
          snake_case__					:	List[Any]          =					hidden_sizes
          snake_case__					:	Optional[Any]          =					depths
          snake_case__					:	Any          =					is_training
          snake_case__					:	str          =					use_labels
          snake_case__					:	Union[str, Any]          =					hidden_act
          snake_case__					:	Optional[int]          =					num_labels
          snake_case__					:	Union[str, Any]          =					scope
          snake_case__					:	Optional[int]          =					len(lowerCamelCase						)
          snake_case__					:	Dict          =					out_features
          snake_case__					:	int          =					out_indices




   def   __lowerCAmelCase						(	self	:					int						)->	List[str]:
          snake_case__					:	int          =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

          snake_case__					:	Optional[int]          =					self.get_config()

          return config, pixel_values, labels




   def   __lowerCAmelCase						(	self	:					str						)->	Tuple:
          return ResNetConfig(
              num_channels=self.num_channels					, embeddings_size=self.embeddings_size					, hidden_sizes=self.hidden_sizes					, depths=self.depths					, hidden_act=self.hidden_act					, num_labels=self.num_labels					, out_features=self.out_features					, out_indices=self.out_indices					, )




   def   __lowerCAmelCase						(	self	:					Any					, lowerCamelCase	:					Tuple					, lowerCamelCase	:					Optional[Any]					, lowerCamelCase	:					Optional[int]						)->	List[str]:
          snake_case__					:	str          =					ResNetModel(config=lowerCamelCase						)
          model.to(lowerCamelCase						)
          model.eval()
          snake_case__					:	int          =					model(lowerCamelCase						)
          # expected last hidden states: B, C, H // 32, W // 32
          self.parent.assertEqual(
              result.last_hidden_state.shape					, (self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)					, )




   def   __lowerCAmelCase						(	self	:					Tuple					, lowerCamelCase	:					Tuple					, lowerCamelCase	:					Tuple					, lowerCamelCase	:					Tuple						)->	Optional[Any]:
          snake_case__					:	str          =					self.num_labels
          snake_case__					:	Dict          =					ResNetForImageClassification(lowerCamelCase						)
          model.to(lowerCamelCase						)
          model.eval()
          snake_case__					:	Optional[int]          =					model(lowerCamelCase					, labels=lowerCamelCase						)
          self.parent.assertEqual(result.logits.shape					, (self.batch_size, self.num_labels)						)




   def   __lowerCAmelCase						(	self	:					Dict					, lowerCamelCase	:					Any					, lowerCamelCase	:					Dict					, lowerCamelCase	:					List[str]						)->	Union[str, Any]:
          snake_case__					:	Optional[Any]          =					ResNetBackbone(config=lowerCamelCase						)
          model.to(lowerCamelCase						)
          model.eval()
          snake_case__					:	Any          =					model(lowerCamelCase						)

          # verify feature maps
          self.parent.assertEqual(len(result.feature_maps						)					, len(config.out_features						)						)
          self.parent.assertListEqual(list(result.feature_maps[0].shape						)					, [self.batch_size, self.hidden_sizes[1], 4, 4]						)

          # verify channels
          self.parent.assertEqual(len(model.channels						)					, len(config.out_features						)						)
          self.parent.assertListEqual(model.channels					, config.hidden_sizes[1:]						)

          # verify backbone works with out_features=None
          snake_case__					:	List[str]          =					None
          snake_case__					:	Optional[Any]          =					ResNetBackbone(config=lowerCamelCase						)
          model.to(lowerCamelCase						)
          model.eval()
          snake_case__					:	List[str]          =					model(lowerCamelCase						)

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

          # verify channels
          self.parent.assertEqual(len(model.channels						)					, 1						)
          self.parent.assertListEqual(model.channels					, [config.hidden_sizes[-1]]						)




   def   __lowerCAmelCase						(	self	:					List[str]						)->	Any:
          snake_case__					:	int          =					self.prepare_config_and_inputs()
          snake_case__       ,   snake_case__       ,   snake_case__					:	str          =					config_and_inputs
          snake_case__					:	Optional[Any]          =					{"""pixel_values""": pixel_values}
          return config, inputs_dict







@require_torch
class 					_A						(						UpperCamelCase    ,  UpperCamelCase    ,  unittest.TestCase							):



   '''simple docstring'''






   _lowercase    						= (
       (
           ResNetModel,
           ResNetForImageClassification,
           ResNetBackbone,
       )
       if is_torch_available()
       else ()
   )
   _lowercase    						= (
       {'feature-extraction': ResNetModel, 'image-classification': ResNetForImageClassification}
       if is_torch_available()
       else {}
   )

   _lowercase    						= True
   _lowercase    						= False
   _lowercase    						= False
   _lowercase    						= False
   _lowercase    						= False




   def   __lowerCAmelCase						(	self	:					str						)->	Optional[int]:
          snake_case__					:	Dict          =					ResNetModelTester(self						)
          snake_case__					:	Optional[int]          =					ConfigTester(self					, config_class=lowerCamelCase					, has_text_modality=lowerCamelCase						)




   def   __lowerCAmelCase						(	self	:					Union[str, Any]						)->	Optional[int]:
          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   __lowerCAmelCase						(	self	:					int						)->	Dict:
          return




   @unittest.skip(reason="""ResNet does not use inputs_embeds"""						)
   def   __lowerCAmelCase						(	self	:					Any						)->	Union[str, Any]:
          pass




   @unittest.skip(reason="""ResNet does not support input and output embeddings"""						)
   def   __lowerCAmelCase						(	self	:					Tuple						)->	Dict:
          pass




   def   __lowerCAmelCase						(	self	:					Optional[Any]						)->	int:
          snake_case__       ,   snake_case__					:	Dict          =					self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 snake_case__					:	Any          =					model_class(lowerCamelCase						)
                 snake_case__					:	Union[str, Any]          =					inspect.signature(model.forward						)
                 # signature.parameters is an OrderedDict => so arg_names order is deterministic
                 snake_case__					:	int          =					[*signature.parameters.keys()]

                 snake_case__					:	List[str]          =					["""pixel_values"""]
                 self.assertListEqual(arg_names[:1]					, lowerCamelCase						)




   def   __lowerCAmelCase						(	self	:					int						)->	Dict:
          snake_case__					:	Optional[Any]          =					self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowerCamelCase						)




   def   __lowerCAmelCase						(	self	:					str						)->	Tuple:
          snake_case__					:	List[Any]          =					self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_backbone(*lowerCamelCase						)




   def   __lowerCAmelCase						(	self	:					int						)->	int:
          snake_case__       ,   snake_case__					:	Optional[Any]          =					self.model_tester.prepare_config_and_inputs_for_common()

          for model_class in self.all_model_classes:
                 snake_case__					:	Optional[Any]          =					model_class(config=lowerCamelCase						)
                 for name, module in model.named_modules():
                        if isinstance(lowerCamelCase					, (nn.BatchNormad, nn.GroupNorm)						):
                               self.assertTrue(
                                   torch.all(module.weight == 1						)					, msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""					, )
                               self.assertTrue(
                                   torch.all(module.bias == 0						)					, msg=F"""Parameter {name} of model {model_class} seems not properly initialized"""					, )




   def   __lowerCAmelCase						(	self	:					Any						)->	Optional[int]:
          def check_hidden_states_output(lowerCamelCase	:					Any					, lowerCamelCase	:					Optional[Any]					, lowerCamelCase	:					str						):
                 snake_case__					:	Any          =					model_class(lowerCamelCase						)
                 model.to(lowerCamelCase						)
                 model.eval()

                 with torch.no_grad():
                        snake_case__					:	Union[str, Any]          =					model(**self._prepare_for_class(lowerCamelCase					, lowerCamelCase						)						)

                 snake_case__					:	int          =					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

                 snake_case__					:	str          =					self.model_tester.num_stages
                 self.assertEqual(len(lowerCamelCase						)					, expected_num_stages + 1						)

                 # ResNet'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 // 4, self.model_tester.image_size // 4]					, )

          snake_case__       ,   snake_case__					:	str          =					self.model_tester.prepare_config_and_inputs_for_common()
          snake_case__					:	List[Any]          =					["""basic""", """bottleneck"""]
          for model_class in self.all_model_classes:
                 for layer_type in layers_type:
                        snake_case__					:	Any          =					layer_type
                        snake_case__					:	Tuple          =					True
                        check_hidden_states_output(lowerCamelCase					, lowerCamelCase					, lowerCamelCase						)

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

                        check_hidden_states_output(lowerCamelCase					, lowerCamelCase					, lowerCamelCase						)




   @unittest.skip(reason="""ResNet does not use feedforward chunking"""						)
   def   __lowerCAmelCase						(	self	:					int						)->	Optional[int]:
          pass




   def   __lowerCAmelCase						(	self	:					Tuple						)->	int:
          snake_case__					:	Union[str, Any]          =					self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*lowerCamelCase						)




   @slow
   def   __lowerCAmelCase						(	self	:					Dict						)->	List[str]:
          for model_name in RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 snake_case__					:	List[Any]          =					ResNetModel.from_pretrained(lowerCamelCase						)
                 self.assertIsNotNone(lowerCamelCase						)







def 				lowerCAmelCase__	(       ):






       """simple docstring"""





       snake_case__					:	List[str]          =					Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""     )
       return image







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



   '''simple docstring'''






   @cached_property
   def   __lowerCAmelCase						(	self	:					Union[str, Any]						)->	Any:
          return (
              AutoImageProcessor.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)
              if is_vision_available()
              else None
          )




   @slow
   def   __lowerCAmelCase						(	self	:					str						)->	Optional[int]:
          snake_case__					:	Tuple          =					ResNetForImageClassification.from_pretrained(RESNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						).to(lowerCamelCase						)

          snake_case__					:	Any          =					self.default_image_processor
          snake_case__					:	int          =					prepare_img()
          snake_case__					:	str          =					image_processor(images=lowerCamelCase					, return_tensors="""pt"""						).to(lowerCamelCase						)

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

          # verify the logits
          snake_case__					:	str          =					torch.Size((1, 1_000)						)
          self.assertEqual(outputs.logits.shape					, lowerCamelCase						)

          snake_case__					:	Union[str, Any]          =					torch.tensor([-11.1_069, -9.7_877, -8.3_777]						).to(lowerCamelCase						)

          self.assertTrue(torch.allclose(outputs.logits[0, :3]					, lowerCamelCase					, atol=1e-4						)						)







@require_torch
class 					_A						(						UpperCamelCase    ,  unittest.TestCase							):



   '''simple docstring'''






   _lowercase    						= (ResNetBackbone,) if is_torch_available() else ()
   _lowercase    						= False
   _lowercase    						= ResNetConfig




   def   __lowerCAmelCase						(	self	:					int						)->	Optional[int]:
          snake_case__					:	Tuple          =					ResNetModelTester(self						)








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


lowerCAmelCase__  =     '1.5.0'

lowerCAmelCase__  =     ['vision-encoder-decoder']



def 				lowerCAmelCase__	(       UpperCAmelCase     ):






       """simple docstring"""





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

              snake_case__					:	Dict          =					version.parse(UpperCAmelCase     )
              if parsed_optimum_version < version.parse(UpperCAmelCase     ):
                     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]"""     )
       snake_case__					:	Union[str, 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}""",
       ]
       snake_case__					:	Union[str, Any]          =					subprocess.Popen(""" """.join(UpperCAmelCase     )    ,       stdout=subprocess.PIPE    ,       shell=UpperCAmelCase     )
       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 				lowerCAmelCase__	(       UpperCAmelCase     ):






       """simple docstring"""





       snake_case__					:	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=UpperCAmelCase     )

       # Allocate the model
       snake_case__					:	Dict          =					FeaturesManager.get_model_from_feature(
           args.feature    ,       args.model    ,       framework=args.framework    ,       cache_dir=args.cache_dir     )

       snake_case__       ,   snake_case__					:	List[Any]          =					FeaturesManager.check_supported_model_or_raise(UpperCAmelCase    ,       feature=args.feature     )
       snake_case__					:	Any          =					model_onnx_config(model.config     )

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

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

              if args.opset is None:
                     snake_case__					:	List[Any]          =					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."""     )

              snake_case__					:	Dict          =					AutoFeatureExtractor.from_pretrained(args.model     )

              snake_case__       ,   snake_case__					:	List[str]          =					export(
                  UpperCAmelCase    ,       UpperCAmelCase    ,       UpperCAmelCase    ,       args.opset    ,       args.output.parent.joinpath("""encoder_model.onnx"""     )    ,       )

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

              snake_case__					:	List[Any]          =					AutoTokenizer.from_pretrained(args.model     )

              snake_case__       ,   snake_case__					:	Dict          =					export(
                  UpperCAmelCase    ,       UpperCAmelCase    ,       UpperCAmelCase    ,       args.opset    ,       args.output.parent.joinpath("""decoder_model.onnx"""     )    ,       )

              validate_model_outputs(
                  UpperCAmelCase    ,       UpperCAmelCase    ,       UpperCAmelCase    ,       args.output.parent.joinpath("""decoder_model.onnx"""     )    ,       UpperCAmelCase    ,       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":
                     snake_case__					:	int          =					get_preprocessor(args.model     )
              elif args.preprocessor == "tokenizer":
                     snake_case__					:	List[str]          =					AutoTokenizer.from_pretrained(args.model     )
              elif args.preprocessor == "image_processor":
                     snake_case__					:	Optional[int]          =					AutoImageProcessor.from_pretrained(args.model     )
              elif args.preprocessor == "feature_extractor":
                     snake_case__					:	Tuple          =					AutoFeatureExtractor.from_pretrained(args.model     )
              elif args.preprocessor == "processor":
                     snake_case__					:	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:
                     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."""     )

              snake_case__       ,   snake_case__					:	Dict          =					export(
                  UpperCAmelCase    ,       UpperCAmelCase    ,       UpperCAmelCase    ,       args.opset    ,       args.output    ,       )

              if args.atol is None:
                     snake_case__					:	int          =					onnx_config.atol_for_validation

              validate_model_outputs(UpperCAmelCase    ,       UpperCAmelCase    ,       UpperCAmelCase    ,       args.output    ,       UpperCAmelCase    ,       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."""    ,       UpperCAmelCase    ,       )



def 				lowerCAmelCase__	(       ):






       """simple docstring"""





       snake_case__					:	List[str]          =					ArgumentParser("""Hugging Face Transformers ONNX exporter"""     )
       parser.add_argument(
           """-m"""    ,       """--model"""    ,       type=UpperCAmelCase    ,       required=UpperCAmelCase    ,       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=UpperCAmelCase    ,       default=UpperCAmelCase    ,       help="""ONNX opset version to export the model with."""     )
       parser.add_argument(
           """--atol"""    ,       type=UpperCAmelCase    ,       default=UpperCAmelCase    ,       help="""Absolute difference tolerance when validating the model."""     )
       parser.add_argument(
           """--framework"""    ,       type=UpperCAmelCase    ,       choices=["""pt""", """tf"""]    ,       default=UpperCAmelCase    ,       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=UpperCAmelCase    ,       help="""Path indicating where to store generated ONNX model."""     )
       parser.add_argument("""--cache_dir"""    ,       type=UpperCAmelCase    ,       default=UpperCAmelCase    ,       help="""Path indicating where to store cache."""     )
       parser.add_argument(
           """--preprocessor"""    ,       type=UpperCAmelCase    ,       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."""
           )    ,       )

       snake_case__					:	str          =					parser.parse_args()
       if args.export_with_transformers or not is_optimum_available():
              export_with_transformers(UpperCAmelCase     )
       else:
              export_with_optimum(UpperCAmelCase     )


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




