import inspect
import unittest

from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, 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 MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
      from transformers.models.mobilevitva.modeling_mobilevitva import (
          MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
          make_divisible,
      )


if is_vision_available():
      from PIL import Image

      from transformers import MobileViTImageProcessor



class   snake_case_       (		__A       ):






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



class   snake_case_       :






   def __init__(      self				:     Optional[int]	,						lowercase_				:     Union[str, Any]	,						lowercase_				:     List[str]=13	,						lowercase_				:     List[str]=64	,						lowercase_				:     Any=2	,						lowercase_				:     Dict=3	,						lowercase_				:     Tuple="swish"	,						lowercase_				:     List[Any]=3	,						lowercase_				:     List[Any]=32	,						lowercase_				:     str=0.1	,						lowercase_				:     Any=0.02	,						lowercase_				:     Optional[int]=True	,						lowercase_				:     List[str]=True	,						lowercase_				:     Optional[Any]=10	,						lowercase_				:     List[str]=None	,						lowercase_				:     int=0.25	,						lowercase_				:     List[str]=0.0	,						lowercase_				:     str=0.0	,						)					->						Dict:
       lowercase__ :   Optional[int]    					=				parent
       lowercase__ :   Optional[Any]    					=				batch_size
       lowercase__ :   str    					=				image_size
       lowercase__ :   Union[str, Any]    					=				patch_size
       lowercase__ :   Tuple    					=				num_channels
       lowercase__ :   Optional[int]    					=				make_divisible(5_12 * width_multiplier	,						divisor=8  )
       lowercase__ :   Optional[Any]    					=				hidden_act
       lowercase__ :   Union[str, Any]    					=				conv_kernel_size
       lowercase__ :   Tuple    					=				output_stride
       lowercase__ :   Dict    					=				classifier_dropout_prob
       lowercase__ :   Optional[int]    					=				use_labels
       lowercase__ :   Dict    					=				is_training
       lowercase__ :   Optional[int]    					=				num_labels
       lowercase__ :   Tuple    					=				initializer_range
       lowercase__ :   List[Any]    					=				scope
       lowercase__ :   List[Any]    					=				width_multiplier
       lowercase__ :   Optional[Any]    					=				ffn_dropout
       lowercase__ :   List[Any]    					=				attn_dropout






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

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

       lowercase__ :   Dict    					=				self.get_config()

       return config, pixel_values, labels, pixel_labels






   def       __UpperCamelCase     (      self				:     Any  )					->						List[str]:
       return MobileViTVaConfig(
           image_size=self.image_size	,						patch_size=self.patch_size	,						num_channels=self.num_channels	,						hidden_act=self.hidden_act	,						conv_kernel_size=self.conv_kernel_size	,						output_stride=self.output_stride	,						classifier_dropout_prob=self.classifier_dropout_prob	,						initializer_range=self.initializer_range	,						width_multiplier=self.width_multiplier	,						ffn_dropout=self.ffn_dropout_prob	,						attn_dropout=self.attn_dropout_prob	,						)






   def       __UpperCamelCase     (      self				:     List[Any]	,						lowercase_				:     str	,						lowercase_				:     List[Any]	,						lowercase_				:     List[Any]	,						lowercase_				:     Dict  )					->						Union[str, Any]:
       lowercase__ :   Any    					=				MobileViTVaModel(config=lowercase_  )
       model.to(lowercase_  )
       model.eval()
       lowercase__ :   List[str]    					=				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,
           )	,						)






   def       __UpperCamelCase     (      self				:     List[str]	,						lowercase_				:     Optional[int]	,						lowercase_				:     Tuple	,						lowercase_				:     Union[str, Any]	,						lowercase_				:     Optional[Any]  )					->						Tuple:
       lowercase__ :   Optional[Any]    					=				self.num_labels
       lowercase__ :   List[Any]    					=				MobileViTVaForImageClassification(lowercase_  )
       model.to(lowercase_  )
       model.eval()
       lowercase__ :   Any    					=				model(lowercase_	,						labels=lowercase_  )
       self.parent.assertEqual(result.logits.shape	,						(self.batch_size, self.num_labels)  )






   def       __UpperCamelCase     (      self				:     Union[str, Any]	,						lowercase_				:     Union[str, Any]	,						lowercase_				:     Optional[int]	,						lowercase_				:     Optional[int]	,						lowercase_				:     Tuple  )					->						Union[str, Any]:
       lowercase__ :   Any    					=				self.num_labels
       lowercase__ :   Dict    					=				MobileViTVaForSemanticSegmentation(lowercase_  )
       model.to(lowercase_  )
       model.eval()
       lowercase__ :   List[Any]    					=				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				:     Tuple  )					->						Optional[Any]:
       lowercase__ :   Tuple    					=				self.prepare_config_and_inputs()
       lowercase__					,   lowercase__					,   lowercase__					,   lowercase__ :   Dict    					=				config_and_inputs
       lowercase__ :   List[Any]    					=				{"pixel_values": pixel_values}
       return config, inputs_dict



@require_torch
class   snake_case_       (		__A  ,__A  ,unittest.TestCase       ):
   __A	:		Optional[int]         =				(
       (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
       if is_torch_available()
       else ()
   )

   __A	:		Tuple         =				(
       {
           "feature-extraction": MobileViTVaModel,
           "image-classification": MobileViTVaForImageClassification,
           "image-segmentation": MobileViTVaForSemanticSegmentation,
       }
       if is_torch_available()
       else {}
   )

   __A	:		List[Any]         =				False
   __A	:		List[str]         =				False
   __A	:		List[str]         =				False
   __A	:		List[Any]         =				False






   def       __UpperCamelCase     (      self				:     str  )					->						List[Any]:
       lowercase__ :   int    					=				MobileViTVaModelTester(self  )
       lowercase__ :   Optional[int]    					=				MobileViTVaConfigTester(self	,						config_class=lowercase_	,						has_text_modality=lowercase_  )






   def       __UpperCamelCase     (      self				:     Any  )					->						Union[str, Any]:
       self.config_tester.run_common_tests()






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






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






   @unittest.skip(reason="MobileViTV2 does not output attentions"  )
   def       __UpperCamelCase     (      self				:     str  )					->						Optional[int]:
       pass






   @require_torch_multi_gpu
   @unittest.skip(reason="Got `CUDA error: misaligned address` for tests after this one being run."  )
   def       __UpperCamelCase     (      self				:     Any  )					->						int:
       pass






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






   def       __UpperCamelCase     (      self				:     Optional[int]  )					->						Union[str, Any]:
       lowercase__					,   lowercase__ :   Dict    					=				self.model_tester.prepare_config_and_inputs_for_common()

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

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






   def       __UpperCamelCase     (      self				:     Union[str, Any]  )					->						Any:
       lowercase__ :   List[Any]    					=				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowercase_  )






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

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

           lowercase__ :   Optional[int]    					=				outputs.hidden_states

           lowercase__ :   Any    					=				5
           self.assertEqual(len(lowercase_  )	,						lowercase_  )

           # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
           # with the width and height being successively divided by 2.
           lowercase__ :   Optional[int]    					=				2
           for i in range(len(lowercase_  )  ):
               self.assertListEqual(
                   list(hidden_states[i].shape[-2:]  )	,						[self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]	,						)
               divisor *= 2

           self.assertEqual(self.model_tester.output_stride	,						divisor // 2  )

       lowercase__					,   lowercase__ :   Any    					=				self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           lowercase__ :   Tuple    					=				True
           check_hidden_states_output(lowercase_	,						lowercase_	,						lowercase_  )

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

           check_hidden_states_output(lowercase_	,						lowercase_	,						lowercase_  )






   def       __UpperCamelCase     (      self				:     List[Any]  )					->						str:
       lowercase__ :   str    					=				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*lowercase_  )






   def       __UpperCamelCase     (      self				:     Any  )					->						int:
       lowercase__ :   Dict    					=				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*lowercase_  )







   @slow
   def       __UpperCamelCase     (      self				:     Union[str, Any]  )					->						List[str]:
       for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowercase__ :   Tuple    					=				MobileViTVaModel.from_pretrained(lowercase_  )
           self.assertIsNotNone(lowercase_  )



def 			lowercase_				(			):
    lowercase__ :   Optional[int]    					=				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				:     List[Any]  )					->						Optional[Any]:
       return (
           MobileViTImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"  )
           if is_vision_available()
           else None
       )






   @slow
   def       __UpperCamelCase     (      self				:     Union[str, Any]  )					->						List[str]:
       lowercase__ :   List[str]    					=				MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"  ).to(
           lowercase_  )

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

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

       # verify the logits
       lowercase__ :   Optional[int]    					=				torch.Size((1, 10_00)  )
       self.assertEqual(outputs.logits.shape	,						lowercase_  )

       lowercase__ :   Tuple    					=				torch.tensor([-1.63_36E00, -7.32_04E-02, -5.18_83E-01]  ).to(lowercase_  )

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






   @slow
   def       __UpperCamelCase     (      self				:     Tuple  )					->						Optional[int]:
       lowercase__ :   Dict    					=				MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"  )
       lowercase__ :   int    					=				model.to(lowercase_  )

       lowercase__ :   Any    					=				MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"  )

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

       # forward pass
       with torch.no_grad():
           lowercase__ :   str    					=				model(**lowercase_  )
       lowercase__ :   Tuple    					=				outputs.logits

       # verify the logits
       lowercase__ :   Union[str, Any]    					=				torch.Size((1, 21, 32, 32)  )
       self.assertEqual(logits.shape	,						lowercase_  )

       lowercase__ :   Optional[Any]    					=				torch.tensor(
           [
               [[7.08_63, 7.15_25, 6.82_01], [6.69_31, 6.87_70, 6.89_33], [6.29_78, 7.03_66, 6.96_36]],
               [[-3.71_34, -3.67_12, -3.66_75], [-3.58_25, -3.35_49, -3.47_77], [-3.34_35, -3.39_79, -3.28_57]],
               [[-2.93_29, -2.80_03, -2.73_69], [-3.05_64, -2.47_80, -2.02_07], [-2.68_89, -1.92_98, -1.76_40]],
           ]	,						device=lowercase_	,						)

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







   @slow
   def       __UpperCamelCase     (      self				:     Any  )					->						List[str]:
       lowercase__ :   Dict    					=				MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"  )
       lowercase__ :   int    					=				model.to(lowercase_  )

       lowercase__ :   Optional[int]    					=				MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"  )

       lowercase__ :   List[str]    					=				prepare_img()
       lowercase__ :   Tuple    					=				image_processor(images=lowercase_	,						return_tensors="pt"  ).to(lowercase_  )

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

       lowercase__ :   Tuple    					=				outputs.logits.detach().cpu()

       lowercase__ :   List[str]    					=				image_processor.post_process_semantic_segmentation(outputs=lowercase_	,						target_sizes=[(50, 60)]  )
       lowercase__ :   List[str]    					=				torch.Size((50, 60)  )
       self.assertEqual(segmentation[0].shape	,						lowercase_  )

       lowercase__ :   int    					=				image_processor.post_process_semantic_segmentation(outputs=lowercase_  )
       lowercase__ :   Dict    					=				torch.Size((32, 32)  )
       self.assertEqual(segmentation[0].shape	,						lowercase_  )





from ...configuration_utils import PretrainedConfig
from ...utils import logging


lowercase  :					List[Any]													=       logging.get_logger(__name__)

lowercase  :					Any													=       {
    'google/pegasus-large': 'https://huggingface.co/google/pegasus-large/resolve/main/config.json',
    # See all PEGASUS models at https://huggingface.co/models?filter=pegasus
}




class  lowerCamelCase__							(				__lowercase):




	'''simple docstring'''




	_A								=     'pegasus'
	_A								=     ['past_key_values']
	_A								=     {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}







	def __init__(					self		:Dict     ,   a		:Dict=5_0_2_6_5     ,   a		:Dict=1_0_2_4     ,   a		:Union[str, Any]=1_2     ,   a		:Any=4_0_9_6     ,   a		:str=1_6     ,   a		:str=1_2     ,   a		:Optional[Any]=4_0_9_6     ,   a		:int=1_6     ,   a		:Optional[int]=0.0     ,   a		:Optional[int]=0.0     ,   a		:List[Any]=True     ,   a		:Union[str, Any]=True     ,   a		:int="gelu"     ,   a		:Dict=1_0_2_4     ,   a		:List[Any]=0.1     ,   a		:List[str]=0.0     ,   a		:List[Any]=0.0     ,   a		:str=0.02     ,   a		:int=0     ,   a		:Any=False     ,   a		:Dict=0     ,   a		:int=1     ,   a		:Optional[Any]=1     ,   **a		:Optional[int]     ,   )		-> str:
								__UpperCamelCase	:   List[Any]			   =					vocab_size
								__UpperCamelCase	:   Union[str, Any]			   =					max_position_embeddings
								__UpperCamelCase	:   str			   =					d_model
								__UpperCamelCase	:   Dict			   =					encoder_ffn_dim
								__UpperCamelCase	:   int			   =					encoder_layers
								__UpperCamelCase	:   int			   =					encoder_attention_heads
								__UpperCamelCase	:   List[Any]			   =					decoder_ffn_dim
								__UpperCamelCase	:   List[Any]			   =					decoder_layers
								__UpperCamelCase	:   List[str]			   =					decoder_attention_heads
								__UpperCamelCase	:   str			   =					dropout
								__UpperCamelCase	:   Union[str, Any]			   =					attention_dropout
								__UpperCamelCase	:   List[str]			   =					activation_dropout
								__UpperCamelCase	:   Optional[Any]			   =					activation_function
								__UpperCamelCase	:   Tuple			   =					init_std
								__UpperCamelCase	:   Optional[int]			   =					encoder_layerdrop
								__UpperCamelCase	:   Union[str, Any]			   =					decoder_layerdrop
								__UpperCamelCase	:   Optional[Any]			   =					use_cache
								__UpperCamelCase	:   Union[str, Any]			   =					encoder_layers
								__UpperCamelCase	:   int			   =					scale_embedding  # scale factor will be sqrt(d_model) if True
								super().__init__(
								    pad_token_id=a     ,   eos_token_id=a     ,   is_encoder_decoder=a     ,   decoder_start_token_id=a     ,   forced_eos_token_id=a     ,   **a     ,   )







	@property
	def    _lowerCamelCase				(					self		:Dict						)		-> int:
								return self.encoder_attention_heads







	@property
	def    _lowerCamelCase				(					self		:Optional[Any]						)		-> int:
								return self.d_model