


'''simple docstring'''







import asyncio
import os
import shutil
import subprocess
import sys
import tempfile
import unittest
from distutils.util import strtobool
from functools import partial
from pathlib import Path
from typing import List, Union
from unittest import mock

import torch

from ..state import AcceleratorState, PartialState
from ..utils import (
    gather,
    is_bnb_available,
    is_comet_ml_available,
    is_datasets_available,
    is_deepspeed_available,
    is_mps_available,
    is_safetensors_available,
    is_tensorboard_available,
    is_torch_version,
    is_tpu_available,
    is_transformers_available,
    is_wandb_available,
    is_xpu_available,
)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE					,	__SCREAMING_SNAKE_CASE=False		)					->       str:
     """simple docstring"""




     try:
          __a   			= os.environ[key]
     except KeyError:
          # KEY isn't set, default to `default`.
          __a   			= default
     else:
          # KEY is set, convert it to True or False.
          try:
               __a   			= strtobool(__SCREAMING_SNAKE_CASE		)
          except ValueError:
               # More values are supported, but let's keep the message simple.
               raise ValueError(F'''If set, {key} must be yes or no.'''		)
     return _value


SCREAMING_SNAKE_CASE_   =      parse_flag_from_env('RUN_SLOW', default=False)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       Union[str, Any]:
     """simple docstring"""




     return unittest.skip("""Test was skipped"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       Union[str, Any]:
     """simple docstring"""




     return unittest.skipUnless(_run_slow_tests					,	"""test is slow"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       Union[str, Any]:
     """simple docstring"""




     return unittest.skipUnless(not torch.cuda.is_available()					,	"""test requires only a CPU"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       str:
     """simple docstring"""




     return unittest.skipUnless(torch.cuda.is_available()					,	"""test requires a GPU"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       int:
     """simple docstring"""




     return unittest.skipUnless(is_xpu_available()					,	"""test requires a XPU"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       int:
     """simple docstring"""




     return unittest.skipUnless(is_mps_available()					,	"""test requires a `mps` backend support in `torch`"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       Union[str, Any]:
     """simple docstring"""




     return unittest.skipUnless(
         is_transformers_available() and is_datasets_available()					,	"""test requires the Hugging Face suite"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       Tuple:
     """simple docstring"""




     return unittest.skipUnless(is_bnb_available()					,	"""test requires the bitsandbytes library"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       List[str]:
     """simple docstring"""




     return unittest.skipUnless(is_tpu_available()					,	"""test requires TPU"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       Dict:
     """simple docstring"""




     return unittest.skipUnless(torch.cuda.device_count() == 1					,	"""test requires a GPU"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       int:
     """simple docstring"""




     return unittest.skipUnless(torch.xpu.device_count() == 1					,	"""test requires a XPU"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       Optional[Any]:
     """simple docstring"""




     return unittest.skipUnless(torch.cuda.device_count() > 1					,	"""test requires multiple GPUs"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       Union[str, Any]:
     """simple docstring"""




     return unittest.skipUnless(torch.xpu.device_count() > 1					,	"""test requires multiple XPUs"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       Optional[int]:
     """simple docstring"""




     return unittest.skipUnless(is_safetensors_available()					,	"""test requires safetensors"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       Tuple:
     """simple docstring"""




     return unittest.skipUnless(is_deepspeed_available()					,	"""test requires DeepSpeed"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       Tuple:
     """simple docstring"""




     return unittest.skipUnless(is_torch_version(""">="""					,	"""1.12.0"""		)					,	"""test requires torch version >= 1.12.0"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE=None					,	__SCREAMING_SNAKE_CASE=None		)					->       Tuple:
     """simple docstring"""




     if test_case is None:
          return partial(__SCREAMING_SNAKE_CASE					,	version=__SCREAMING_SNAKE_CASE		)
     return unittest.skipUnless(is_torch_version(""">="""					,	__SCREAMING_SNAKE_CASE		)					,	F'''test requires torch version >= {version}'''		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       Tuple:
     """simple docstring"""




     return unittest.skipUnless(is_tensorboard_available()					,	"""test requires Tensorboard"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       Union[str, Any]:
     """simple docstring"""




     return unittest.skipUnless(is_wandb_available()					,	"""test requires wandb"""		)(__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       Union[str, Any]:
     """simple docstring"""




     return unittest.skipUnless(is_comet_ml_available()					,	"""test requires comet_ml"""		)(__SCREAMING_SNAKE_CASE		)


SCREAMING_SNAKE_CASE_   =      (
    any([is_wandb_available(), is_tensorboard_available()]) and not is_comet_ml_available()
)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       Any:
     """simple docstring"""




     return unittest.skipUnless(
         _atleast_one_tracker_available					,	"""test requires at least one tracker to be available and for `comet_ml` to not be installed"""					,	)(__SCREAMING_SNAKE_CASE		)


class 			lowerCAmelCase_    (							unittest.TestCase   ):





  """simple docstring"""



  a_							:int				       =True

  @classmethod
  def __a    (       cls  :				Optional[Any]    ):





       '''simple docstring'''

       __a   			= tempfile.mkdtemp()

  @classmethod
  def __a    (       cls  :				Tuple    ):





       '''simple docstring'''

       if os.path.exists(cls.tmpdir    ):
            shutil.rmtree(cls.tmpdir    )


  def __a    (       self  :				List[Any]    ):





       '''simple docstring'''

       if self.clear_on_setup:
            for path in Path(self.tmpdir    ).glob("""**/*"""    ):
                 if path.is_file():
                      path.unlink()
                 elif path.is_dir():
                      shutil.rmtree(__lowerCamelCase    )


class 			lowerCAmelCase_    (							unittest.TestCase   ):





  """simple docstring"""



  def __a    (       self  :				Any    ):





       '''simple docstring'''

       super().tearDown()
       # Reset the state of the AcceleratorState singleton.
       AcceleratorState._reset_state()
       PartialState._reset_state()


class 			lowerCAmelCase_    (							unittest.TestCase   ):





  """simple docstring"""



  def __a    (       self  :				Dict					,				SCREAMING_SNAKE_CASE__  :				Union[mock.Mock, List[mock.Mock]]    ):





       '''simple docstring'''

       __a   			= mocks if isinstance(__lowerCamelCase					,				(tuple, list)    ) else [mocks]
       for m in self.mocks:
            m.start()
            self.addCleanup(m.stop    )




def 							__lowercase    (   __SCREAMING_SNAKE_CASE		)					->       Optional[Any]:
     """simple docstring"""




     __a   			= AcceleratorState()
     __a   			= tensor[None].clone().to(state.device		)
     __a   			= gather(__SCREAMING_SNAKE_CASE		).cpu()
     __a   			= tensor[0].cpu()
     for i in range(tensors.shape[0]		):
          if not torch.equal(tensors[i]					,	__SCREAMING_SNAKE_CASE		):
               return False
     return True


class 			lowerCAmelCase_    :





  """simple docstring"""



  def __init__(       self  :				Optional[Any]					,				SCREAMING_SNAKE_CASE__  :				List[Any]					,				SCREAMING_SNAKE_CASE__  :				Tuple					,				SCREAMING_SNAKE_CASE__  :				Any    ):





       '''simple docstring'''

       __a   			= returncode
       __a   			= stdout
       __a   			= stderr




async def 							__lowercase    (   __SCREAMING_SNAKE_CASE					,	__SCREAMING_SNAKE_CASE		)					->       int:
     """simple docstring"""




     while True:
          __a   			= await stream.readline()
          if line:
               callback(__SCREAMING_SNAKE_CASE		)
          else:
               break




async def 							__lowercase    (   __SCREAMING_SNAKE_CASE					,	__SCREAMING_SNAKE_CASE=None					,	__SCREAMING_SNAKE_CASE=None					,	__SCREAMING_SNAKE_CASE=None					,	__SCREAMING_SNAKE_CASE=False					,	__SCREAMING_SNAKE_CASE=False		)					->       _RunOutput:
     """simple docstring"""




     if echo:
          print("""\nRunning: """					,	""" """.join(__SCREAMING_SNAKE_CASE		)		)

     __a   			= await asyncio.create_subprocess_exec(
         cmd[0]					,	*cmd[1:]					,	stdin=__SCREAMING_SNAKE_CASE					,	stdout=asyncio.subprocess.PIPE					,	stderr=asyncio.subprocess.PIPE					,	env=__SCREAMING_SNAKE_CASE					,	)

     # note: there is a warning for a possible deadlock when using `wait` with huge amounts of data in the pipe
     # https://docs.python.org/3/library/asyncio-subprocess.html#asyncio.asyncio.subprocess.Process.wait
     #
     # If it starts hanging, will need to switch to the following code. The problem is that no data
     # will be seen until it's done and if it hangs for example there will be no debug info.
     # out, err = await p.communicate()
     # return _RunOutput(p.returncode, out, err)

     __a   			= []
     __a   			= []

     def tee(__SCREAMING_SNAKE_CASE					,	__SCREAMING_SNAKE_CASE					,	__SCREAMING_SNAKE_CASE					,	__SCREAMING_SNAKE_CASE=""		):
          __a   			= line.decode("""utf-8"""		).rstrip()
          sink.append(__SCREAMING_SNAKE_CASE		)
          if not quiet:
               print(__SCREAMING_SNAKE_CASE					,	__SCREAMING_SNAKE_CASE					,	file=__SCREAMING_SNAKE_CASE		)

    # XXX: the timeout doesn't seem to make any difference here
     await asyncio.wait(
         [
             asyncio.create_task(_read_stream(p.stdout					,	lambda __SCREAMING_SNAKE_CASE		: tee(__SCREAMING_SNAKE_CASE					,	__SCREAMING_SNAKE_CASE					,	sys.stdout					,	label="""stdout:"""		)		)		),
             asyncio.create_task(_read_stream(p.stderr					,	lambda __SCREAMING_SNAKE_CASE		: tee(__SCREAMING_SNAKE_CASE					,	__SCREAMING_SNAKE_CASE					,	sys.stderr					,	label="""stderr:"""		)		)		),
         ]					,	timeout=__SCREAMING_SNAKE_CASE					,	)
     return _RunOutput(await p.wait()					,	__SCREAMING_SNAKE_CASE					,	__SCREAMING_SNAKE_CASE		)




def 							__lowercase    (   __SCREAMING_SNAKE_CASE					,	__SCREAMING_SNAKE_CASE=None					,	__SCREAMING_SNAKE_CASE=None					,	__SCREAMING_SNAKE_CASE=180					,	__SCREAMING_SNAKE_CASE=False					,	__SCREAMING_SNAKE_CASE=True		)					->       _RunOutput:
     """simple docstring"""




     __a   			= asyncio.get_event_loop()
     __a   			= loop.run_until_complete(
         _stream_subprocess(__SCREAMING_SNAKE_CASE					,	env=__SCREAMING_SNAKE_CASE					,	stdin=__SCREAMING_SNAKE_CASE					,	timeout=__SCREAMING_SNAKE_CASE					,	quiet=__SCREAMING_SNAKE_CASE					,	echo=__SCREAMING_SNAKE_CASE		)		)

     __a   			= ' '.join(__SCREAMING_SNAKE_CASE		)
     if result.returncode > 0:
          __a   			= '\n'.join(result.stderr		)
          raise RuntimeError(
              F'''\'{cmd_str}\' failed with returncode {result.returncode}\n\n'''
              F'''The combined stderr from workers follows:\n{stderr}'''		)

     return result


class 			lowerCAmelCase_    (							lowerCAmelCase_   ):





  """simple docstring"""



  pass




def 							__lowercase    (   __SCREAMING_SNAKE_CASE					,	__SCREAMING_SNAKE_CASE=False		)					->       Optional[Any]:
     """simple docstring"""




     try:
          __a   			= subprocess.check_output(__SCREAMING_SNAKE_CASE					,	stderr=subprocess.STDOUT		)
          if return_stdout:
               if hasattr(__SCREAMING_SNAKE_CASE					,	"""decode"""		):
                    __a   			= output.decode("""utf-8"""		)
               return output
     except subprocess.CalledProcessError as e:
          raise SubprocessCallException(
              F'''Command `{' '.join(__SCREAMING_SNAKE_CASE		)}` failed with the following error:\n\n{e.output.decode()}'''		) from e












'''simple docstring'''






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, MobileNetVaForSemanticSegmentation, MobileNetVaModel
      from transformers.models.mobilenet_va.modeling_mobilenet_va import MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import MobileNetVaImageProcessor






class        lowercase_      (						lowerCAmelCase_							):





     def 			_lowerCAmelCase      (     self     :					Any			):
           snake_case__       :   Union[str, Any]	      =    self.config_class(**self.inputs_dict			)
           self.parent.assertTrue(hasattr(__lowerCamelCase     ,							'tf_padding'			)			)
           self.parent.assertTrue(hasattr(__lowerCamelCase     ,							'depth_multiplier'			)			)






class        lowercase_      :





     def __init__(     self     :					Optional[int]     ,							__lowerCamelCase     :					Optional[Any]     ,							__lowerCamelCase     :					Dict=13     ,							__lowerCamelCase     :					Optional[Any]=3     ,							__lowerCamelCase     :					str=32     ,							__lowerCamelCase     :					str=0.2_5     ,							__lowerCamelCase     :					List[Any]=8     ,							__lowerCamelCase     :					List[Any]=8     ,							__lowerCamelCase     :					Union[str, Any]=6     ,							__lowerCamelCase     :					Optional[Any]=32     ,							__lowerCamelCase     :					Dict=True     ,							__lowerCamelCase     :					str=True     ,							__lowerCamelCase     :					int=True     ,							__lowerCamelCase     :					Tuple="relu6"     ,							__lowerCamelCase     :					List[str]=1280     ,							__lowerCamelCase     :					Optional[Any]=0.1     ,							__lowerCamelCase     :					Tuple=0.0_2     ,							__lowerCamelCase     :					str=True     ,							__lowerCamelCase     :					int=True     ,							__lowerCamelCase     :					int=10     ,							__lowerCamelCase     :					int=None     ,							):
           snake_case__       :   Dict	      =    parent
           snake_case__       :   Union[str, Any]	      =    batch_size
           snake_case__       :   List[Any]	      =    num_channels
           snake_case__       :   List[str]	      =    image_size
           snake_case__       :   Optional[int]	      =    depth_multiplier
           snake_case__       :   int	      =    depth_divisible_by
           snake_case__       :   List[Any]	      =    min_depth
           snake_case__       :   Dict	      =    expand_ratio
           snake_case__       :   Optional[Any]	      =    tf_padding
           snake_case__       :   List[Any]	      =    output_stride
           snake_case__       :   List[str]	      =    first_layer_is_expansion
           snake_case__       :   Optional[Any]	      =    finegrained_output
           snake_case__       :   int	      =    hidden_act
           snake_case__       :   List[Any]	      =    last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier			)
           snake_case__       :   List[str]	      =    classifier_dropout_prob
           snake_case__       :   List[Any]	      =    use_labels
           snake_case__       :   Tuple	      =    is_training
           snake_case__       :   Dict	      =    num_labels
           snake_case__       :   Any	      =    initializer_range
           snake_case__       :   int	      =    scope





     def 			_lowerCAmelCase      (     self     :					int			):
           snake_case__       :   int	      =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

           snake_case__       :   Optional[int]	      =    None
           snake_case__       :   Optional[int]	      =    None
           if self.use_labels:
                 snake_case__       :   Dict	      =    ids_tensor([self.batch_size]     ,							self.num_labels			)
                 snake_case__       :   List[str]	      =    ids_tensor([self.batch_size, self.image_size, self.image_size]     ,							self.num_labels			)

           snake_case__       :   List[Any]	      =    self.get_config()

           return config, pixel_values, labels, pixel_labels





     def 			_lowerCAmelCase      (     self     :					Tuple			):
           return MobileNetVaConfig(
               num_channels=self.num_channels     ,							image_size=self.image_size     ,							depth_multiplier=self.depth_multiplier     ,							depth_divisible_by=self.depth_divisible_by     ,							min_depth=self.min_depth     ,							expand_ratio=self.expand_ratio     ,							output_stride=self.output_stride     ,							first_layer_is_expansion=self.first_layer_is_expansion     ,							finegrained_output=self.finegrained_output     ,							hidden_act=self.hidden_act     ,							tf_padding=self.tf_padding     ,							classifier_dropout_prob=self.classifier_dropout_prob     ,							initializer_range=self.initializer_range     ,							)





     def 			_lowerCAmelCase      (     self     :					Dict     ,							__lowerCamelCase     :					str     ,							__lowerCamelCase     :					int     ,							__lowerCamelCase     :					Dict     ,							__lowerCamelCase     :					Union[str, Any]			):
           snake_case__       :   Optional[Any]	      =    MobileNetVaModel(config=__lowerCamelCase			)
           model.to(__lowerCamelCase			)
           model.eval()
           snake_case__       :   List[Any]	      =    model(__lowerCamelCase			)
           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,
               )     ,							)
           self.parent.assertEqual(
               result.pooler_output.shape     ,							(self.batch_size, self.last_hidden_size)     ,							)





     def 			_lowerCAmelCase      (     self     :					str     ,							__lowerCamelCase     :					str     ,							__lowerCamelCase     :					Optional[int]     ,							__lowerCamelCase     :					Optional[int]     ,							__lowerCamelCase     :					Dict			):
           snake_case__       :   Optional[int]	      =    self.num_labels
           snake_case__       :   int	      =    MobileNetVaForImageClassification(__lowerCamelCase			)
           model.to(__lowerCamelCase			)
           model.eval()
           snake_case__       :   int	      =    model(__lowerCamelCase     ,							labels=__lowerCamelCase			)
           self.parent.assertEqual(result.logits.shape     ,							(self.batch_size, self.num_labels)			)





     def 			_lowerCAmelCase      (     self     :					Dict     ,							__lowerCamelCase     :					int     ,							__lowerCamelCase     :					Dict     ,							__lowerCamelCase     :					Optional[int]     ,							__lowerCamelCase     :					Union[str, Any]			):
           snake_case__       :   Tuple	      =    self.num_labels
           snake_case__       :   Optional[Any]	      =    MobileNetVaForSemanticSegmentation(__lowerCamelCase			)
           model.to(__lowerCamelCase			)
           model.eval()
           snake_case__       :   Optional[Any]	      =    model(__lowerCamelCase			)
           self.parent.assertEqual(
               result.logits.shape     ,							(
                   self.batch_size,
                   self.num_labels,
                   self.image_size // self.output_stride,
                   self.image_size // self.output_stride,
               )     ,							)
           snake_case__       :   Dict	      =    model(__lowerCamelCase     ,							labels=__lowerCamelCase			)
           self.parent.assertEqual(
               result.logits.shape     ,							(
                   self.batch_size,
                   self.num_labels,
                   self.image_size // self.output_stride,
                   self.image_size // self.output_stride,
               )     ,							)





     def 			_lowerCAmelCase      (     self     :					Any			):
           snake_case__       :   List[Any]	      =    self.prepare_config_and_inputs()
           snake_case__      ,							snake_case__      ,							snake_case__      ,							snake_case__       :   str	      =    config_and_inputs
           snake_case__       :   Union[str, Any]	      =    {'pixel_values': pixel_values}
           return config, inputs_dict






@require_torch
class        lowercase_      (						lowerCAmelCase_						,       lowerCAmelCase_						,       unittest.TestCase							):
     A_											=			(
         (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
         if is_torch_available()
         else ()
     )
     A_											=			(
         {
             "feature-extraction": MobileNetVaModel,
             "image-classification": MobileNetVaForImageClassification,
             "image-segmentation": MobileNetVaForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )

     A_											=			False
     A_											=			False
     A_											=			False
     A_											=			False





     def 			_lowerCAmelCase      (     self     :					Dict			):
           snake_case__       :   List[Any]	      =    MobileNetVaModelTester(self			)
           snake_case__       :   str	      =    MobileNetVaConfigTester(self     ,							config_class=__lowerCamelCase     ,							has_text_modality=__lowerCamelCase			)





     def 			_lowerCAmelCase      (     self     :					Any			):
           self.config_tester.run_common_tests()





     @unittest.skip(reason='MobileNetV2 does not use inputs_embeds'			)
     def 			_lowerCAmelCase      (     self     :					Union[str, Any]			):
           pass





     @unittest.skip(reason='MobileNetV2 does not support input and output embeddings'			)
     def 			_lowerCAmelCase      (     self     :					int			):
           pass





     @unittest.skip(reason='MobileNetV2 does not output attentions'			)
     def 			_lowerCAmelCase      (     self     :					Tuple			):
           pass





     def 			_lowerCAmelCase      (     self     :					Any			):
           snake_case__      ,							snake_case__       :   Any	      =    self.model_tester.prepare_config_and_inputs_for_common()

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

                 snake_case__       :   int	      =    ['pixel_values']
                 self.assertListEqual(arg_names[:1]     ,							__lowerCamelCase			)





     def 			_lowerCAmelCase      (     self     :					List[str]			):
           snake_case__       :   str	      =    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*__lowerCamelCase			)





     def 			_lowerCAmelCase      (     self     :					Tuple			):
           def check_hidden_states_output(__lowerCamelCase     :					str     ,							__lowerCamelCase     :					List[str]     ,							__lowerCamelCase     :					List[str]			):
                 snake_case__       :   Tuple	      =    model_class(__lowerCamelCase			)
                 model.to(__lowerCamelCase			)
                 model.eval()

                 with torch.no_grad():
                       snake_case__       :   List[str]	      =    model(**self._prepare_for_class(__lowerCamelCase     ,							__lowerCamelCase			)			)

                 snake_case__       :   List[str]	      =    outputs.hidden_states

                 snake_case__       :   List[Any]	      =    16
                 self.assertEqual(len(__lowerCamelCase			)     ,							__lowerCamelCase			)

           snake_case__      ,							snake_case__       :   Optional[Any]	      =    self.model_tester.prepare_config_and_inputs_for_common()

           for model_class in self.all_model_classes:
                 snake_case__       :   List[Any]	      =    True
                 check_hidden_states_output(__lowerCamelCase     ,							__lowerCamelCase     ,							__lowerCamelCase			)

                 # check that output_hidden_states also work using config
                 del inputs_dict["output_hidden_states"]
                 snake_case__       :   List[Any]	      =    True

                 check_hidden_states_output(__lowerCamelCase     ,							__lowerCamelCase     ,							__lowerCamelCase			)





     def 			_lowerCAmelCase      (     self     :					List[str]			):
           snake_case__       :   Union[str, Any]	      =    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase			)





     def 			_lowerCAmelCase      (     self     :					str			):
           snake_case__       :   Tuple	      =    self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_semantic_segmentation(*__lowerCamelCase			)





     @slow
     def 			_lowerCAmelCase      (     self     :					Dict			):
           for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 snake_case__       :   Any	      =    MobileNetVaModel.from_pretrained(__lowerCamelCase			)
                 self.assertIsNotNone(__lowerCamelCase			)






def 		UpperCamelCase__      (		)    ->   Dict:
      snake_case__       :   Tuple	      =    Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'		)
      return image






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





     @cached_property
     def 			_lowerCAmelCase      (     self     :					Tuple			):
           return (
               MobileNetVaImageProcessor.from_pretrained('google/mobilenet_v2_1.0_224'			) if is_vision_available() else None
           )





     @slow
     def 			_lowerCAmelCase      (     self     :					int			):
           snake_case__       :   Dict	      =    MobileNetVaForImageClassification.from_pretrained('google/mobilenet_v2_1.0_224'			).to(__lowerCamelCase			)

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

           # forward pass
           with torch.no_grad():
                 snake_case__       :   Any	      =    model(**__lowerCamelCase			)

           # verify the logits
           snake_case__       :   Tuple	      =    torch.Size((1, 1001)			)
           self.assertEqual(outputs.logits.shape     ,							__lowerCamelCase			)

           snake_case__       :   int	      =    torch.tensor([0.2_4_4_5, -1.1_9_9_3, 0.1_9_0_5]			).to(__lowerCamelCase			)

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





     @slow
     def 			_lowerCAmelCase      (     self     :					int			):
           snake_case__       :   str	      =    MobileNetVaForSemanticSegmentation.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513'			)
           snake_case__       :   int	      =    model.to(__lowerCamelCase			)

           snake_case__       :   Any	      =    MobileNetVaImageProcessor.from_pretrained('google/deeplabv3_mobilenet_v2_1.0_513'			)

           snake_case__       :   Any	      =    prepare_img()
           snake_case__       :   Dict	      =    image_processor(images=__lowerCamelCase     ,							return_tensors='pt'			).to(__lowerCamelCase			)

           # forward pass
           with torch.no_grad():
                 snake_case__       :   Any	      =    model(**__lowerCamelCase			)
           snake_case__       :   Optional[int]	      =    outputs.logits

           # verify the logits
           snake_case__       :   str	      =    torch.Size((1, 21, 65, 65)			)
           self.assertEqual(logits.shape     ,							__lowerCamelCase			)

           snake_case__       :   Optional[Any]	      =    torch.tensor(
               [
                   [[1_7.5_7_9_0, 1_7.7_5_8_1, 1_8.3_3_5_5], [1_8.3_2_5_7, 1_8.4_2_3_0, 1_8.8_9_7_3], [1_8.6_1_6_9, 1_8.8_6_5_0, 1_9.2_1_8_7]],
                   [[-2.1_5_9_5, -2.0_9_7_7, -2.3_7_4_1], [-2.4_2_2_6, -2.3_0_2_8, -2.6_8_3_5], [-2.7_8_1_9, -2.5_9_9_1, -2.7_7_0_6]],
                   [[4.2_0_5_8, 4.8_3_1_7, 4.7_6_3_8], [4.4_1_3_6, 5.0_3_6_1, 4.9_3_8_3], [4.5_0_2_8, 4.9_6_4_4, 4.8_7_3_4]],
               ]     ,							device=__lowerCamelCase     ,							)

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