





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    ,							UpperCAmelCase    ,							UpperCAmelCase=13    ,							UpperCAmelCase=32    ,							UpperCAmelCase=3    ,							UpperCAmelCase=[3, 3, 5]    ,							UpperCAmelCase=[32, 16, 24]    ,							UpperCAmelCase=[16, 24, 40]    ,							UpperCAmelCase=[1, 1, 2]    ,							UpperCAmelCase=[1, 1, 2]    ,							UpperCAmelCase=[1, 6, 6]    ,							UpperCAmelCase=True    ,							UpperCAmelCase=True    ,							UpperCAmelCase=37    ,							UpperCAmelCase="gelu"    ,							UpperCAmelCase=10    ,							)->   Optional[Any]:
     __A    =  parent
     __A    =  batch_size
     __A    =  image_size
     __A    =  num_channels
     __A    =  kernel_sizes
     __A    =  in_channels
     __A    =  out_channels
     __A    =  strides
     __A    =  num_block_repeats
     __A    =  expand_ratios
     __A    =  is_training
     __A    =  hidden_act
     __A    =  num_labels
     __A    =  use_labels

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   List[str]:
     __A    =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

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

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   str:
     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 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase      )->   str:
     __A    =  EfficientNetModel(config=UpperCAmelCase      )
     model.to(UpperCAmelCase      )
     model.eval()
     __A    =  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 						SCREAMING_SNAKE_CASE__			(   self    ,							UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase      )->   Dict:
     __A    =  EfficientNetForImageClassification(UpperCAmelCase      )
     model.to(UpperCAmelCase      )
     model.eval()
     __A    =  model(UpperCAmelCase    ,							labels=UpperCAmelCase      )
     self.parent.assertEqual(result.logits.shape    ,							(self.batch_size, self.num_labels)      )





  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Union[str, Any]:
     __A    =  self.prepare_config_and_inputs()
     __A    =  config_and_inputs
     __A    =  {"""pixel_values""": pixel_values}
     return config, inputs_dict







@require_torch
class 		_lowerCAmelCase(		_lowerCAmelCase						,       _lowerCAmelCase						,       unittest.TestCase):

  """simple docstring"""







  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 						SCREAMING_SNAKE_CASE__			(   self      )->   int:
     __A    =  EfficientNetModelTester(self      )
     __A    =  ConfigTester(
         self    ,							config_class=UpperCAmelCase    ,							has_text_modality=UpperCAmelCase    ,							hidden_size=37      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   List[Any]:
     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 						SCREAMING_SNAKE_CASE__			(   self      )->   List[str]:
     return

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

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

  @unittest.skip(reason='''EfficientNet does not use feedforward chunking'''      )
  def 						SCREAMING_SNAKE_CASE__			(   self      )->   List[str]:
     pass

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Optional[Any]:
     __A    =  self.model_tester.prepare_config_and_inputs_for_common()

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

        __A    =  ["""pixel_values"""]
        self.assertListEqual(arg_names[:1]    ,							UpperCAmelCase      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   List[str]:
     __A    =  self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*UpperCAmelCase      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   List[Any]:
     def check_hidden_states_output(UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase      ):
        __A    =  model_class(UpperCAmelCase      )
        model.to(UpperCAmelCase      )
        model.eval()

        with torch.no_grad():
           __A    =  model(**self._prepare_for_class(UpperCAmelCase    ,							UpperCAmelCase      )      )

        __A    =  outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states
        __A    =  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]    ,							)

     __A    =  self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
        __A    =  True
        check_hidden_states_output(UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase      )

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

        check_hidden_states_output(UpperCAmelCase    ,							UpperCAmelCase    ,							UpperCAmelCase      )

  def 						SCREAMING_SNAKE_CASE__			(   self      )->   str:
     __A    =  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 						SCREAMING_SNAKE_CASE__			(   self      )->   str:
     pass

  @slow
  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Optional[Any]:
     for model_name in EFFICIENTNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        __A    =  EfficientNetModel.from_pretrained(UpperCAmelCase      )
        self.assertIsNotNone(UpperCAmelCase      )





  @is_pipeline_test
  @require_vision
  @slow
  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Dict:
     super().test_pipeline_image_classification()
def  __UpperCamelCase    (						)    ->		Optional[Any]:


   '''simple docstring'''







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







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

  """simple docstring"""







  @cached_property
  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Optional[int]:
     return AutoImageProcessor.from_pretrained('''google/efficientnet-b7'''      ) if is_vision_available() else None





  @slow
  def 						SCREAMING_SNAKE_CASE__			(   self      )->   Optional[int]:
     __A    =  EfficientNetForImageClassification.from_pretrained('''google/efficientnet-b7'''      ).to(UpperCAmelCase      )

     __A    =  self.default_image_processor
     __A    =  prepare_img()
     __A    =  image_processor(images=UpperCAmelCase    ,							return_tensors='''pt'''      ).to(UpperCAmelCase      )

     # forward pass
     with torch.no_grad():
        __A    =  model(**UpperCAmelCase      )

     # verify the logits
     __A    =  torch.Size((1, 10_00)      )
     self.assertEqual(outputs.logits.shape    ,							UpperCAmelCase      )

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






"""simple docstring"""
import importlib
import sys
from argparse import REMAINDER, ArgumentParser
from pathlib import Path

import torch_xla.distributed.xla_multiprocessing as xmp
def   A_    (     ):







						'''simple docstring'''


						snake_case_					:str		=     ArgumentParser(
						    description=(
						        """PyTorch TPU distributed training launch helper utility that will spawn up multiple distributed processes"""
						    )      )

						# Optional arguments for the launch helper
						parser.add_argument("""--num_cores""",   type=_lowercase,   default=1,   help="""Number of TPU cores to use (1 or 8)."""      )

						# positional
						parser.add_argument(
						    """training_script""",   type=_lowercase,   help=(
						        """The full path to the single TPU training """
						        """program/script to be launched in parallel, """
						        """followed by all the arguments for the """
						        """training script"""
						    ),   )

						# rest from the training program
						parser.add_argument("""training_script_args""",   nargs=_lowercase      )

						return parser.parse_args()
def   A_    (     ):







						'''simple docstring'''


						snake_case_					:Any		=     parse_args()

						# Import training_script as a module.
						snake_case_					:str		=     Path(args.training_script      )
						sys.path.append(str(script_fpath.parent.resolve()      )      )
						snake_case_					:Dict		=     script_fpath.stem
						snake_case_					:int		=     importlib.import_module(_lowercase      )

						# Patch sys.argv
						snake_case_					:Optional[Any]		=     [args.training_script] + args.training_script_args + ["""--tpu_num_cores""", str(args.num_cores      )]

						xmp.spawn(mod._mp_fn,   args=(),   nprocs=args.num_cores      )


if __name__ == "__main__":
						main()
