





"""simple docstring"""
from __future__ import annotations

import inspect
import unittest

import numpy as np

from transformers import DeiTConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import tensorflow as tf

		from transformers import (
		    TFDeiTForImageClassification,
		    TFDeiTForImageClassificationWithTeacher,
		    TFDeiTForMaskedImageModeling,
		    TFDeiTModel,
		)
		from transformers.models.deit.modeling_tf_deit import TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import DeiTImageProcessor






class 					_UpperCAmelCase   :


					def __init__(					self			:str     ,       __UpperCamelCase			:Dict     ,       __UpperCamelCase			:Tuple=13     ,       __UpperCamelCase			:Union[str, Any]=30     ,       __UpperCamelCase			:Tuple=2     ,       __UpperCamelCase			:Optional[Any]=3     ,       __UpperCamelCase			:Optional[int]=True     ,       __UpperCamelCase			:int=True     ,       __UpperCamelCase			:int=32     ,       __UpperCamelCase			:Optional[Any]=2     ,       __UpperCamelCase			:List[str]=4     ,       __UpperCamelCase			:Optional[Any]=37     ,       __UpperCamelCase			:Optional[Any]="gelu"     ,       __UpperCamelCase			:List[Any]=0.1     ,       __UpperCamelCase			:List[str]=0.1     ,       __UpperCamelCase			:Any=10     ,       __UpperCamelCase			:Dict=0.02     ,       __UpperCamelCase			:Union[str, Any]=3     ,       __UpperCamelCase			:Any=None     ,       __UpperCamelCase			:int=2     ,       ):
												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 DeiT, the seq length equals the number of patches + 2 (we add 2 for the [CLS] and distilation tokens)
												A		=  (image_size // patch_size) ** 2
												A		=  num_patches + 2


					def 	lowerCamelCase       (					self			:Tuple		):
												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 	lowerCamelCase       (					self			:List[str]		):
												return DeiTConfig(
												    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 	lowerCamelCase       (					self			:Union[str, Any]     ,       __UpperCamelCase			:Dict     ,       __UpperCamelCase			:List[str]     ,       __UpperCamelCase			:List[str]		):
												A		=  TFDeiTModel(config=A_		)
												A		=  model(A_		)
												self.parent.assertEqual(result.last_hidden_state.shape     ,       (self.batch_size, self.seq_length, self.hidden_size)		)


					def 	lowerCamelCase       (					self			:Union[str, Any]     ,       __UpperCamelCase			:Dict     ,       __UpperCamelCase			:Union[str, Any]     ,       __UpperCamelCase			:List[Any]		):
												A		=  TFDeiTForMaskedImageModeling(config=A_		)
												A		=  model(A_		)
												self.parent.assertEqual(
												    result.reconstruction.shape     ,       (self.batch_size, self.num_channels, self.image_size, self.image_size)		)

												# test greyscale images
												A		=  1
												A		=  TFDeiTForMaskedImageModeling(A_		)

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


					def 	lowerCamelCase       (					self			:Union[str, Any]     ,       __UpperCamelCase			:Optional[int]     ,       __UpperCamelCase			:Dict     ,       __UpperCamelCase			:str		):
												A		=  self.type_sequence_label_size
												A		=  TFDeiTForImageClassification(A_		)
												A		=  model(A_     ,       labels=A_		)
												self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.type_sequence_label_size)		)

												# test greyscale images
												A		=  1
												A		=  TFDeiTForImageClassification(A_		)

												A		=  floats_tensor([self.batch_size, 1, self.image_size, self.image_size]		)
												A		=  model(A_     ,       labels=A_		)
												self.parent.assertEqual(result.logits.shape     ,       (self.batch_size, self.type_sequence_label_size)		)


					def 	lowerCamelCase       (					self			:Tuple		):
												A		=  self.prepare_config_and_inputs()
												A,	A,	A		=  config_and_inputs
												A		=  {"pixel_values": pixel_values}
												return config, inputs_dict







@require_tf
class 					_UpperCAmelCase   (	_SCREAMING_SNAKE_CASE     ,							_SCREAMING_SNAKE_CASE     ,							unittest.TestCase ):
					UpperCamelCase      =							(
					    (
					        TFDeiTModel,
					        TFDeiTForImageClassification,
					        TFDeiTForImageClassificationWithTeacher,
					        TFDeiTForMaskedImageModeling,
					    )
					    if is_tf_available()
					    else ()
					)
					UpperCamelCase      =							(
					    {
					        "feature-extraction": TFDeiTModel,
					        "image-classification": (TFDeiTForImageClassification, TFDeiTForImageClassificationWithTeacher),
					    }
					    if is_tf_available()
					    else {}
					)

					UpperCamelCase      =							False
					UpperCamelCase      =							False
					UpperCamelCase      =							False
					UpperCamelCase      =							False


					def 	lowerCamelCase       (					self			:Any		):
												A		=  TFDeiTModelTester(self		)
												A		=  ConfigTester(self     ,       config_class=A_     ,       has_text_modality=A_     ,       hidden_size=37		)


					def 	lowerCamelCase       (					self			:int		):
												self.config_tester.run_common_tests()


					@unittest.skip(reason="DeiT does not use inputs_embeds"		)
					def 	lowerCamelCase       (					self			:Union[str, Any]		):
												pass


					def 	lowerCamelCase       (					self			:Union[str, Any]		):
												A,	A		=  self.model_tester.prepare_config_and_inputs_for_common()

												for model_class in self.all_model_classes:
																			A		=  model_class(A_		)
																			self.assertIsInstance(model.get_input_embeddings()     ,       (tf.keras.layers.Layer)		)
																			A		=  model.get_output_embeddings()
																			self.assertTrue(x is None or isinstance(A_     ,       tf.keras.layers.Dense		)		)


					def 	lowerCamelCase       (					self			:Optional[int]		):
												A,	A		=  self.model_tester.prepare_config_and_inputs_for_common()

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

																			A		=  ["pixel_values"]
																			self.assertListEqual(arg_names[:1]     ,       A_		)


					def 	lowerCamelCase       (					self			:Any		):
												A		=  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_model(*A_		)


					def 	lowerCamelCase       (					self			:str		):
												A		=  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_masked_image_modeling(*A_		)


					def 	lowerCamelCase       (					self			:List[Any]		):
												A		=  self.model_tester.prepare_config_and_inputs()
												self.model_tester.create_and_check_for_image_classification(*A_		)


					def 	lowerCamelCase       (					self			:Optional[Any]     ,       __UpperCamelCase			:Tuple     ,       __UpperCamelCase			:Any     ,       __UpperCamelCase			:List[str]=False		):
												A		=  super()._prepare_for_class(A_     ,       A_     ,       return_labels=A_		)

												if return_labels:
																			if "labels" in inputs_dict and "labels" not in inspect.signature(model_class.call		).parameters:
																										del inputs_dict["labels"]

												return inputs_dict


					@slow
					def 	lowerCamelCase       (					self			:Tuple		):
												for model_name in TF_DEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																			A		=  TFDeiTModel.from_pretrained(A_		)
																			self.assertIsNotNone(A_		)







def 					A__				(			):
							A		=  Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"       )
							return image






@require_tf
@require_vision
class 					_UpperCAmelCase   (	unittest.TestCase ):


					@cached_property
					def 	lowerCamelCase       (					self			:Optional[int]		):
												return (
												    DeiTImageProcessor.from_pretrained("facebook/deit-base-distilled-patch16-224"		)
												    if is_vision_available()
												    else None
												)


					@slow
					def 	lowerCamelCase       (					self			:Dict		):
												A		=  TFDeiTForImageClassificationWithTeacher.from_pretrained("facebook/deit-base-distilled-patch16-224"		)

												A		=  self.default_image_processor
												A		=  prepare_img()
												A		=  image_processor(images=A_     ,       return_tensors="tf"		)

												# forward pass
												A		=  model(**A_		)

												# verify the logits
												A		=  tf.TensorShape((1, 10_00)		)
												self.assertEqual(outputs.logits.shape     ,       A_		)

												A		=  tf.constant([-1.0_266, 0.1_912, -1.2_861]		)

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




import gc
import unittest

import numpy as np
import torch

from diffusers import StableDiffusionKDiffusionPipeline
from diffusers.utils import slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu


enable_full_determinism()


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



		def __UpperCamelCase ( self       )  ->					Dict:
				"""simple docstring"""
				# clean up the VRAM after each test
				super().tearDown()
				gc.collect()
				torch.cuda.empty_cache()



		def __UpperCamelCase ( self       )  ->					str:
				"""simple docstring"""
				UpperCamelCase		=     StableDiffusionKDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4'       )
				UpperCamelCase		=     sd_pipe.to(A_       )
				sd_pipe.set_progress_bar_config(disable=A_       )

				sd_pipe.set_scheduler('sample_euler'       )

				UpperCamelCase		=     'A painting of a squirrel eating a burger'
				UpperCamelCase		=     torch.manual_seed(0       )
				UpperCamelCase		=     sd_pipe([prompt]				,      generator=A_				,      guidance_scale=9.0				,      num_inference_steps=20				,      output_type='np'       )

				UpperCamelCase		=     output.images

				UpperCamelCase		=     image[0, -3:, -3:, -1]

				assert image.shape == (1, 512, 512, 3)
				UpperCamelCase		=     np.array([0.0447, 0.0492, 0.0468, 0.0408, 0.0383, 0.0408, 0.0354, 0.0380, 0.0339]       )

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



		def __UpperCamelCase ( self       )  ->					Any:
				"""simple docstring"""
				UpperCamelCase		=     StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'       )
				UpperCamelCase		=     sd_pipe.to(A_       )
				sd_pipe.set_progress_bar_config(disable=A_       )

				sd_pipe.set_scheduler('sample_euler'       )

				UpperCamelCase		=     'A painting of a squirrel eating a burger'
				UpperCamelCase		=     torch.manual_seed(0       )
				UpperCamelCase		=     sd_pipe([prompt]				,      generator=A_				,      guidance_scale=9.0				,      num_inference_steps=20				,      output_type='np'       )

				UpperCamelCase		=     output.images

				UpperCamelCase		=     image[0, -3:, -3:, -1]

				assert image.shape == (1, 512, 512, 3)
				UpperCamelCase		=     np.array([0.1237, 0.1320, 0.1438, 0.1359, 0.1390, 0.1132, 0.1277, 0.1175, 0.1112]       )

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



		def __UpperCamelCase ( self       )  ->					Optional[int]:
				"""simple docstring"""
				UpperCamelCase		=     StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'       )
				UpperCamelCase		=     sd_pipe.to(A_       )
				sd_pipe.set_progress_bar_config(disable=A_       )

				sd_pipe.set_scheduler('sample_dpmpp_2m'       )

				UpperCamelCase		=     'A painting of a squirrel eating a burger'
				UpperCamelCase		=     torch.manual_seed(0       )
				UpperCamelCase		=     sd_pipe(
				    [prompt]				,      generator=A_				,      guidance_scale=7.5				,      num_inference_steps=15				,      output_type='np'				,      use_karras_sigmas=A_				,      )

				UpperCamelCase		=     output.images

				UpperCamelCase		=     image[0, -3:, -3:, -1]

				assert image.shape == (1, 512, 512, 3)
				UpperCamelCase		=     np.array(
				    [0.1138_1689, 0.1211_2921, 0.138_9457, 0.1254_9606, 0.124_4964, 0.1083_1517, 0.1156_2866, 0.1086_7816, 0.1049_9048]       )

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