
import inspect
import unittest

from transformers import MobileNetVaConfig
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_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 MobileNetVaForImageClassification, MobileNetVaModel
    from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import MobileNetVaImageProcessor




class        UpperCAmelCase_			( _A     ):


  '''simple docstring'''







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







    """simple docstring"""






    __magic_name__				     =       self.config_class(**self.inputs_dict    )
    self.parent.assertTrue(hasattr(UpperCamelCase__			,							"""tf_padding"""    )    )
    self.parent.assertTrue(hasattr(UpperCamelCase__			,							"""depth_multiplier"""    )    )







class        UpperCAmelCase_			:


  '''simple docstring'''







  def __init__( self			: Dict			,							UpperCamelCase__			: str			,							UpperCamelCase__			: Any=13			,							UpperCamelCase__			: Optional[int]=3			,							UpperCamelCase__			: str=32			,							UpperCamelCase__			: Any=0.25			,							UpperCamelCase__			: Union[str, Any]=8			,							UpperCamelCase__			: Tuple=True			,							UpperCamelCase__			: int=1024			,							UpperCamelCase__			: str=32			,							UpperCamelCase__			: List[Any]="relu6"			,							UpperCamelCase__			: Any=0.1			,							UpperCamelCase__			: Dict=0.02			,							UpperCamelCase__			: Optional[int]=True			,							UpperCamelCase__			: Optional[Any]=True			,							UpperCamelCase__			: List[Any]=10			,							UpperCamelCase__			: Optional[Any]=None			,							)			->	int:







    """simple docstring"""






    __magic_name__				     =       parent
    __magic_name__				     =       batch_size
    __magic_name__				     =       num_channels
    __magic_name__				     =       image_size
    __magic_name__				     =       depth_multiplier
    __magic_name__				     =       min_depth
    __magic_name__				     =       tf_padding
    __magic_name__				     =       int(last_hidden_size * depth_multiplier    )
    __magic_name__				     =       output_stride
    __magic_name__				     =       hidden_act
    __magic_name__				     =       classifier_dropout_prob
    __magic_name__				     =       use_labels
    __magic_name__				     =       is_training
    __magic_name__				     =       num_labels
    __magic_name__				     =       initializer_range
    __magic_name__				     =       scope
  def 							_lowercase							( self			: List[str]    )			->	Dict:







    """simple docstring"""






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

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

    __magic_name__				     =       self.get_config()

    return config, pixel_values, labels, pixel_labels
  def 							_lowercase							( self			: int    )			->	int:







    """simple docstring"""






    return MobileNetVaConfig(
        num_channels=self.num_channels			,							image_size=self.image_size			,							depth_multiplier=self.depth_multiplier			,							min_depth=self.min_depth			,							tf_padding=self.tf_padding			,							hidden_act=self.hidden_act			,							classifier_dropout_prob=self.classifier_dropout_prob			,							initializer_range=self.initializer_range			,							)
  def 							_lowercase							( self			: List[str]			,							UpperCamelCase__			: List[Any]			,							UpperCamelCase__			: Union[str, Any]			,							UpperCamelCase__			: List[str]			,							UpperCamelCase__			: Optional[Any]    )			->	Tuple:







    """simple docstring"""






    __magic_name__				     =       MobileNetVaModel(config=UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()
    __magic_name__				     =       model(UpperCamelCase__    )
    self.parent.assertEqual(
        result.last_hidden_state.shape			,							(
            self.batch_size,
            self.last_hidden_size,
            self.image_size // self.output_stride,
            self.image_size // self.output_stride,
        )			,							)
  def 							_lowercase							( self			: Any			,							UpperCamelCase__			: Any			,							UpperCamelCase__			: Dict			,							UpperCamelCase__			: Dict			,							UpperCamelCase__			: Tuple    )			->	Dict:







    """simple docstring"""






    __magic_name__				     =       self.num_labels
    __magic_name__				     =       MobileNetVaForImageClassification(UpperCamelCase__    )
    model.to(UpperCamelCase__    )
    model.eval()
    __magic_name__				     =       model(UpperCamelCase__			,							labels=UpperCamelCase__    )
    self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.num_labels)    )





  def 							_lowercase							( self			: Optional[int]    )			->	str:







    """simple docstring"""






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







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


  '''simple docstring'''







  a__           =		(MobileNetVaModel, MobileNetVaForImageClassification) if is_torch_available() else ()
  a__           =		(
      {"""feature-extraction""": MobileNetVaModel, """image-classification""": MobileNetVaForImageClassification}
      if is_torch_available()
      else {}
  )

  a__           =		False
  a__           =		False
  a__           =		False
  a__           =		False
  def 							_lowercase							( self			: List[str]    )			->	List[Any]:







    """simple docstring"""






    __magic_name__				     =       MobileNetVaModelTester(self    )
    __magic_name__				     =       MobileNetVaConfigTester(self			,							config_class=UpperCamelCase__			,							has_text_modality=UpperCamelCase__    )
  def 							_lowercase							( self			: str    )			->	str:







    """simple docstring"""






    self.config_tester.run_common_tests()
  @unittest.skip(reason="""MobileNetV1 does not use inputs_embeds"""    )
  def 							_lowercase							( self			: List[str]    )			->	Optional[int]:







    """simple docstring"""






    pass
  @unittest.skip(reason="""MobileNetV1 does not support input and output embeddings"""    )
  def 							_lowercase							( self			: List[str]    )			->	Tuple:







    """simple docstring"""






    pass
  @unittest.skip(reason="""MobileNetV1 does not output attentions"""    )
  def 							_lowercase							( self			: Union[str, Any]    )			->	Tuple:







    """simple docstring"""






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







    """simple docstring"""






    __magic_name__     ,    __magic_name__				     =       self.model_tester.prepare_config_and_inputs_for_common()

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

      __magic_name__				     =       ["""pixel_values"""]
      self.assertListEqual(arg_names[:1]			,							UpperCamelCase__    )
  def 							_lowercase							( self			: List[Any]    )			->	int:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*UpperCamelCase__    )
  def 							_lowercase							( self			: Optional[Any]    )			->	Optional[int]:







    """simple docstring"""






    def check_hidden_states_output(UpperCamelCase__			: Dict			,							UpperCamelCase__			: int			,							UpperCamelCase__			: Dict    ):
      __magic_name__				     =       model_class(UpperCamelCase__    )
      model.to(UpperCamelCase__    )
      model.eval()

      with torch.no_grad():
        __magic_name__				     =       model(**self._prepare_for_class(UpperCamelCase__			,							UpperCamelCase__    )    )

      __magic_name__				     =       outputs.hidden_states

      __magic_name__				     =       26
      self.assertEqual(len(UpperCamelCase__    )			,							UpperCamelCase__    )

    __magic_name__     ,    __magic_name__				     =       self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
      __magic_name__				     =       True
      check_hidden_states_output(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__    )

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

      check_hidden_states_output(UpperCamelCase__			,							UpperCamelCase__			,							UpperCamelCase__    )
  def 							_lowercase							( self			: Optional[Any]    )			->	List[Any]:







    """simple docstring"""






    __magic_name__				     =       self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*UpperCamelCase__    )





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







    """simple docstring"""






    for model_name in MOBILENET_V1_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      __magic_name__				     =       MobileNetVaModel.from_pretrained(UpperCamelCase__    )
      self.assertIsNotNone(UpperCamelCase__    )







def a__    (       ):






  '''simple docstring'''





  __magic_name__				     =       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
  return image





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


  '''simple docstring'''







  @cached_property
  def 							_lowercase							( self			: int    )			->	str:







    """simple docstring"""






    return (
        MobileNetVaImageProcessor.from_pretrained("""google/mobilenet_v1_1.0_224"""    ) if is_vision_available() else None
    )





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







    """simple docstring"""






    __magic_name__				     =       MobileNetVaForImageClassification.from_pretrained("""google/mobilenet_v1_1.0_224"""    ).to(UpperCamelCase__    )

    __magic_name__				     =       self.default_image_processor
    __magic_name__				     =       prepare_img()
    __magic_name__				     =       image_processor(images=UpperCamelCase__			,							return_tensors="""pt"""    ).to(UpperCamelCase__    )

    # forward pass
    with torch.no_grad():
      __magic_name__				     =       model(**UpperCamelCase__    )

    # verify the logits
    __magic_name__				     =       torch.Size((1, 1001)    )
    self.assertEqual(outputs.logits.shape			,							UpperCamelCase__    )

    __magic_name__				     =       torch.tensor([-4.1739, -1.1233, 3.1205]    ).to(UpperCamelCase__    )

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



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





  __magic_name__				     =       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=A_,     default=1,     help="""Number of TPU cores to use (1 or 8)."""					)

  # positional
  parser.add_argument(
      """training_script""",     type=A_,     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=A_					)

  return parser.parse_args()

def a__    (       ):






  '''simple docstring'''





  __magic_name__				     =       parse_args()

  # Import training_script as a module.
  __magic_name__				     =       Path(args.training_script					)
  sys.path.append(str(script_fpath.parent.resolve()					)					)
  __magic_name__				     =       script_fpath.stem
  __magic_name__				     =       importlib.import_module(A_					)

  # Patch sys.argv
  __magic_name__				     =       [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()

