




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


     """simple docstring"""


     def __init__(	self			: Optional[int]				,_UpperCamelCase			: Union[str, Any]				,_UpperCamelCase			: Dict=1_3				,_UpperCamelCase			: Any=3_2				,_UpperCamelCase			: Union[str, Any]=3				,_UpperCamelCase			: Union[str, Any]=[3, 3, 5]				,_UpperCamelCase			: str=[3_2, 1_6, 2_4]				,_UpperCamelCase			: Any=[1_6, 2_4, 4_0]				,_UpperCamelCase			: Dict=[1, 1, 2]				,_UpperCamelCase			: Tuple=[1, 1, 2]				,_UpperCamelCase			: Dict=[1, 6, 6]				,_UpperCamelCase			: str=True				,_UpperCamelCase			: Any=True				,_UpperCamelCase			: Union[str, Any]=3_7				,_UpperCamelCase			: List[Any]="gelu"				,_UpperCamelCase			: str=1_0				,)		->   Dict:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=parent
         SCREAMING_SNAKE_CASE__								=batch_size
         SCREAMING_SNAKE_CASE__								=image_size
         SCREAMING_SNAKE_CASE__								=num_channels
         SCREAMING_SNAKE_CASE__								=kernel_sizes
         SCREAMING_SNAKE_CASE__								=in_channels
         SCREAMING_SNAKE_CASE__								=out_channels
         SCREAMING_SNAKE_CASE__								=strides
         SCREAMING_SNAKE_CASE__								=num_block_repeats
         SCREAMING_SNAKE_CASE__								=expand_ratios
         SCREAMING_SNAKE_CASE__								=is_training
         SCREAMING_SNAKE_CASE__								=hidden_act
         SCREAMING_SNAKE_CASE__								=num_labels
         SCREAMING_SNAKE_CASE__								=use_labels




     def   __A				(	self			: Optional[Any]						)		->   List[str]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

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

         SCREAMING_SNAKE_CASE__								=self.get_config()
         return config, pixel_values, labels




     def   __A				(	self			: Optional[int]						)		->   Optional[Any]:


         '''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   __A				(	self			: Dict				,_UpperCamelCase			: Union[str, Any]				,_UpperCamelCase			: Optional[Any]				,_UpperCamelCase			: str						)		->   List[Any]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=EfficientNetModel(config=_UpperCamelCase						)
         model.to(_UpperCamelCase						)
         model.eval()
         SCREAMING_SNAKE_CASE__								=model(_UpperCamelCase						)
         # 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   __A				(	self			: Optional[Any]				,_UpperCamelCase			: List[str]				,_UpperCamelCase			: Dict				,_UpperCamelCase			: Union[str, Any]						)		->   Tuple:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=EfficientNetForImageClassification(_UpperCamelCase						)
         model.to(_UpperCamelCase						)
         model.eval()
         SCREAMING_SNAKE_CASE__								=model(_UpperCamelCase				,labels=_UpperCamelCase						)
         self.parent.assertEqual(result.logits.shape				,(self.batch_size, self.num_labels)						)




     def   __A				(	self			: Optional[Any]						)		->   List[Any]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=self.prepare_config_and_inputs()
         SCREAMING_SNAKE_CASE__			,		SCREAMING_SNAKE_CASE__			,		SCREAMING_SNAKE_CASE__								=config_and_inputs
         SCREAMING_SNAKE_CASE__								={"""pixel_values""": pixel_values}
         return config, inputs_dict






@require_torch
class       __a					( __lowerCamelCase							,     __lowerCamelCase							,     unittest.TestCase     ):


     """simple docstring"""


     _A				:    Optional[Any]									=  (EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
     _A				:    Optional[int]									=  (
         {"feature-extraction": EfficientNetModel, "image-classification": EfficientNetForImageClassification}
         if is_torch_available()
         else {}
     )

     _A				:    Dict									=  False
     _A				:    List[str]									=  False
     _A				:    Union[str, Any]									=  False
     _A				:    str									=  False
     _A				:    List[str]									=  False




     def   __A				(	self			: Optional[int]						)		->   int:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=EfficientNetModelTester(self						)
         SCREAMING_SNAKE_CASE__								=ConfigTester(
             self				,config_class=_UpperCamelCase				,has_text_modality=_UpperCamelCase				,hidden_size=3_7						)




     def   __A				(	self			: Optional[int]						)		->   Tuple:


         '''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   __A				(	self			: Optional[Any]						)		->   List[Any]:


         '''simple docstring'''





         return




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


         '''simple docstring'''





         pass




     @unittest.skip(reason="""EfficientNet does not support input and output embeddings"""						)
     def   __A				(	self			: List[Any]						)		->   Optional[int]:


         '''simple docstring'''





         pass




     @unittest.skip(reason="""EfficientNet does not use feedforward chunking"""						)
     def   __A				(	self			: List[str]						)		->   int:


         '''simple docstring'''





         pass




     def   __A				(	self			: Union[str, Any]						)		->   Optional[Any]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__			,		SCREAMING_SNAKE_CASE__								=self.model_tester.prepare_config_and_inputs_for_common()

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

             SCREAMING_SNAKE_CASE__								=["""pixel_values"""]
             self.assertListEqual(arg_names[:1]				,_UpperCamelCase						)




     def   __A				(	self			: Tuple						)		->   int:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*_UpperCamelCase						)




     def   __A				(	self			: Any						)		->   Union[str, Any]:


         '''simple docstring'''





         def check_hidden_states_output(_UpperCamelCase			: Any				,_UpperCamelCase			: str				,_UpperCamelCase			: int						):
             SCREAMING_SNAKE_CASE__								=model_class(_UpperCamelCase						)
             model.to(_UpperCamelCase						)
             model.eval()

             with torch.no_grad():
                 SCREAMING_SNAKE_CASE__								=model(**self._prepare_for_class(_UpperCamelCase				,_UpperCamelCase						)						)

             SCREAMING_SNAKE_CASE__								=outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
             SCREAMING_SNAKE_CASE__								=sum(config.num_block_repeats						) * 4
             self.assertEqual(len(_UpperCamelCase						)				,_UpperCamelCase						)

             # 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]				,)

         SCREAMING_SNAKE_CASE__			,		SCREAMING_SNAKE_CASE__								=self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE__								=True
             check_hidden_states_output(_UpperCamelCase				,_UpperCamelCase				,_UpperCamelCase						)

             # check that output_hidden_states also work using config
             del inputs_dict["output_hidden_states"]
             SCREAMING_SNAKE_CASE__								=True

             check_hidden_states_output(_UpperCamelCase				,_UpperCamelCase				,_UpperCamelCase						)




     def   __A				(	self			: Any						)		->   int:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*_UpperCamelCase						)




     @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""						)
     def   __A				(	self			: List[Any]						)		->   Tuple:


         '''simple docstring'''





         pass




     @slow
     def   __A				(	self			: List[Any]						)		->   Optional[int]:


         '''simple docstring'''





         for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             SCREAMING_SNAKE_CASE__								=EfficientNetModel.from_pretrained(_UpperCamelCase						)
             self.assertIsNotNone(_UpperCamelCase						)




     @is_pipeline_test
     @require_vision
     @slow
     def   __A				(	self			: int						)		->   Optional[int]:


         '''simple docstring'''





         super().test_pipeline_image_classification()






def 	UpperCAmelCase_    (	):
    SCREAMING_SNAKE_CASE__								=Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""	)
    return image




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


     """simple docstring"""


     @cached_property
     def   __A				(	self			: Dict						)		->   Optional[int]:


         '''simple docstring'''





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




     @slow
     def   __A				(	self			: Tuple						)		->   Optional[int]:


         '''simple docstring'''





         SCREAMING_SNAKE_CASE__								=EfficientNetForImageClassification.from_pretrained("""google/efficientnet-b7"""						).to(_UpperCamelCase						)

         SCREAMING_SNAKE_CASE__								=self.default_image_processor
         SCREAMING_SNAKE_CASE__								=prepare_img()
         SCREAMING_SNAKE_CASE__								=image_processor(images=_UpperCamelCase				,return_tensors="""pt"""						).to(_UpperCamelCase						)

         # forward pass
         with torch.no_grad():
             SCREAMING_SNAKE_CASE__								=model(**_UpperCamelCase						)

         # verify the logits
         SCREAMING_SNAKE_CASE__								=torch.Size((1, 1_0_0_0)						)
         self.assertEqual(outputs.logits.shape				,_UpperCamelCase						)

         SCREAMING_SNAKE_CASE__								=torch.tensor([0.0001, 0.0002, 0.0002]						).to(_UpperCamelCase						)
         self.assertTrue(torch.allclose(outputs.logits[0, :3]				,_UpperCamelCase				,atol=1e-4						)						)












def 	UpperCAmelCase_    (	__UpperCamelCase	):
    if not isinstance(__UpperCamelCase,				__UpperCamelCase	):
        raise ValueError("""double_factorial() only accepts integral values"""	)
    if n < 0:
        raise ValueError("""double_factorial() not defined for negative values"""	)
    return 1 if n <= 1 else n * double_factorial(n - 2	)


if __name__ == "__main__":
    import doctest

    doctest.testmod()






