


'''simple docstring'''




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 		UpperCAmelCase_      (  __UpperCamelCase		):





     def 							__UpperCAmelCase      ( self       :      str    )				->  Tuple:
        lowerCAmelCase     =			self.config_class(**self.inputs_dict    )
        self.parent.assertTrue(hasattr(a_    ,      'width_multiplier'    )    )




class 		UpperCAmelCase_      :





     def __init__( self       :      str    ,      UpperCAmelCase__       :      Any    ,      UpperCAmelCase__       :      Tuple=1_3    ,      UpperCAmelCase__       :      Tuple=6_4    ,      UpperCAmelCase__       :      Optional[int]=2    ,      UpperCAmelCase__       :      List[str]=3    ,      UpperCAmelCase__       :      Optional[Any]="swish"    ,      UpperCAmelCase__       :      Optional[Any]=3    ,      UpperCAmelCase__       :      str=3_2    ,      UpperCAmelCase__       :      Dict=0.1    ,      UpperCAmelCase__       :      int=0.02    ,      UpperCAmelCase__       :      Tuple=True    ,      UpperCAmelCase__       :      List[Any]=True    ,      UpperCAmelCase__       :      Optional[int]=1_0    ,      UpperCAmelCase__       :      Optional[int]=None    ,      UpperCAmelCase__       :      Dict=0.25    ,      UpperCAmelCase__       :      Tuple=0.0    ,      UpperCAmelCase__       :      List[Any]=0.0    ,      )				->  List[str]:
        lowerCAmelCase     =			parent
        lowerCAmelCase     =			batch_size
        lowerCAmelCase     =			image_size
        lowerCAmelCase     =			patch_size
        lowerCAmelCase     =			num_channels
        lowerCAmelCase     =			make_divisible(5_1_2 * width_multiplier    ,      divisor=8    )
        lowerCAmelCase     =			hidden_act
        lowerCAmelCase     =			conv_kernel_size
        lowerCAmelCase     =			output_stride
        lowerCAmelCase     =			classifier_dropout_prob
        lowerCAmelCase     =			use_labels
        lowerCAmelCase     =			is_training
        lowerCAmelCase     =			num_labels
        lowerCAmelCase     =			initializer_range
        lowerCAmelCase     =			scope
        lowerCAmelCase     =			width_multiplier
        lowerCAmelCase     =			ffn_dropout
        lowerCAmelCase     =			attn_dropout





     def 							__UpperCAmelCase      ( self       :      List[Any]    )				->  Optional[int]:
        lowerCAmelCase     =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

        lowerCAmelCase     =			self.get_config()

        return config, pixel_values, labels, pixel_labels





     def 							__UpperCAmelCase      ( self       :      Union[str, Any]    )				->  Union[str, Any]:
        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       :      Optional[Any]    ,      UpperCAmelCase__       :      Dict    ,      UpperCAmelCase__       :      List[Any]    ,      UpperCAmelCase__       :      Dict    ,      UpperCAmelCase__       :      Tuple    )				->  List[Any]:
        lowerCAmelCase     =			MobileViTVaModel(config=a_    )
        model.to(a_    )
        model.eval()
        lowerCAmelCase     =			model(a_    )
        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       :      Union[str, Any]    ,      UpperCAmelCase__       :      Dict    ,      UpperCAmelCase__       :      Union[str, Any]    ,      UpperCAmelCase__       :      str    ,      UpperCAmelCase__       :      List[str]    )				->  Optional[Any]:
        lowerCAmelCase     =			self.num_labels
        lowerCAmelCase     =			MobileViTVaForImageClassification(a_    )
        model.to(a_    )
        model.eval()
        lowerCAmelCase     =			model(a_    ,      labels=a_    )
        self.parent.assertEqual(result.logits.shape    ,      (self.batch_size, self.num_labels)    )





     def 							__UpperCAmelCase      ( self       :      str    ,      UpperCAmelCase__       :      List[str]    ,      UpperCAmelCase__       :      Optional[Any]    ,      UpperCAmelCase__       :      List[str]    ,      UpperCAmelCase__       :      int    )				->  Dict:
        lowerCAmelCase     =			self.num_labels
        lowerCAmelCase     =			MobileViTVaForSemanticSegmentation(a_    )
        model.to(a_    )
        model.eval()
        lowerCAmelCase     =			model(a_    )
        self.parent.assertEqual(
            result.logits.shape    ,      (
                self.batch_size,
                self.num_labels,
                self.image_size // self.output_stride,
                self.image_size // self.output_stride,
            )    ,      )
        lowerCAmelCase     =			model(a_    ,      labels=a_    )
        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       :      List[str]    )				->  Any:
        lowerCAmelCase     =			self.prepare_config_and_inputs()
        lowerCAmelCase     =			config_and_inputs
        lowerCAmelCase     =			{'''pixel_values''': pixel_values}
        return config, inputs_dict




@require_torch
class 		UpperCAmelCase_      (  __UpperCamelCase       ,	__UpperCamelCase       ,	unittest.TestCase		):
     lowerCamelCase				:	List[str]		=     (
         (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
         if is_torch_available()
         else ()
     )

     lowerCamelCase				:	str		=     (
         {
             '''feature-extraction''': MobileViTVaModel,
             '''image-classification''': MobileViTVaForImageClassification,
             '''image-segmentation''': MobileViTVaForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )

     lowerCamelCase				:	Union[str, Any]		=     False
     lowerCamelCase				:	Any		=     False
     lowerCamelCase				:	Optional[int]		=     False
     lowerCamelCase				:	Optional[int]		=     False





     def 							__UpperCAmelCase      ( self       :      List[Any]    )				->  List[str]:
        lowerCAmelCase     =			MobileViTVaModelTester(self    )
        lowerCAmelCase     =			MobileViTVaConfigTester(self    ,      config_class=a_    ,      has_text_modality=a_    )





     def 							__UpperCAmelCase      ( self       :      str    )				->  str:
        self.config_tester.run_common_tests()





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





     @unittest.skip(reason='MobileViTV2 does not support input and output embeddings'    )
     def 							__UpperCAmelCase      ( self       :      Union[str, Any]    )				->  List[Any]:
        pass





     @unittest.skip(reason='MobileViTV2 does not output attentions'    )
     def 							__UpperCAmelCase      ( self       :      Tuple    )				->  int:
        pass





     @require_torch_multi_gpu
     @unittest.skip(reason='Got `CUDA error: misaligned address` for tests after this one being run.'    )
     def 							__UpperCAmelCase      ( self       :      Dict    )				->  Union[str, Any]:
        pass





     @unittest.skip('Will be fixed soon by reducing the size of the model used for common tests.'    )
     def 							__UpperCAmelCase      ( self       :      Optional[Any]    )				->  Dict:
        pass





     def 							__UpperCAmelCase      ( self       :      Any    )				->  Union[str, Any]:
        lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs_for_common()

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

           lowerCAmelCase     =			['''pixel_values''']
           self.assertListEqual(arg_names[:1]    ,      a_    )





     def 							__UpperCAmelCase      ( self       :      Union[str, Any]    )				->  str:
        lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*a_    )





     def 							__UpperCAmelCase      ( self       :      int    )				->  Optional[int]:





        def check_hidden_states_output(UpperCAmelCase__       :      List[Any]    ,      UpperCAmelCase__       :      List[Any]    ,      UpperCAmelCase__       :      Union[str, Any]    ):
           lowerCAmelCase     =			model_class(a_    )
           model.to(a_    )
           model.eval()

           with torch.no_grad():
              lowerCAmelCase     =			model(**self._prepare_for_class(a_    ,      a_    )    )

           lowerCAmelCase     =			outputs.hidden_states

           lowerCAmelCase     =			5
           self.assertEqual(len(a_    )    ,      a_    )

           # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
           # with the width and height being successively divided by 2.
           lowerCAmelCase     =			2
           for i in range(len(a_    )    ):
              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    )

        lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
           lowerCAmelCase     =			True
           check_hidden_states_output(a_    ,      a_    ,      a_    )

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

           check_hidden_states_output(a_    ,      a_    ,      a_    )





     def 							__UpperCAmelCase      ( self       :      Dict    )				->  Union[str, Any]:
        lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*a_    )





     def 							__UpperCAmelCase      ( self       :      Any    )				->  List[str]:
        lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*a_    )





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





        for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowerCAmelCase     =			MobileViTVaModel.from_pretrained(a_    )
           self.assertIsNotNone(a_    )





def 	a_					( ):
   lowerCAmelCase     =			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
   return image




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





     @cached_property
     def 							__UpperCAmelCase      ( self       :      Optional[int]    )				->  int:
        return (
            MobileViTImageProcessor.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256'    )
            if is_vision_available()
            else None
        )





     @slow
     def 							__UpperCAmelCase      ( self       :      Optional[Any]    )				->  Union[str, Any]:
        lowerCAmelCase     =			MobileViTVaForImageClassification.from_pretrained('apple/mobilevitv2-1.0-imagenet1k-256'    ).to(
            a_    )

        lowerCAmelCase     =			self.default_image_processor
        lowerCAmelCase     =			prepare_img()
        lowerCAmelCase     =			image_processor(images=a_    ,      return_tensors='pt'    ).to(a_    )

        # forward pass
        with torch.no_grad():
           lowerCAmelCase     =			model(**a_    )

        # verify the logits
        lowerCAmelCase     =			torch.Size((1, 1_0_0_0)    )
        self.assertEqual(outputs.logits.shape    ,      a_    )

        lowerCAmelCase     =			torch.tensor([-1.63_36E00, -7.32_04E-02, -5.18_83E-01]    ).to(a_    )

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





     @slow
     def 							__UpperCAmelCase      ( self       :      List[Any]    )				->  List[Any]:
        lowerCAmelCase     =			MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'    )
        lowerCAmelCase     =			model.to(a_    )

        lowerCAmelCase     =			MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'    )

        lowerCAmelCase     =			prepare_img()
        lowerCAmelCase     =			image_processor(images=a_    ,      return_tensors='pt'    ).to(a_    )

        # forward pass
        with torch.no_grad():
           lowerCAmelCase     =			model(**a_    )
        lowerCAmelCase     =			outputs.logits

        # verify the logits
        lowerCAmelCase     =			torch.Size((1, 2_1, 3_2, 3_2)    )
        self.assertEqual(logits.shape    ,      a_    )

        lowerCAmelCase     =			torch.tensor(
            [
                [[7.0_863, 7.1_525, 6.8_201], [6.6_931, 6.8_770, 6.8_933], [6.2_978, 7.0_366, 6.9_636]],
                [[-3.7_134, -3.6_712, -3.6_675], [-3.5_825, -3.3_549, -3.4_777], [-3.3_435, -3.3_979, -3.2_857]],
                [[-2.9_329, -2.8_003, -2.7_369], [-3.0_564, -2.4_780, -2.0_207], [-2.6_889, -1.9_298, -1.7_640]],
            ]    ,      device=a_    ,      )

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





     @slow
     def 							__UpperCAmelCase      ( self       :      Dict    )				->  Any:
        lowerCAmelCase     =			MobileViTVaForSemanticSegmentation.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'    )
        lowerCAmelCase     =			model.to(a_    )

        lowerCAmelCase     =			MobileViTImageProcessor.from_pretrained('shehan97/mobilevitv2-1.0-voc-deeplabv3'    )

        lowerCAmelCase     =			prepare_img()
        lowerCAmelCase     =			image_processor(images=a_    ,      return_tensors='pt'    ).to(a_    )

        # forward pass
        with torch.no_grad():
           lowerCAmelCase     =			model(**a_    )

        lowerCAmelCase     =			outputs.logits.detach().cpu()

        lowerCAmelCase     =			image_processor.post_process_semantic_segmentation(outputs=a_    ,      target_sizes=[(5_0, 6_0)]    )
        lowerCAmelCase     =			torch.Size((5_0, 6_0)    )
        self.assertEqual(segmentation[0].shape    ,      a_    )

        lowerCAmelCase     =			image_processor.post_process_semantic_segmentation(outputs=a_    )
        lowerCAmelCase     =			torch.Size((3_2, 3_2)    )
        self.assertEqual(segmentation[0].shape    ,      a_    )










import unittest

from transformers import load_tool
from transformers.utils import is_torch_available


if is_torch_available():
				import torch

from transformers.testing_utils import require_torch

from .test_tools_common import ToolTesterMixin

@require_torch
class 		UpperCAmelCase__			(			unittest.TestCase						,__UpperCamelCase   ):




			'''simple docstring'''






			def  snake_case__     (   self							: List[Any] ):
					'''simple docstring'''





					__UpperCAmelCase    :     Tuple													=	load_tool('''text-to-speech''' )
					self.tool.setup()




			def  snake_case__     (   self							: Union[str, Any] ):
					'''simple docstring'''





					torch.manual_seed(0 )
					__UpperCAmelCase    :     List[Any]													=	self.tool('''hey''' )
					__UpperCAmelCase    :     Union[str, Any]													=	result.to_raw()
					self.assertTrue(
					    torch.allclose(
					        resulting_tensor[:3]       ,       torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5] )       ,       ) )




			def  snake_case__     (   self							: Optional[Any] ):
					'''simple docstring'''





					torch.manual_seed(0 )
					__UpperCAmelCase    :     Optional[int]													=	self.tool('''hey''' )
					__UpperCAmelCase    :     List[str]													=	result.to_raw()
					self.assertTrue(
					    torch.allclose(
					        resulting_tensor[:3]       ,       torch.tensor([-0.0_0_0_5_9_6_6_6_6_8_8_3_2_1_1_5_8_2_9, -0.0_0_0_3_6_5_7_6_4_0_1_9_0_7_9_5_0_6_4, -0.0_0_0_1_3_4_3_9_5_0_2_7_9_9_8_8_3_4_8_5] )       ,       ) )





