





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






       '''simple docstring'''


       def __init__(					self			,  __lowerCamelCase			,  __lowerCamelCase=1_3			,  __lowerCamelCase=3_2			,  __lowerCamelCase=3			,  __lowerCamelCase=[3, 3, 5]			,  __lowerCamelCase=[3_2, 1_6, 2_4]			,  __lowerCamelCase=[1_6, 2_4, 4_0]			,  __lowerCamelCase=[1, 1, 2]			,  __lowerCamelCase=[1, 1, 2]			,  __lowerCamelCase=[1, 6, 6]			,  __lowerCamelCase=True			,  __lowerCamelCase=True			,  __lowerCamelCase=3_7			,  __lowerCamelCase="gelu"			,  __lowerCamelCase=1_0			,  )	->   Union[str, Any]:
            _SCREAMING_SNAKE_CASE				:		str  			=							parent
            _SCREAMING_SNAKE_CASE				:		Any  			=							batch_size
            _SCREAMING_SNAKE_CASE				:		List[str]  			=							image_size
            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							num_channels
            _SCREAMING_SNAKE_CASE				:		Dict  			=							kernel_sizes
            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							in_channels
            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							out_channels
            _SCREAMING_SNAKE_CASE				:		int  			=							strides
            _SCREAMING_SNAKE_CASE				:		str  			=							num_block_repeats
            _SCREAMING_SNAKE_CASE				:		str  			=							expand_ratios
            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							is_training
            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							hidden_act
            _SCREAMING_SNAKE_CASE				:		List[str]  			=							num_labels
            _SCREAMING_SNAKE_CASE				:		Dict  			=							use_labels




       def 			UpperCamelCase_	(					self							)	->   Optional[int]:
            _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

            _SCREAMING_SNAKE_CASE				:		int  			=							None
            if self.use_labels:
                 _SCREAMING_SNAKE_CASE				:		List[Any]  			=							ids_tensor([self.batch_size]			,  self.num_labels							)

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




       def 			UpperCamelCase_	(					self							)	->   Union[str, Any]:
            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 			UpperCamelCase_	(					self			,  __lowerCamelCase			,  __lowerCamelCase			,  __lowerCamelCase							)	->   Optional[Any]:
            _SCREAMING_SNAKE_CASE				:		Dict  			=							EfficientNetModel(config=__lowerCamelCase							)
            model.to(__lowerCamelCase							)
            model.eval()
            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							model(__lowerCamelCase							)
            # 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 			UpperCamelCase_	(					self			,  __lowerCamelCase			,  __lowerCamelCase			,  __lowerCamelCase							)	->   Optional[Any]:
            _SCREAMING_SNAKE_CASE				:		str  			=							EfficientNetForImageClassification(__lowerCamelCase							)
            model.to(__lowerCamelCase							)
            model.eval()
            _SCREAMING_SNAKE_CASE				:		str  			=							model(__lowerCamelCase			,  labels=__lowerCamelCase							)
            self.parent.assertEqual(result.logits.shape			,  (self.batch_size, self.num_labels)							)







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





@require_torch
class 	lowerCAmelCase__(       __lowercase     ,   __lowercase     ,   unittest.TestCase			):






       '''simple docstring'''


       __snake_case       	=			(EfficientNetModel, EfficientNetForImageClassification) if is_torch_available() else ()
       __snake_case       	=			(
           {'feature-extraction': EfficientNetModel, 'image-classification': EfficientNetForImageClassification}
           if is_torch_available()
           else {}
       )

       __snake_case       	=			False
       __snake_case       	=			False
       __snake_case       	=			False
       __snake_case       	=			False
       __snake_case       	=			False




       def 			UpperCamelCase_	(					self							)	->   Optional[Any]:
            _SCREAMING_SNAKE_CASE				:		int  			=							EfficientNetModelTester(self							)
            _SCREAMING_SNAKE_CASE				:		str  			=							ConfigTester(
                self			,  config_class=__lowerCamelCase			,  has_text_modality=__lowerCamelCase			,  hidden_size=3_7							)




       def 			UpperCamelCase_	(					self							)	->   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 			UpperCamelCase_	(					self							)	->   int:
            return




       @unittest.skip(reason="EfficientNet does not use inputs_embeds"							)
       def 			UpperCamelCase_	(					self							)	->   Tuple:
            pass




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




       @unittest.skip(reason="EfficientNet does not use feedforward chunking"							)
       def 			UpperCamelCase_	(					self							)	->   int:
            pass




       def 			UpperCamelCase_	(					self							)	->   Tuple:
            _SCREAMING_SNAKE_CASE			,	_SCREAMING_SNAKE_CASE				:		List[Any]  			=							self.model_tester.prepare_config_and_inputs_for_common()

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

                 _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							["pixel_values"]
                 self.assertListEqual(arg_names[:1]			,  __lowerCamelCase							)




       def 			UpperCamelCase_	(					self							)	->   Optional[Any]:
            _SCREAMING_SNAKE_CASE				:		int  			=							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*__lowerCamelCase							)




       def 			UpperCamelCase_	(					self							)	->   Any:
            def check_hidden_states_output(__lowerCamelCase			,  __lowerCamelCase			,  __lowerCamelCase							):
                 _SCREAMING_SNAKE_CASE				:		Dict  			=							model_class(__lowerCamelCase							)
                 model.to(__lowerCamelCase							)
                 model.eval()

                 with torch.no_grad():
                      _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							model(**self._prepare_for_class(__lowerCamelCase			,  __lowerCamelCase							)							)

                 _SCREAMING_SNAKE_CASE				:		str  			=							outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
                 _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							sum(config.num_block_repeats							) * 4
                 self.assertEqual(len(__lowerCamelCase							)			,  __lowerCamelCase							)

                 # 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				:		Tuple  			=							self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                 _SCREAMING_SNAKE_CASE				:		Any  			=							True
                 check_hidden_states_output(__lowerCamelCase			,  __lowerCamelCase			,  __lowerCamelCase							)

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

                 check_hidden_states_output(__lowerCamelCase			,  __lowerCamelCase			,  __lowerCamelCase							)




       def 			UpperCamelCase_	(					self							)	->   List[str]:
            _SCREAMING_SNAKE_CASE				:		int  			=							self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase							)




       @unittest.skip("Will be fixed soon by reducing the size of the model used for common tests."							)
       def 			UpperCamelCase_	(					self							)	->   Union[str, Any]:
            pass




       @slow
       def 			UpperCamelCase_	(					self							)	->   Optional[int]:
            for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 _SCREAMING_SNAKE_CASE				:		int  			=							EfficientNetModel.from_pretrained(__lowerCamelCase							)
                 self.assertIsNotNone(__lowerCamelCase							)







       @is_pipeline_test
       @require_vision
       @slow
       def 			UpperCamelCase_	(					self							)	->   Dict:
            super().test_pipeline_image_classification()






def 			lowerCamelCase__	():
     _SCREAMING_SNAKE_CASE				:		str  			=							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
     return image





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






       '''simple docstring'''


       @cached_property
       def 			UpperCamelCase_	(					self							)	->   Any:
            return AutoImageProcessor.from_pretrained("google/efficientnet-b7"							) if is_vision_available() else None







       @slow
       def 			UpperCamelCase_	(					self							)	->   Tuple:
            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							EfficientNetForImageClassification.from_pretrained("google/efficientnet-b7"							).to(__lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		List[str]  			=							self.default_image_processor
            _SCREAMING_SNAKE_CASE				:		int  			=							prepare_img()
            _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							image_processor(images=__lowerCamelCase			,  return_tensors="pt"							).to(__lowerCamelCase							)

            # forward pass
            with torch.no_grad():
                 _SCREAMING_SNAKE_CASE				:		Optional[Any]  			=							model(**__lowerCamelCase							)

            # verify the logits
            _SCREAMING_SNAKE_CASE				:		int  			=							torch.Size((1, 1_0_0_0)							)
            self.assertEqual(outputs.logits.shape			,  __lowerCamelCase							)

            _SCREAMING_SNAKE_CASE				:		str  			=							torch.tensor([0.0001, 0.0002, 0.0002]							).to(__lowerCamelCase							)
            self.assertTrue(torch.allclose(outputs.logits[0, :3]			,  __lowerCamelCase			,  atol=1E-4							)							)






# as due to their complexity multi-gpu tests could impact other tests, and to aid debug we have those in a separate module.

import os
import sys

from transformers.testing_utils import TestCasePlus, execute_subprocess_async, get_gpu_count, require_torch_gpu, slow

from .utils import load_json





class 	lowerCAmelCase__(       __lowercase			):






       '''simple docstring'''


       @classmethod
       def 			UpperCamelCase_	(					cls							)	->   Tuple:
            return cls







       @slow
       @require_torch_gpu
       def 			UpperCamelCase_	(					self							)	->   Any:
            _SCREAMING_SNAKE_CASE				:		List[str]  			=							self.get_auto_remove_tmp_dir()
            _SCREAMING_SNAKE_CASE				:		List[Any]  			=							F"""
            --model_name Helsinki-NLP/opus-mt-en-ro
            --save_dir {output_dir}
            --data_dir {self.test_file_dir_str}/test_data/wmt_en_ro
            --num_beams 2
            --task translation
        """.split()

            # we want this test to run even if there is only one GPU, but if there are more we use them all
            _SCREAMING_SNAKE_CASE				:		List[str]  			=							get_gpu_count()
            _SCREAMING_SNAKE_CASE				:		Union[str, Any]  			=							F"""
            -m torch.distributed.launch
            --nproc_per_node={n_gpu}
            {self.test_file_dir}/run_distributed_eval.py
        """.split()
            _SCREAMING_SNAKE_CASE				:		int  			=							[sys.executable] + distributed_args + args
            execute_subprocess_async(__lowerCamelCase			,  env=self.get_env()							)

            _SCREAMING_SNAKE_CASE				:		Optional[int]  			=							os.path.join(__lowerCamelCase			,  "test_bleu.json"							)
            _SCREAMING_SNAKE_CASE				:		List[str]  			=							load_json(__lowerCamelCase							)
            # print(metrics)
            self.assertGreaterEqual(metrics["bleu"]			,  2_5							)