




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 							__SCREAMING_SNAKE_CASE				:

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







						'''simple docstring'''




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

					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						Optional[int]				  =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

						lowerCamelCase_				:						int				  =				None
						if self.use_labels:
							lowerCamelCase_				:						str				  =				ids_tensor([self.batch_size]					,			self.num_labels   )

						lowerCamelCase_				:						Union[str, Any]				  =				self.get_config()
						return config, pixel_values, labels

					def       lowercase_				(							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       lowercase_				(							self					,			__lowercase					,			__lowercase					,			__lowercase   ):







						'''simple docstring'''




						lowerCamelCase_				:						Any				  =				EfficientNetModel(config=__lowercase   )
						model.to(__lowercase   )
						model.eval()
						lowerCamelCase_				:						Dict				  =				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       lowercase_				(							self					,			__lowercase					,			__lowercase					,			__lowercase   ):







						'''simple docstring'''




						lowerCamelCase_				:						Tuple				  =				EfficientNetForImageClassification(__lowercase   )
						model.to(__lowercase   )
						model.eval()
						lowerCamelCase_				:						Union[str, Any]				  =				model(__lowercase					,			labels=__lowercase   )
						self.parent.assertEqual(result.logits.shape					,			(self.batch_size, self.num_labels)   )





					def       lowercase_				(							self   ):







						'''simple docstring'''




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


@require_torch
class 							__SCREAMING_SNAKE_CASE				(						lowerCamelCase  ,	lowerCamelCase  ,	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       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						Optional[Any]				  =				EfficientNetModelTester(self   )
						lowerCamelCase_				:						Dict				  =				ConfigTester(
						    self					,			config_class=__lowercase					,			has_text_modality=__lowercase					,			hidden_size=37   )

					def       lowercase_				(							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       lowercase_				(							self   ):







						'''simple docstring'''




						return

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







						'''simple docstring'''




						pass

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







						'''simple docstring'''




						pass

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







						'''simple docstring'''




						pass

					def       lowercase_				(							self   ):







						'''simple docstring'''




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

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

							lowerCamelCase_				:						Any				  =				['pixel_values']
							self.assertListEqual(arg_names[:1]					,			__lowercase   )

					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						Tuple				  =				self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*__lowercase   )

					def       lowercase_				(							self   ):







						'''simple docstring'''




						def check_hidden_states_output(__lowercase					,			__lowercase					,			__lowercase   ):
							lowerCamelCase_				:						List[Any]				  =				model_class(__lowercase   )
							model.to(__lowercase   )
							model.eval()

							with torch.no_grad():
								lowerCamelCase_				:						str				  =				model(**self._prepare_for_class(__lowercase					,			__lowercase   )   )

							lowerCamelCase_				:						List[Any]				  =				outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
							lowerCamelCase_				:						str				  =				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]					,			)

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

						for model_class in self.all_model_classes:
							lowerCamelCase_				:						Any				  =				True
							check_hidden_states_output(__lowercase					,			__lowercase					,			__lowercase   )

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

							check_hidden_states_output(__lowercase					,			__lowercase					,			__lowercase   )

					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						Optional[Any]				  =				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       lowercase_				(							self   ):







						'''simple docstring'''




						pass

					@slow
					def       lowercase_				(							self   ):







						'''simple docstring'''




						for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							lowerCamelCase_				:						int				  =				EfficientNetModel.from_pretrained(__lowercase   )
							self.assertIsNotNone(__lowercase   )





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







						'''simple docstring'''




						super().test_pipeline_image_classification()






def    snake_case   (				)				->				List[Any]:




	'''simple docstring'''


	lowerCamelCase_				:						Optional[Any]				  =				Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'     )
	return image



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

					@cached_property
					def       lowercase_				(							self   ):







						'''simple docstring'''




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





					@slow
					def       lowercase_				(							self   ):







						'''simple docstring'''




						lowerCamelCase_				:						str				  =				EfficientNetForImageClassification.from_pretrained('google/efficientnet-b7'   ).to(__lowercase   )

						lowerCamelCase_				:						int				  =				self.default_image_processor
						lowerCamelCase_				:						Optional[Any]				  =				prepare_img()
						lowerCamelCase_				:						Optional[int]				  =				image_processor(images=__lowercase					,			return_tensors='pt'   ).to(__lowercase   )

						# forward pass
						with torch.no_grad():
							lowerCamelCase_				:						List[Any]				  =				model(**__lowercase   )

						# verify the logits
						lowerCamelCase_				:						List[str]				  =				torch.Size((1, 1_000)   )
						self.assertEqual(outputs.logits.shape					,			__lowercase   )

						lowerCamelCase_				:						Tuple				  =				torch.tensor([0.00_01, 0.00_02, 0.00_02]   ).to(__lowercase   )
						self.assertTrue(torch.allclose(outputs.logits[0, :3]					,			__lowercase					,			atol=1E-4   )   )


import copy

from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ..auto.configuration_auto import AutoConfig


__UpperCAmelCase   						=     logging.get_logger(__name__)





class 				UpperCamelCase__		(	__SCREAMING_SNAKE_CASE	):






       """simple docstring"""


       UpperCAmelCase_				       ="speech-encoder-decoder"
       UpperCAmelCase_				       =True



       def __init__(							self ,     **_A	)				->				Dict:
          super().__init__(**_A	)
          if "encoder" not in kwargs or "decoder" not in kwargs:
             raise ValueError(
                 F'''A configuraton of type {self.model_type} cannot be instantiated because not both `encoder` and'''
                 F''' `decoder` sub-configurations are passed, but only {kwargs}'''	)

          SCREAMING_SNAKE_CASE_	=      kwargs.pop('''encoder'''	)
          SCREAMING_SNAKE_CASE_	=      encoder_config.pop('''model_type'''	)
          SCREAMING_SNAKE_CASE_	=      kwargs.pop('''decoder'''	)
          SCREAMING_SNAKE_CASE_	=      decoder_config.pop('''model_type'''	)

          SCREAMING_SNAKE_CASE_	=      AutoConfig.for_model(_A ,     **_A	)
          SCREAMING_SNAKE_CASE_	=      AutoConfig.for_model(_A ,     **_A	)
          SCREAMING_SNAKE_CASE_	=      True



       @classmethod
       def     _UpperCamelCase	(							cls ,     _A ,     _A ,     **_A	)				->				PretrainedConfig:
          logger.info('''Setting `config.is_decoder=True` and `config.add_cross_attention=True` for decoder_config'''	)
          SCREAMING_SNAKE_CASE_	=      True
          SCREAMING_SNAKE_CASE_	=      True

          return cls(encoder=encoder_config.to_dict() ,     decoder=decoder_config.to_dict() ,     **_A	)




       def     _UpperCamelCase	(							self	)				->				Union[str, Any]:
          SCREAMING_SNAKE_CASE_	=      copy.deepcopy(self.__dict__	)
          SCREAMING_SNAKE_CASE_	=      self.encoder.to_dict()
          SCREAMING_SNAKE_CASE_	=      self.decoder.to_dict()
          SCREAMING_SNAKE_CASE_	=      self.__class__.model_type
          return output


