
"""simple docstring"""




import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_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 torch import nn

    from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
    from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import ViTImageProcessor







class     lowercase:



     def __init__(							self     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE=1_3     ,				__SCREAMING_SNAKE_CASE=3_0     ,				__SCREAMING_SNAKE_CASE=2     ,				__SCREAMING_SNAKE_CASE=3     ,				__SCREAMING_SNAKE_CASE=True     ,				__SCREAMING_SNAKE_CASE=True     ,				__SCREAMING_SNAKE_CASE=3_2     ,				__SCREAMING_SNAKE_CASE=5     ,				__SCREAMING_SNAKE_CASE=4     ,				__SCREAMING_SNAKE_CASE=3_7     ,				__SCREAMING_SNAKE_CASE="gelu"     ,				__SCREAMING_SNAKE_CASE=0.1     ,				__SCREAMING_SNAKE_CASE=0.1     ,				__SCREAMING_SNAKE_CASE=1_0     ,				__SCREAMING_SNAKE_CASE=0.02     ,				__SCREAMING_SNAKE_CASE=None     ,				__SCREAMING_SNAKE_CASE=2     ,				)		->     List[str]:







         """simple docstring"""



         a__		=			parent
         a__		=			batch_size
         a__		=			image_size
         a__		=			patch_size
         a__		=			num_channels
         a__		=			is_training
         a__		=			use_labels
         a__		=			hidden_size
         a__		=			num_hidden_layers
         a__		=			num_attention_heads
         a__		=			intermediate_size
         a__		=			hidden_act
         a__		=			hidden_dropout_prob
         a__		=			attention_probs_dropout_prob
         a__		=			type_sequence_label_size
         a__		=			initializer_range
         a__		=			scope
         a__		=			encoder_stride

         # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
         a__		=			(image_size // patch_size) ** 2
         a__		=			num_patches + 1



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







         """simple docstring"""



         a__		=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

         a__		=			None
         if self.use_labels:
             a__		=			ids_tensor([self.batch_size]     ,				self.type_sequence_label_size   )

         a__		=			self.get_config()

         return config, pixel_values, labels



     def 			lowercase__  (							self   )		->     List[str]:







         """simple docstring"""



         return ViTConfig(
             image_size=self.image_size     ,				patch_size=self.patch_size     ,				num_channels=self.num_channels     ,				hidden_size=self.hidden_size     ,				num_hidden_layers=self.num_hidden_layers     ,				num_attention_heads=self.num_attention_heads     ,				intermediate_size=self.intermediate_size     ,				hidden_act=self.hidden_act     ,				hidden_dropout_prob=self.hidden_dropout_prob     ,				attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,				is_decoder=__SCREAMING_SNAKE_CASE     ,				initializer_range=self.initializer_range     ,				encoder_stride=self.encoder_stride     ,				)



     def 			lowercase__  (							self     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE   )		->     List[str]:







         """simple docstring"""



         a__		=			ViTModel(config=__SCREAMING_SNAKE_CASE   )
         model.to(__SCREAMING_SNAKE_CASE   )
         model.eval()
         a__		=			model(__SCREAMING_SNAKE_CASE   )
         self.parent.assertEqual(result.last_hidden_state.shape     ,				(self.batch_size, self.seq_length, self.hidden_size)   )



     def 			lowercase__  (							self     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE   )		->     Union[str, Any]:







         """simple docstring"""



         a__		=			ViTForMaskedImageModeling(config=__SCREAMING_SNAKE_CASE   )
         model.to(__SCREAMING_SNAKE_CASE   )
         model.eval()
         a__		=			model(__SCREAMING_SNAKE_CASE   )
         self.parent.assertEqual(
             result.reconstruction.shape     ,				(self.batch_size, self.num_channels, self.image_size, self.image_size)   )

         # test greyscale images
         a__		=			1
         a__		=			ViTForMaskedImageModeling(__SCREAMING_SNAKE_CASE   )
         model.to(__SCREAMING_SNAKE_CASE   )
         model.eval()

         a__		=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]   )
         a__		=			model(__SCREAMING_SNAKE_CASE   )
         self.parent.assertEqual(result.reconstruction.shape     ,				(self.batch_size, 1, self.image_size, self.image_size)   )



     def 			lowercase__  (							self     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE   )		->     Optional[int]:







         """simple docstring"""



         a__		=			self.type_sequence_label_size
         a__		=			ViTForImageClassification(__SCREAMING_SNAKE_CASE   )
         model.to(__SCREAMING_SNAKE_CASE   )
         model.eval()
         a__		=			model(__SCREAMING_SNAKE_CASE     ,				labels=__SCREAMING_SNAKE_CASE   )
         self.parent.assertEqual(result.logits.shape     ,				(self.batch_size, self.type_sequence_label_size)   )

         # test greyscale images
         a__		=			1
         a__		=			ViTForImageClassification(__SCREAMING_SNAKE_CASE   )
         model.to(__SCREAMING_SNAKE_CASE   )
         model.eval()

         a__		=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]   )
         a__		=			model(__SCREAMING_SNAKE_CASE   )
         self.parent.assertEqual(result.logits.shape     ,				(self.batch_size, self.type_sequence_label_size)   )




     def 			lowercase__  (							self   )		->     Union[str, Any]:







         """simple docstring"""



         a__		=			self.prepare_config_and_inputs()
         (
             (
             a__
         )	,     (
             a__
         )	,     (
             a__
         )	,     
         )		=			config_and_inputs
         a__		=			{'pixel_values': pixel_values}
         return config, inputs_dict







@require_torch
class     lowercase(_lowercase    ,						_lowercase    ,						unittest.TestCase       ):
     __snake_case:	int						=     (
         (
             ViTModel,
             ViTForImageClassification,
             ViTForMaskedImageModeling,
         )
         if is_torch_available()
         else ()
     )
     __snake_case:	Any						=     (
         {'feature-extraction': ViTModel, 'image-classification': ViTForImageClassification}
         if is_torch_available()
         else {}
     )
     __snake_case:	Optional[Any]						=     True

     __snake_case:	int						=     False
     __snake_case:	Dict						=     False
     __snake_case:	str						=     False



     def 			lowercase__  (							self   )		->     int:







         """simple docstring"""



         a__		=			ViTModelTester(self   )
         a__		=			ConfigTester(self     ,				config_class=__SCREAMING_SNAKE_CASE     ,				has_text_modality=__SCREAMING_SNAKE_CASE     ,				hidden_size=3_7   )



     def 			lowercase__  (							self   )		->     str:







         """simple docstring"""



         self.config_tester.run_common_tests()



     @unittest.skip(reason='ViT does not use inputs_embeds'   )
     def 			lowercase__  (							self   )		->     Optional[Any]:







         """simple docstring"""



         pass



     def 			lowercase__  (							self   )		->     Dict:







         """simple docstring"""



         a__	,     a__		=			self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
             a__		=			model_class(__SCREAMING_SNAKE_CASE   )
             self.assertIsInstance(model.get_input_embeddings()     ,				(nn.Module)   )
             a__		=			model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(__SCREAMING_SNAKE_CASE     ,				nn.Linear   )   )



     def 			lowercase__  (							self   )		->     Union[str, Any]:







         """simple docstring"""



         a__	,     a__		=			self.model_tester.prepare_config_and_inputs_for_common()

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

             a__		=			['pixel_values']
             self.assertListEqual(arg_names[:1]     ,				__SCREAMING_SNAKE_CASE   )



     def 			lowercase__  (							self   )		->     List[Any]:







         """simple docstring"""



         a__		=			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__SCREAMING_SNAKE_CASE   )



     def 			lowercase__  (							self   )		->     Union[str, Any]:







         """simple docstring"""



         a__		=			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_masked_image_modeling(*__SCREAMING_SNAKE_CASE   )



     def 			lowercase__  (							self   )		->     Tuple:







         """simple docstring"""



         a__		=			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__SCREAMING_SNAKE_CASE   )




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







         """simple docstring"""



         for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             a__		=			ViTModel.from_pretrained(__SCREAMING_SNAKE_CASE   )
             self.assertIsNotNone(__SCREAMING_SNAKE_CASE   )




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







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



     @cached_property
     def 			lowercase__  (							self   )		->     Dict:







         """simple docstring"""



         return ViTImageProcessor.from_pretrained('google/vit-base-patch16-224'   ) if is_vision_available() else None



     @slow
     def 			lowercase__  (							self   )		->     Any:







         """simple docstring"""



         a__		=			ViTForImageClassification.from_pretrained('google/vit-base-patch16-224'   ).to(__SCREAMING_SNAKE_CASE   )

         a__		=			self.default_image_processor
         a__		=			prepare_img()
         a__		=			image_processor(images=__SCREAMING_SNAKE_CASE     ,				return_tensors='pt'   ).to(__SCREAMING_SNAKE_CASE   )

         # forward pass
         with torch.no_grad():
             a__		=			model(**__SCREAMING_SNAKE_CASE   )

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

         a__		=			torch.tensor([-0.27_44, 0.82_15, -0.08_36]   ).to(__SCREAMING_SNAKE_CASE   )

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



     @slow
     def 			lowercase__  (							self   )		->     Any:







         """simple docstring"""



         a__		=			ViTModel.from_pretrained('facebook/dino-vits8'   ).to(__SCREAMING_SNAKE_CASE   )

         a__		=			ViTImageProcessor.from_pretrained('facebook/dino-vits8'     ,				size=4_8_0   )
         a__		=			prepare_img()
         a__		=			image_processor(images=__SCREAMING_SNAKE_CASE     ,				return_tensors='pt'   )
         a__		=			inputs.pixel_values.to(__SCREAMING_SNAKE_CASE   )

         # forward pass
         with torch.no_grad():
             a__		=			model(__SCREAMING_SNAKE_CASE     ,				interpolate_pos_encoding=__SCREAMING_SNAKE_CASE   )

         # verify the logits
         a__		=			torch.Size((1, 3_6_0_1, 3_8_4)   )
         self.assertEqual(outputs.last_hidden_state.shape     ,				__SCREAMING_SNAKE_CASE   )

         a__		=			torch.tensor(
             [[4.23_40, 4.39_06, -6.66_92], [4.54_63, 1.89_28, -6.72_57], [4.44_29, 0.84_96, -5.85_85]]   ).to(__SCREAMING_SNAKE_CASE   )

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




     @slow
     @require_accelerate
     @require_torch_gpu
     def 			lowercase__  (							self   )		->     Tuple:







         """simple docstring"""



         a__		=			ViTModel.from_pretrained('facebook/dino-vits8'     ,				torch_dtype=torch.floataa     ,				device_map='auto'   )
         a__		=			self.default_image_processor

         a__		=			prepare_img()
         a__		=			image_processor(images=__SCREAMING_SNAKE_CASE     ,				return_tensors='pt'   )
         a__		=			inputs.pixel_values.to(__SCREAMING_SNAKE_CASE   )

         # forward pass to make sure inference works in fp16
         with torch.no_grad():
             a__		=			model(__SCREAMING_SNAKE_CASE   )




"""simple docstring"""




import random
import unittest

import torch

from diffusers import IFImgaImgSuperResolutionPipeline
from diffusers.utils import floats_tensor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import skip_mps, torch_device

from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
from ..test_pipelines_common import PipelineTesterMixin
from . import IFPipelineTesterMixin







@skip_mps
class     lowercase(_lowercase    ,						_lowercase    ,						unittest.TestCase       ):
     __snake_case:	Optional[int]						=     IFImgaImgSuperResolutionPipeline
     __snake_case:	Dict						=     TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {'width', 'height'}
     __snake_case:	Any						=     TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({'original_image'}       )
     __snake_case:	List[Any]						=     PipelineTesterMixin.required_optional_params - {'latents'}



     def 			lowercase__  (							self   )		->     Tuple:







         """simple docstring"""



         return self._get_superresolution_dummy_components()



     def 			lowercase__  (							self     ,				__SCREAMING_SNAKE_CASE     ,				__SCREAMING_SNAKE_CASE=0   )		->     Union[str, Any]:







         """simple docstring"""



         if str(__SCREAMING_SNAKE_CASE   ).startswith('mps'   ):
             a__		=			torch.manual_seed(__SCREAMING_SNAKE_CASE   )
         else:
             a__		=			torch.Generator(device=__SCREAMING_SNAKE_CASE   ).manual_seed(__SCREAMING_SNAKE_CASE   )

         a__		=			floats_tensor((1, 3, 3_2, 3_2)     ,				rng=random.Random(__SCREAMING_SNAKE_CASE   )   ).to(__SCREAMING_SNAKE_CASE   )
         a__		=			floats_tensor((1, 3, 1_6, 1_6)     ,				rng=random.Random(__SCREAMING_SNAKE_CASE   )   ).to(__SCREAMING_SNAKE_CASE   )

         a__		=			{
             'prompt': 'A painting of a squirrel eating a burger',
             'image': image,
             'original_image': original_image,
             'generator': generator,
             'num_inference_steps': 2,
             'output_type': 'numpy',
         }

         return inputs



     @unittest.skipIf(
         torch_device != 'cuda' or not is_xformers_available()     ,				reason='XFormers attention is only available with CUDA and `xformers` installed'     ,				)
     def 			lowercase__  (							self   )		->     Optional[int]:







         """simple docstring"""



         self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3   )



     def 			lowercase__  (							self   )		->     Any:







         """simple docstring"""



         self._test_save_load_optional_components()



     @unittest.skipIf(torch_device != 'cuda'     ,				reason='float16 requires CUDA'   )
     def 			lowercase__  (							self   )		->     List[Any]:







         """simple docstring"""



         super().test_save_load_floataa(expected_max_diff=1e-1   )



     def 			lowercase__  (							self   )		->     List[str]:







         """simple docstring"""



         self._test_attention_slicing_forward_pass(expected_max_diff=1e-2   )



     def 			lowercase__  (							self   )		->     Optional[Any]:







         """simple docstring"""



         self._test_save_load_local()




     def 			lowercase__  (							self   )		->     Any:







         """simple docstring"""



         self._test_inference_batch_single_identical(
             expected_max_diff=1e-2     ,				)


