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   snake_case_       (		__A       ):






   def       __UpperCamelCase     (      self				:     Optional[Any]  )					->						Optional[Any]:
       lowercase__ :   List[str]    					=				self.config_class(**self.inputs_dict  )
       self.parent.assertTrue(hasattr(lowercase_	,						"tf_padding"  )  )
       self.parent.assertTrue(hasattr(lowercase_	,						"depth_multiplier"  )  )



class   snake_case_       :






   def __init__(      self				:     Optional[Any]	,						lowercase_				:     Dict	,						lowercase_				:     List[Any]=13	,						lowercase_				:     List[Any]=3	,						lowercase_				:     Tuple=32	,						lowercase_				:     int=0.25	,						lowercase_				:     List[Any]=8	,						lowercase_				:     Tuple=8	,						lowercase_				:     List[str]=6	,						lowercase_				:     Tuple=32	,						lowercase_				:     str=True	,						lowercase_				:     List[str]=True	,						lowercase_				:     Tuple=True	,						lowercase_				:     Optional[Any]="relu6"	,						lowercase_				:     str=12_80	,						lowercase_				:     List[Any]=0.1	,						lowercase_				:     Optional[int]=0.02	,						lowercase_				:     Union[str, Any]=True	,						lowercase_				:     Optional[int]=True	,						lowercase_				:     Any=10	,						lowercase_				:     Any=None	,						)					->						Dict:
       lowercase__ :   Tuple    					=				parent
       lowercase__ :   Union[str, Any]    					=				batch_size
       lowercase__ :   Optional[Any]    					=				num_channels
       lowercase__ :   List[Any]    					=				image_size
       lowercase__ :   Union[str, Any]    					=				depth_multiplier
       lowercase__ :   Dict    					=				depth_divisible_by
       lowercase__ :   Any    					=				min_depth
       lowercase__ :   Any    					=				expand_ratio
       lowercase__ :   Union[str, Any]    					=				tf_padding
       lowercase__ :   Dict    					=				output_stride
       lowercase__ :   Optional[Any]    					=				first_layer_is_expansion
       lowercase__ :   Optional[Any]    					=				finegrained_output
       lowercase__ :   Optional[int]    					=				hidden_act
       lowercase__ :   List[str]    					=				last_hidden_size if finegrained_output else int(last_hidden_size * depth_multiplier  )
       lowercase__ :   Union[str, Any]    					=				classifier_dropout_prob
       lowercase__ :   List[str]    					=				use_labels
       lowercase__ :   Tuple    					=				is_training
       lowercase__ :   Optional[int]    					=				num_labels
       lowercase__ :   str    					=				initializer_range
       lowercase__ :   Union[str, Any]    					=				scope






   def       __UpperCamelCase     (      self				:     List[Any]  )					->						Any:
       lowercase__ :   int    					=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

       lowercase__ :   Optional[Any]    					=				None
       lowercase__ :   str    					=				None
       if self.use_labels:
           lowercase__ :   Union[str, Any]    					=				ids_tensor([self.batch_size]	,						self.num_labels  )
           lowercase__ :   Optional[int]    					=				ids_tensor([self.batch_size, self.image_size, self.image_size]	,						self.num_labels  )

       lowercase__ :   Union[str, Any]    					=				self.get_config()

       return config, pixel_values, labels, pixel_labels






   def       __UpperCamelCase     (      self				:     str  )					->						str:
       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       __UpperCamelCase     (      self				:     Tuple	,						lowercase_				:     int	,						lowercase_				:     Optional[Any]	,						lowercase_				:     Tuple	,						lowercase_				:     str  )					->						Optional[int]:
       lowercase__ :   List[Any]    					=				MobileNetVaModel(config=lowercase_  )
       model.to(lowercase_  )
       model.eval()
       lowercase__ :   Union[str, Any]    					=				model(lowercase_  )
       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       __UpperCamelCase     (      self				:     Optional[int]	,						lowercase_				:     Optional[int]	,						lowercase_				:     str	,						lowercase_				:     List[str]	,						lowercase_				:     Tuple  )					->						List[Any]:
       lowercase__ :   Tuple    					=				self.num_labels
       lowercase__ :   List[str]    					=				MobileNetVaForImageClassification(lowercase_  )
       model.to(lowercase_  )
       model.eval()
       lowercase__ :   Optional[int]    					=				model(lowercase_	,						labels=lowercase_  )
       self.parent.assertEqual(result.logits.shape	,						(self.batch_size, self.num_labels)  )






   def       __UpperCamelCase     (      self				:     Any	,						lowercase_				:     Any	,						lowercase_				:     List[Any]	,						lowercase_				:     List[str]	,						lowercase_				:     List[str]  )					->						Union[str, Any]:
       lowercase__ :   Any    					=				self.num_labels
       lowercase__ :   List[str]    					=				MobileNetVaForSemanticSegmentation(lowercase_  )
       model.to(lowercase_  )
       model.eval()
       lowercase__ :   str    					=				model(lowercase_  )
       self.parent.assertEqual(
           result.logits.shape	,						(
               self.batch_size,
               self.num_labels,
               self.image_size // self.output_stride,
               self.image_size // self.output_stride,
           )	,						)
       lowercase__ :   Tuple    					=				model(lowercase_	,						labels=lowercase_  )
       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       __UpperCamelCase     (      self				:     str  )					->						str:
       lowercase__ :   Tuple    					=				self.prepare_config_and_inputs()
       lowercase__					,   lowercase__					,   lowercase__					,   lowercase__ :   Optional[Any]    					=				config_and_inputs
       lowercase__ :   int    					=				{"pixel_values": pixel_values}
       return config, inputs_dict



@require_torch
class   snake_case_       (		__A  ,__A  ,unittest.TestCase       ):
   __A	:		Any         =				(
       (MobileNetVaModel, MobileNetVaForImageClassification, MobileNetVaForSemanticSegmentation)
       if is_torch_available()
       else ()
   )
   __A	:		Tuple         =				(
       {
           "feature-extraction": MobileNetVaModel,
           "image-classification": MobileNetVaForImageClassification,
           "image-segmentation": MobileNetVaForSemanticSegmentation,
       }
       if is_torch_available()
       else {}
   )

   __A	:		List[str]         =				False
   __A	:		Dict         =				False
   __A	:		Union[str, Any]         =				False
   __A	:		Optional[Any]         =				False






   def       __UpperCamelCase     (      self				:     List[Any]  )					->						int:
       lowercase__ :   List[Any]    					=				MobileNetVaModelTester(self  )
       lowercase__ :   Dict    					=				MobileNetVaConfigTester(self	,						config_class=lowercase_	,						has_text_modality=lowercase_  )






   def       __UpperCamelCase     (      self				:     Optional[Any]  )					->						Any:
       self.config_tester.run_common_tests()






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






   @unittest.skip(reason="MobileNetV2 does not support input and output embeddings"  )
   def       __UpperCamelCase     (      self				:     Tuple  )					->						Dict:
       pass






   @unittest.skip(reason="MobileNetV2 does not output attentions"  )
   def       __UpperCamelCase     (      self				:     Tuple  )					->						str:
       pass






   def       __UpperCamelCase     (      self				:     int  )					->						int:
       lowercase__					,   lowercase__ :   int    					=				self.model_tester.prepare_config_and_inputs_for_common()

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

           lowercase__ :   Union[str, Any]    					=				["pixel_values"]
           self.assertListEqual(arg_names[:1]	,						lowercase_  )






   def       __UpperCamelCase     (      self				:     Optional[int]  )					->						Tuple:
       lowercase__ :   Optional[Any]    					=				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowercase_  )






   def       __UpperCamelCase     (      self				:     int  )					->						str:
       def check_hidden_states_output(lowercase_				:     List[str]	,						lowercase_				:     int	,						lowercase_				:     Union[str, Any]  ):
           lowercase__ :   Optional[int]    					=				model_class(lowercase_  )
           model.to(lowercase_  )
           model.eval()

           with torch.no_grad():
               lowercase__ :   Any    					=				model(**self._prepare_for_class(lowercase_	,						lowercase_  )  )

           lowercase__ :   int    					=				outputs.hidden_states

           lowercase__ :   Tuple    					=				16
           self.assertEqual(len(lowercase_  )	,						lowercase_  )

       lowercase__					,   lowercase__ :   List[str]    					=				self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           lowercase__ :   Union[str, Any]    					=				True
           check_hidden_states_output(lowercase_	,						lowercase_	,						lowercase_  )

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

           check_hidden_states_output(lowercase_	,						lowercase_	,						lowercase_  )






   def       __UpperCamelCase     (      self				:     Optional[int]  )					->						int:
       lowercase__ :   Optional[int]    					=				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*lowercase_  )






   def       __UpperCamelCase     (      self				:     int  )					->						Tuple:
       lowercase__ :   Optional[int]    					=				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*lowercase_  )







   @slow
   def       __UpperCamelCase     (      self				:     Tuple  )					->						Union[str, Any]:
       for model_name in MOBILENET_V2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowercase__ :   Optional[int]    					=				MobileNetVaModel.from_pretrained(lowercase_  )
           self.assertIsNotNone(lowercase_  )



def 			lowercase_				(			):
    lowercase__ :   Any    					=				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
    return image



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






   @cached_property
   def       __UpperCamelCase     (      self				:     Any  )					->						Optional[int]:
       return (
           MobileNetVaImageProcessor.from_pretrained("google/mobilenet_v2_1.0_224"  ) if is_vision_available() else None
       )






   @slow
   def       __UpperCamelCase     (      self				:     List[str]  )					->						Tuple:
       lowercase__ :   List[str]    					=				MobileNetVaForImageClassification.from_pretrained("google/mobilenet_v2_1.0_224"  ).to(lowercase_  )

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

       # forward pass
       with torch.no_grad():
           lowercase__ :   Any    					=				model(**lowercase_  )

       # verify the logits
       lowercase__ :   Dict    					=				torch.Size((1, 10_01)  )
       self.assertEqual(outputs.logits.shape	,						lowercase_  )

       lowercase__ :   str    					=				torch.tensor([0.24_45, -1.19_93, 0.19_05]  ).to(lowercase_  )

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







   @slow
   def       __UpperCamelCase     (      self				:     Union[str, Any]  )					->						List[str]:
       lowercase__ :   Tuple    					=				MobileNetVaForSemanticSegmentation.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"  )
       lowercase__ :   List[Any]    					=				model.to(lowercase_  )

       lowercase__ :   List[str]    					=				MobileNetVaImageProcessor.from_pretrained("google/deeplabv3_mobilenet_v2_1.0_513"  )

       lowercase__ :   int    					=				prepare_img()
       lowercase__ :   Tuple    					=				image_processor(images=lowercase_	,						return_tensors="pt"  ).to(lowercase_  )

       # forward pass
       with torch.no_grad():
           lowercase__ :   List[Any]    					=				model(**lowercase_  )
       lowercase__ :   Dict    					=				outputs.logits

       # verify the logits
       lowercase__ :   Any    					=				torch.Size((1, 21, 65, 65)  )
       self.assertEqual(logits.shape	,						lowercase_  )

       lowercase__ :   int    					=				torch.tensor(
           [
               [[17.57_90, 17.75_81, 18.33_55], [18.32_57, 18.42_30, 18.89_73], [18.61_69, 18.86_50, 19.21_87]],
               [[-2.15_95, -2.09_77, -2.37_41], [-2.42_26, -2.30_28, -2.68_35], [-2.78_19, -2.59_91, -2.77_06]],
               [[4.20_58, 4.83_17, 4.76_38], [4.41_36, 5.03_61, 4.93_83], [4.50_28, 4.96_44, 4.87_34]],
           ]	,						device=lowercase_	,						)

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






import operator as op


a__				=		'''scaler.pt'''
a__				=		'''pytorch_model'''
a__				=		'''random_states'''
a__				=		'''optimizer'''
a__				=		'''scheduler'''
a__				=		'''pytorch_model.bin'''
a__				=		'''pytorch_model.bin.index.json'''
a__				=		'''model.safetensors'''
a__				=		'''model.safetensors.index.json'''
a__				=		'''1.10.2'''
a__				=		'''py38'''
a__				=		'''4.17.0'''
a__				=		['''ml.p3.16xlarge''', '''ml.p3dn.24xlarge''', '''ml.p4dn.24xlarge''']
a__				=		['''FULL_SHARD''', '''SHARD_GRAD_OP''', '''NO_SHARD''', '''HYBRID_SHARD''', '''HYBRID_SHARD_ZERO2''']
a__				=		['''TRANSFORMER_BASED_WRAP''', '''SIZE_BASED_WRAP''', '''NO_WRAP''']
a__				=		['''BACKWARD_PRE''', '''BACKWARD_POST''', '''NO_PREFETCH''']
a__				=		['''FULL_STATE_DICT''', '''LOCAL_STATE_DICT''', '''SHARDED_STATE_DICT''']
a__				=		'''2.0.1'''
a__				=		['''pdsh''', '''standard''', '''openmpi''', '''mvapich''']
a__				=		['''default''', '''reduce-overhead''', '''max-autotune''']

a__				=		{'''>''': op.gt, '''>=''': op.ge, '''==''': op.eq, '''!=''': op.ne, '''<=''': op.le, '''<''': op.lt}

# These are the args for `torch.distributed.launch` for pytorch < 1.9
a__				=		[
    '''nnodes''',
    '''nproc_per_node''',
    '''rdzv_backend''',
    '''rdzv_endpoint''',
    '''rdzv_id''',
    '''rdzv_conf''',
    '''standalone''',
    '''max_restarts''',
    '''monitor_interval''',
    '''start_method''',
    '''role''',
    '''module''',
    '''m''',
    '''no_python''',
    '''run_path''',
    '''log_dir''',
    '''r''',
    '''redirects''',
    '''t''',
    '''tee''',
    '''node_rank''',
    '''master_addr''',
    '''master_port''',
]

a__				=		['''DEEPSPEED''', '''MULTI_GPU''', '''FSDP''', '''MEGATRON_LM''']
a__				=		['''DEEPSPEED''', '''MULTI_XPU''', '''FSDP''']



