
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   ,A__   ,A__=1_3   ,A__=3_0   ,A__=2   ,A__=3   ,A__=True   ,A__=True   ,A__=3_2   ,A__=5   ,A__=4   ,A__=3_7   ,A__="gelu"   ,A__=0.1   ,A__=0.1   ,A__=1_0   ,A__=0.02   ,A__=None   ,A__=2   ,):
												lowercase							=						parent
												lowercase							=						batch_size
												lowercase							=						image_size
												lowercase							=						patch_size
												lowercase							=						num_channels
												lowercase							=						is_training
												lowercase							=						use_labels
												lowercase							=						hidden_size
												lowercase							=						num_hidden_layers
												lowercase							=						num_attention_heads
												lowercase							=						intermediate_size
												lowercase							=						hidden_act
												lowercase							=						hidden_dropout_prob
												lowercase							=						attention_probs_dropout_prob
												lowercase							=						type_sequence_label_size
												lowercase							=						initializer_range
												lowercase							=						scope
												lowercase							=						encoder_stride

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




							def  A__      (				self):
												lowercase							=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

												lowercase							=						self.get_config()

												return config, pixel_values, labels




							def  A__      (				self):
												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=A__   ,initializer_range=self.initializer_range   ,encoder_stride=self.encoder_stride   ,)




							def  A__      (				self   ,A__   ,A__   ,A__):
												lowercase							=						ViTModel(config=A__)
												model.to(A__)
												model.eval()
												lowercase							=						model(A__)
												self.parent.assertEqual(result.last_hidden_state.shape   ,(self.batch_size, self.seq_length, self.hidden_size))




							def  A__      (				self   ,A__   ,A__   ,A__):
												lowercase							=						ViTForMaskedImageModeling(config=A__)
												model.to(A__)
												model.eval()
												lowercase							=						model(A__)
												self.parent.assertEqual(
												    result.reconstruction.shape   ,(self.batch_size, self.num_channels, self.image_size, self.image_size))

												# test greyscale images
												lowercase							=						1
												lowercase							=						ViTForMaskedImageModeling(A__)
												model.to(A__)
												model.eval()

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




							def  A__      (				self   ,A__   ,A__   ,A__):
												lowercase							=						self.type_sequence_label_size
												lowercase							=						ViTForImageClassification(A__)
												model.to(A__)
												model.eval()
												lowercase							=						model(A__   ,labels=A__)
												self.parent.assertEqual(result.logits.shape   ,(self.batch_size, self.type_sequence_label_size))

												# test greyscale images
												lowercase							=						1
												lowercase							=						ViTForImageClassification(A__)
												model.to(A__)
												model.eval()

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





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







@require_torch
class 				lowercase		(					SCREAMING_SNAKE_CASE__       ,  SCREAMING_SNAKE_CASE__       ,  unittest.TestCase		):
							lowercase_       :       Tuple       					=(
							    (
							        ViTModel,
							        ViTForImageClassification,
							        ViTForMaskedImageModeling,
							    )
							    if is_torch_available()
							    else ()
							)
							lowercase_       :       List[Any]       					=(
							    {'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification}
							    if is_torch_available()
							    else {}
							)
							lowercase_       :       Dict       					=True

							lowercase_       :       Tuple       					=False
							lowercase_       :       Any       					=False
							lowercase_       :       str       					=False




							def  A__      (				self):
												lowercase							=						ViTModelTester(self)
												lowercase							=						ConfigTester(self   ,config_class=A__   ,has_text_modality=A__   ,hidden_size=3_7)




							def  A__      (				self):
												self.config_tester.run_common_tests()




							@unittest.skip(reason='''ViT does not use inputs_embeds''')
							def  A__      (				self):
												pass




							def  A__      (				self):
												lowercase	,						lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

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




							def  A__      (				self):
												lowercase	,						lowercase							=						self.model_tester.prepare_config_and_inputs_for_common()

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

																	lowercase							=						['''pixel_values''']
																	self.assertListEqual(arg_names[:1]   ,A__)




							def  A__      (				self):
												lowercase							=						self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*A__)




							def  A__      (				self):
												lowercase							=						self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_masked_image_modeling(*A__)




							def  A__      (				self):
												lowercase							=						self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*A__)





							@slow
							def  A__      (				self):
												for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	lowercase							=						ViTModel.from_pretrained(A__)
																	self.assertIsNotNone(A__)



def        UpperCamelCase    (							):
					'''simple docstring'''
					lowercase							=						Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
					return image







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




							@cached_property
							def  A__      (				self):
												return ViTImageProcessor.from_pretrained('''google/vit-base-patch16-224''') if is_vision_available() else None




							@slow
							def  A__      (				self):
												lowercase							=						ViTForImageClassification.from_pretrained('''google/vit-base-patch16-224''').to(A__)

												lowercase							=						self.default_image_processor
												lowercase							=						prepare_img()
												lowercase							=						image_processor(images=A__   ,return_tensors='''pt''').to(A__)

												# forward pass
												with torch.no_grad():
																	lowercase							=						model(**A__)

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

												lowercase							=						torch.tensor([-0.2744, 0.8215, -0.0836]).to(A__)

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




							@slow
							def  A__      (				self):
												# ViT models have an `interpolate_pos_encoding` argument in their forward method,
												# allowing to interpolate the pre-trained position embeddings in order to use
												# the model on higher resolutions. The DINO model by Facebook AI leverages this
												# to visualize self-attention on higher resolution images.
												lowercase							=						ViTModel.from_pretrained('''facebook/dino-vits8''').to(A__)

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

												# forward pass
												with torch.no_grad():
																	lowercase							=						model(A__   ,interpolate_pos_encoding=A__)

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

												lowercase							=						torch.tensor(
												    [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]]).to(A__)

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





							@slow
							@require_accelerate
							@require_torch_gpu
							def  A__      (				self):
												lowercase							=						ViTModel.from_pretrained('''facebook/dino-vits8'''   ,torch_dtype=torch.floataa   ,device_map='''auto''')
												lowercase							=						self.default_image_processor

												lowercase							=						prepare_img()
												lowercase							=						image_processor(images=A__   ,return_tensors='''pt''')
												lowercase							=						inputs.pixel_values.to(A__)

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






import gc
import random
import unittest

import torch

from diffusers import (
    IFImgaImgPipeline,
    IFImgaImgSuperResolutionPipeline,
    IFInpaintingPipeline,
    IFInpaintingSuperResolutionPipeline,
    IFPipeline,
    IFSuperResolutionPipeline,
)
from diffusers.models.attention_processor import AttnAddedKVProcessor
from diffusers.utils.import_utils import is_xformers_available
from diffusers.utils.testing_utils import floats_tensor, load_numpy, require_torch_gpu, skip_mps, slow, torch_device

from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
from . import IFPipelineTesterMixin







@skip_mps
class 				lowercase		(					SCREAMING_SNAKE_CASE__       ,  SCREAMING_SNAKE_CASE__       ,  unittest.TestCase		):
							lowercase_       :       Optional[Any]       					=IFPipeline
							lowercase_       :       List[str]       					=TEXT_TO_IMAGE_PARAMS - {'''width''', '''height''', '''latents'''}
							lowercase_       :       List[str]       					=TEXT_TO_IMAGE_BATCH_PARAMS
							lowercase_       :       int       					=PipelineTesterMixin.required_optional_params - {'''latents'''}




							def  A__      (				self):
												return self._get_dummy_components()




							def  A__      (				self   ,A__   ,A__=0):
												if str(A__).startswith('''mps'''):
																	lowercase							=						torch.manual_seed(A__)
												else:
																	lowercase							=						torch.Generator(device=A__).manual_seed(A__)

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

												return inputs




							def  A__      (				self):
												self._test_save_load_optional_components()




							@unittest.skipIf(torch_device != '''cuda'''   ,reason='''float16 requires CUDA''')
							def  A__      (				self):
												# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
												super().test_save_load_floataa(expected_max_diff=1E-1)




							def  A__      (				self):
												self._test_attention_slicing_forward_pass(expected_max_diff=1E-2)




							def  A__      (				self):
												self._test_save_load_local()




							def  A__      (				self):
												self._test_inference_batch_single_identical(
												    expected_max_diff=1E-2   ,)





							@unittest.skipIf(
							    torch_device != '''cuda''' or not is_xformers_available()   ,reason='''XFormers attention is only available with CUDA and `xformers` installed'''   ,)
							def  A__      (				self):
												self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1E-3)







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




							def  A__      (				self):
												# clean up the VRAM after each test
												super().tearDown()
												gc.collect()
												torch.cuda.empty_cache()




							def  A__      (				self):
												# if

												lowercase							=						IFPipeline.from_pretrained('''DeepFloyd/IF-I-XL-v1.0'''   ,variant='''fp16'''   ,torch_dtype=torch.floataa)

												lowercase							=						IFSuperResolutionPipeline.from_pretrained(
												    '''DeepFloyd/IF-II-L-v1.0'''   ,variant='''fp16'''   ,torch_dtype=torch.floataa   ,text_encoder=A__   ,tokenizer=A__)

												# pre compute text embeddings and remove T5 to save memory

												pipe_a.text_encoder.to('''cuda''')

												lowercase	,						lowercase							=						pipe_a.encode_prompt('''anime turtle'''   ,device='''cuda''')

												del pipe_a.tokenizer
												del pipe_a.text_encoder
												gc.collect()

												lowercase							=						None
												lowercase							=						None

												pipe_a.enable_model_cpu_offload()
												pipe_a.enable_model_cpu_offload()

												pipe_a.unet.set_attn_processor(AttnAddedKVProcessor())
												pipe_a.unet.set_attn_processor(AttnAddedKVProcessor())

												self._test_if(A__   ,A__   ,A__   ,A__)

												pipe_a.remove_all_hooks()
												pipe_a.remove_all_hooks()

												# img2img

												lowercase							=						IFImgaImgPipeline(**pipe_a.components)
												lowercase							=						IFImgaImgSuperResolutionPipeline(**pipe_a.components)

												pipe_a.enable_model_cpu_offload()
												pipe_a.enable_model_cpu_offload()

												pipe_a.unet.set_attn_processor(AttnAddedKVProcessor())
												pipe_a.unet.set_attn_processor(AttnAddedKVProcessor())

												self._test_if_imgaimg(A__   ,A__   ,A__   ,A__)

												pipe_a.remove_all_hooks()
												pipe_a.remove_all_hooks()

												# inpainting

												lowercase							=						IFInpaintingPipeline(**pipe_a.components)
												lowercase							=						IFInpaintingSuperResolutionPipeline(**pipe_a.components)

												pipe_a.enable_model_cpu_offload()
												pipe_a.enable_model_cpu_offload()

												pipe_a.unet.set_attn_processor(AttnAddedKVProcessor())
												pipe_a.unet.set_attn_processor(AttnAddedKVProcessor())

												self._test_if_inpainting(A__   ,A__   ,A__   ,A__)




							def  A__      (				self   ,A__   ,A__   ,A__   ,A__):
												# pipeline 1

												_start_torch_memory_measurement()

												lowercase							=						torch.Generator(device='''cpu''').manual_seed(0)
												lowercase							=						pipe_a(
												    prompt_embeds=A__   ,negative_prompt_embeds=A__   ,num_inference_steps=2   ,generator=A__   ,output_type='''np'''   ,)

												lowercase							=						output.images[0]

												assert image.shape == (6_4, 6_4, 3)

												lowercase							=						torch.cuda.max_memory_allocated()
												assert mem_bytes < 1_3 * 1_0**9

												lowercase							=						load_numpy(
												    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy''')
												assert_mean_pixel_difference(A__   ,A__)

												# pipeline 2

												_start_torch_memory_measurement()

												lowercase							=						torch.Generator(device='''cpu''').manual_seed(0)

												lowercase							=						floats_tensor((1, 3, 6_4, 6_4)   ,rng=random.Random(0)).to(A__)

												lowercase							=						pipe_a(
												    prompt_embeds=A__   ,negative_prompt_embeds=A__   ,image=A__   ,generator=A__   ,num_inference_steps=2   ,output_type='''np'''   ,)

												lowercase							=						output.images[0]

												assert image.shape == (2_5_6, 2_5_6, 3)

												lowercase							=						torch.cuda.max_memory_allocated()
												assert mem_bytes < 4 * 1_0**9

												lowercase							=						load_numpy(
												    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy''')
												assert_mean_pixel_difference(A__   ,A__)




							def  A__      (				self   ,A__   ,A__   ,A__   ,A__):
												# pipeline 1

												_start_torch_memory_measurement()

												lowercase							=						floats_tensor((1, 3, 6_4, 6_4)   ,rng=random.Random(0)).to(A__)

												lowercase							=						torch.Generator(device='''cpu''').manual_seed(0)

												lowercase							=						pipe_a(
												    prompt_embeds=A__   ,negative_prompt_embeds=A__   ,image=A__   ,num_inference_steps=2   ,generator=A__   ,output_type='''np'''   ,)

												lowercase							=						output.images[0]

												assert image.shape == (6_4, 6_4, 3)

												lowercase							=						torch.cuda.max_memory_allocated()
												assert mem_bytes < 1_0 * 1_0**9

												lowercase							=						load_numpy(
												    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy''')
												assert_mean_pixel_difference(A__   ,A__)

												# pipeline 2

												_start_torch_memory_measurement()

												lowercase							=						torch.Generator(device='''cpu''').manual_seed(0)

												lowercase							=						floats_tensor((1, 3, 2_5_6, 2_5_6)   ,rng=random.Random(0)).to(A__)
												lowercase							=						floats_tensor((1, 3, 6_4, 6_4)   ,rng=random.Random(0)).to(A__)

												lowercase							=						pipe_a(
												    prompt_embeds=A__   ,negative_prompt_embeds=A__   ,image=A__   ,original_image=A__   ,generator=A__   ,num_inference_steps=2   ,output_type='''np'''   ,)

												lowercase							=						output.images[0]

												assert image.shape == (2_5_6, 2_5_6, 3)

												lowercase							=						torch.cuda.max_memory_allocated()
												assert mem_bytes < 4 * 1_0**9

												lowercase							=						load_numpy(
												    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy''')
												assert_mean_pixel_difference(A__   ,A__)





							def  A__      (				self   ,A__   ,A__   ,A__   ,A__):
												# pipeline 1

												_start_torch_memory_measurement()

												lowercase							=						floats_tensor((1, 3, 6_4, 6_4)   ,rng=random.Random(0)).to(A__)
												lowercase							=						floats_tensor((1, 3, 6_4, 6_4)   ,rng=random.Random(1)).to(A__)

												lowercase							=						torch.Generator(device='''cpu''').manual_seed(0)
												lowercase							=						pipe_a(
												    prompt_embeds=A__   ,negative_prompt_embeds=A__   ,image=A__   ,mask_image=A__   ,num_inference_steps=2   ,generator=A__   ,output_type='''np'''   ,)

												lowercase							=						output.images[0]

												assert image.shape == (6_4, 6_4, 3)

												lowercase							=						torch.cuda.max_memory_allocated()
												assert mem_bytes < 1_0 * 1_0**9

												lowercase							=						load_numpy(
												    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy''')
												assert_mean_pixel_difference(A__   ,A__)

												# pipeline 2

												_start_torch_memory_measurement()

												lowercase							=						torch.Generator(device='''cpu''').manual_seed(0)

												lowercase							=						floats_tensor((1, 3, 6_4, 6_4)   ,rng=random.Random(0)).to(A__)
												lowercase							=						floats_tensor((1, 3, 2_5_6, 2_5_6)   ,rng=random.Random(0)).to(A__)
												lowercase							=						floats_tensor((1, 3, 2_5_6, 2_5_6)   ,rng=random.Random(1)).to(A__)

												lowercase							=						pipe_a(
												    prompt_embeds=A__   ,negative_prompt_embeds=A__   ,image=A__   ,mask_image=A__   ,original_image=A__   ,generator=A__   ,num_inference_steps=2   ,output_type='''np'''   ,)

												lowercase							=						output.images[0]

												assert image.shape == (2_5_6, 2_5_6, 3)

												lowercase							=						torch.cuda.max_memory_allocated()
												assert mem_bytes < 4 * 1_0**9

												lowercase							=						load_numpy(
												    '''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy''')
												assert_mean_pixel_difference(A__   ,A__)



def        UpperCamelCase    (							):
					'''simple docstring'''
					torch.cuda.empty_cache()
					torch.cuda.reset_max_memory_allocated()
					torch.cuda.reset_peak_memory_stats()




