






'''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    __SCREAMING_SNAKE_CASE					(	A__ ):




 def    __magic_name__		(					self		:							str					)		->  List[Any]:
       SCREAMING_SNAKE_CASE__   : Dict													=self.config_class(**self.inputs_dict					)
       self.parent.assertTrue(hasattr(_a    ,					'''width_multiplier'''					)					)






class    __SCREAMING_SNAKE_CASE					:




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




 def    __magic_name__		(					self		:							Optional[Any]					)		->  Optional[Any]:
       SCREAMING_SNAKE_CASE__   : List[str]													=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

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

       SCREAMING_SNAKE_CASE__   : List[str]													=self.get_config()

       return config, pixel_values, labels, pixel_labels




 def    __magic_name__		(					self		:							Any					)		->  List[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    __magic_name__		(					self		:							List[str]    ,					__lowercase		:							Optional[Any]    ,					__lowercase		:							List[Any]    ,					__lowercase		:							List[Any]    ,					__lowercase		:							Optional[Any]					)		->  Optional[Any]:
       SCREAMING_SNAKE_CASE__   : int													=MobileViTVaModel(config=_a					)
       model.to(_a					)
       model.eval()
       SCREAMING_SNAKE_CASE__   : Optional[int]													=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    __magic_name__		(					self		:							Optional[Any]    ,					__lowercase		:							List[Any]    ,					__lowercase		:							int    ,					__lowercase		:							Tuple    ,					__lowercase		:							Tuple					)		->  Any:
       SCREAMING_SNAKE_CASE__   : Any													=self.num_labels
       SCREAMING_SNAKE_CASE__   : Dict													=MobileViTVaForImageClassification(_a					)
       model.to(_a					)
       model.eval()
       SCREAMING_SNAKE_CASE__   : str													=model(_a    ,					labels=_a					)
       self.parent.assertEqual(result.logits.shape    ,					(self.batch_size, self.num_labels)					)




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






@require_torch
class    __SCREAMING_SNAKE_CASE					(	A__		, A__		, unittest.TestCase ):
 snake_case_     							=							(
     (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
     if is_torch_available()
     else ()
 )

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

 snake_case_     							=							False
 snake_case_     							=							False
 snake_case_     							=							False
 snake_case_     							=							False




 def    __magic_name__		(					self		:							Dict					)		->  List[Any]:
       SCREAMING_SNAKE_CASE__   : List[Any]													=MobileViTVaModelTester(self					)
       SCREAMING_SNAKE_CASE__   : Any													=MobileViTVaConfigTester(self    ,					config_class=_a    ,					has_text_modality=_a					)




 def    __magic_name__		(					self		:							Optional[int]					)		->  List[str]:
       self.config_tester.run_common_tests()




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




 @unittest.skip(reason='''MobileViTV2 does not support input and output embeddings'''					)
 def    __magic_name__		(					self		:							Dict					)		->  Any:
       pass




 @unittest.skip(reason='''MobileViTV2 does not output attentions'''					)
 def    __magic_name__		(					self		:							List[Any]					)		->  Optional[int]:
       pass




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




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




 def    __magic_name__		(					self		:							int					)		->  List[Any]:
       SCREAMING_SNAKE_CASE__						,		SCREAMING_SNAKE_CASE__   : List[str]													=self.model_tester.prepare_config_and_inputs_for_common()

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

             SCREAMING_SNAKE_CASE__   : Any													=['''pixel_values''']
             self.assertListEqual(arg_names[:1]    ,					_a					)




 def    __magic_name__		(					self		:							Dict					)		->  Union[str, Any]:
       SCREAMING_SNAKE_CASE__   : Dict													=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_a					)




 def    __magic_name__		(					self		:							str					)		->  Optional[Any]:






       def check_hidden_states_output(__lowercase		:							str    ,					__lowercase		:							Optional[int]    ,					__lowercase		:							Dict					):
             SCREAMING_SNAKE_CASE__   : Optional[int]													=model_class(_a					)
             model.to(_a					)
             model.eval()

             with torch.no_grad():
                   SCREAMING_SNAKE_CASE__   : Any													=model(**self._prepare_for_class(_a    ,					_a					)					)

             SCREAMING_SNAKE_CASE__   : List[str]													=outputs.hidden_states

             SCREAMING_SNAKE_CASE__   : Dict													=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.
             SCREAMING_SNAKE_CASE__   : Dict													=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					)

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

       for model_class in self.all_model_classes:
             SCREAMING_SNAKE_CASE__   : Optional[int]													=True
             check_hidden_states_output(_a    ,					_a    ,					_a					)

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

             check_hidden_states_output(_a    ,					_a    ,					_a					)




 def    __magic_name__		(					self		:							int					)		->  List[str]:
       SCREAMING_SNAKE_CASE__   : Tuple													=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*_a					)




 def    __magic_name__		(					self		:							Dict					)		->  Union[str, Any]:
       SCREAMING_SNAKE_CASE__   : List[Any]													=self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*_a					)




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






       for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             SCREAMING_SNAKE_CASE__   : List[str]													=MobileViTVaModel.from_pretrained(_a					)
             self.assertIsNotNone(_a					)





def        _a(     ):




      '''simple docstring'''






      SCREAMING_SNAKE_CASE__   : List[str]													=Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''							)
      return image







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




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




 @slow
 def    __magic_name__		(					self		:							Optional[Any]					)		->  List[Any]:
       SCREAMING_SNAKE_CASE__   : int													=MobileViTVaForImageClassification.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256'''					).to(
           _a					)

       SCREAMING_SNAKE_CASE__   : Optional[int]													=self.default_image_processor
       SCREAMING_SNAKE_CASE__   : Any													=prepare_img()
       SCREAMING_SNAKE_CASE__   : List[Any]													=image_processor(images=_a    ,					return_tensors='''pt'''					).to(_a					)

       # forward pass
       with torch.no_grad():
             SCREAMING_SNAKE_CASE__   : int													=model(**_a					)

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

       SCREAMING_SNAKE_CASE__   : Optional[Any]													=torch.tensor([-1.6336e00, -7.3204e-02, -5.1883e-01]					).to(_a					)

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




 @slow
 def    __magic_name__		(					self		:							Union[str, Any]					)		->  Optional[int]:
       SCREAMING_SNAKE_CASE__   : List[str]													=MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''					)
       SCREAMING_SNAKE_CASE__   : int													=model.to(_a					)

       SCREAMING_SNAKE_CASE__   : Any													=MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''					)

       SCREAMING_SNAKE_CASE__   : Dict													=prepare_img()
       SCREAMING_SNAKE_CASE__   : int													=image_processor(images=_a    ,					return_tensors='''pt'''					).to(_a					)

       # forward pass
       with torch.no_grad():
             SCREAMING_SNAKE_CASE__   : Union[str, Any]													=model(**_a					)
       SCREAMING_SNAKE_CASE__   : Optional[Any]													=outputs.logits

       # verify the logits
       SCREAMING_SNAKE_CASE__   : Optional[Any]													=torch.Size((1, 21, 32, 32)					)
       self.assertEqual(logits.shape    ,					_a					)

       SCREAMING_SNAKE_CASE__   : List[str]													=torch.tensor(
           [
               [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]],
               [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]],
               [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]],
           ]    ,					device=_a    ,					)

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




 @slow
 def    __magic_name__		(					self		:							Optional[int]					)		->  List[Any]:
       SCREAMING_SNAKE_CASE__   : List[str]													=MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''					)
       SCREAMING_SNAKE_CASE__   : List[str]													=model.to(_a					)

       SCREAMING_SNAKE_CASE__   : List[str]													=MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3'''					)

       SCREAMING_SNAKE_CASE__   : str													=prepare_img()
       SCREAMING_SNAKE_CASE__   : Union[str, Any]													=image_processor(images=_a    ,					return_tensors='''pt'''					).to(_a					)

       # forward pass
       with torch.no_grad():
             SCREAMING_SNAKE_CASE__   : Optional[int]													=model(**_a					)

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

       SCREAMING_SNAKE_CASE__   : Any													=image_processor.post_process_semantic_segmentation(outputs=_a    ,					target_sizes=[(50, 60)]					)
       SCREAMING_SNAKE_CASE__   : Optional[int]													=torch.Size((50, 60)					)
       self.assertEqual(segmentation[0].shape    ,					_a					)

       SCREAMING_SNAKE_CASE__   : Optional[Any]													=image_processor.post_process_semantic_segmentation(outputs=_a					)
       SCREAMING_SNAKE_CASE__   : Union[str, Any]													=torch.Size((32, 32)					)
       self.assertEqual(segmentation[0].shape    ,					_a					)


'''simple docstring'''
import unittest

import numpy as np
import torch

from diffusers import VersatileDiffusionImageVariationPipeline
from diffusers.utils.testing_utils import load_image, require_torch_gpu, slow, torch_device


lowerCamelCase :      Optional[int]					 =     False







class 							A__    (       unittest.TestCase  ):
  pass







@slow
@require_torch_gpu
class 							A__    (       unittest.TestCase  ):





  def 						A  (		self      :	Tuple )	->    Dict:





       '''simple docstring'''






       _SCREAMING_SNAKE_CASE							    =VersatileDiffusionImageVariationPipeline.from_pretrained('shi-labs/versatile-diffusion' )
       pipe.to(_a )
       pipe.set_progress_bar_config(disable=_a )

       _SCREAMING_SNAKE_CASE							    =load_image(
           'https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/versatile_diffusion/benz.jpg' )
       _SCREAMING_SNAKE_CASE							    =torch.manual_seed(0 )
       _SCREAMING_SNAKE_CASE							    =pipe(
           image=_a							,					generator=_a							,					guidance_scale=7.5							,					num_inference_steps=50							,					output_type='numpy'							,					).images

       _SCREAMING_SNAKE_CASE							    =image[0, 253:256, 253:256, -1]

       assert image.shape == (1, 512, 512, 3)
       _SCREAMING_SNAKE_CASE							    =np.array([0.04_41, 0.04_69, 0.05_07, 0.05_75, 0.06_32, 0.06_50, 0.08_65, 0.09_09, 0.09_45] )

       assert np.abs(image_slice.flatten() - expected_slice ).max() < 1e-2
