






import inspect
import unittest

import numpy as np

from tests.test_modeling_common import floats_tensor
from transformers import MaskaFormerConfig, is_torch_available, is_vision_available
from transformers.testing_utils import require_torch, require_torch_multi_gpu, require_vision, slow, torch_device
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
	import torch

	from transformers import MaskaFormerForUniversalSegmentation, MaskaFormerModel

	if is_vision_available():
		from transformers import MaskaFormerImageProcessor

if is_vision_available():
	from PIL import Image

class     _SCREAMING_SNAKE_CASE       :





	def __init__(		self				:					Dict ,  __lowerCamelCase				:					Union[str, Any] ,  __lowerCamelCase				:					Union[str, Any]=2 ,  __lowerCamelCase				:					List[str]=True ,  __lowerCamelCase				:					Dict=False ,  __lowerCamelCase				:					Any=10 ,  __lowerCamelCase				:					Union[str, Any]=3 ,  __lowerCamelCase				:					Optional[Any]=32 * 8 ,  __lowerCamelCase				:					Tuple=32 * 8 ,  __lowerCamelCase				:					Union[str, Any]=4 ,  __lowerCamelCase				:					Tuple=64 ,  ):
		UpperCamelCase     :int          =	parent
		UpperCamelCase     :Optional[Any]          =	batch_size
		UpperCamelCase     :Tuple          =	is_training
		UpperCamelCase     :Tuple          =	use_auxiliary_loss
		UpperCamelCase     :Dict          =	num_queries
		UpperCamelCase     :Any          =	num_channels
		UpperCamelCase     :List[Any]          =	min_size
		UpperCamelCase     :Any          =	max_size
		UpperCamelCase     :List[str]          =	num_labels
		UpperCamelCase     :Dict          =	hidden_dim
		UpperCamelCase     :Optional[Any]          =	hidden_dim





	def 						_A (		self				:					Any	):
		UpperCamelCase     :Optional[Any]          =	floats_tensor([self.batch_size, self.num_channels, self.min_size, self.max_size]	).to(
		    __lowerCamelCase	)

		UpperCamelCase     :Optional[int]          =	torch.ones([self.batch_size, self.min_size, self.max_size] ,  device=__lowerCamelCase	)

		UpperCamelCase     :Optional[Any]          =	(
		    torch.rand([self.batch_size, self.num_labels, self.min_size, self.max_size] ,  device=__lowerCamelCase	) > 0.5
		).float()
		UpperCamelCase     :Any          =	(torch.rand((self.batch_size, self.num_labels) ,  device=__lowerCamelCase	) > 0.5).long()

		UpperCamelCase     :List[Any]          =	self.get_config()
		return config, pixel_values, pixel_mask, mask_labels, class_labels





	def 						_A (		self				:					Optional[int]	):
		UpperCamelCase     :int          =	MaskaFormerConfig(
		    hidden_size=self.hidden_dim ,  )
		UpperCamelCase     :Tuple          =	self.num_queries
		UpperCamelCase     :Optional[Any]          =	self.num_labels

		UpperCamelCase     :Any          =	[1, 1, 1, 1]
		UpperCamelCase     :List[str]          =	self.num_channels

		UpperCamelCase     :int          =	64
		UpperCamelCase     :Union[str, Any]          =	128
		UpperCamelCase     :Optional[Any]          =	self.hidden_dim
		UpperCamelCase     :List[Any]          =	self.hidden_dim
		UpperCamelCase     :List[str]          =	self.hidden_dim
		return config





	def 						_A (		self				:					List[Any]	):
		UpperCamelCase     ,      UpperCamelCase     ,      UpperCamelCase     ,      UpperCamelCase     ,      UpperCamelCase     :List[str]          =	self.prepare_config_and_inputs()
		UpperCamelCase     :List[Any]          =	{"""pixel_values""": pixel_values, """pixel_mask""": pixel_mask}
		return config, inputs_dict





	def 						_A (		self				:					Dict ,  __lowerCamelCase				:					int ,  __lowerCamelCase				:					Optional[int]	):
		UpperCamelCase     :Optional[Any]          =	output.encoder_hidden_states
		UpperCamelCase     :Optional[Any]          =	output.pixel_decoder_hidden_states
		UpperCamelCase     :Dict          =	output.transformer_decoder_hidden_states

		self.parent.assertTrue(len(__lowerCamelCase	) ,  len(config.backbone_config.depths	)	)
		self.parent.assertTrue(len(__lowerCamelCase	) ,  len(config.backbone_config.depths	)	)
		self.parent.assertTrue(len(__lowerCamelCase	) ,  config.decoder_layers	)





	def 						_A (		self				:					List[str] ,  __lowerCamelCase				:					Dict ,  __lowerCamelCase				:					Union[str, Any] ,  __lowerCamelCase				:					int ,  __lowerCamelCase				:					Optional[Any]=False	):
		with torch.no_grad():
			UpperCamelCase     :Optional[Any]          =	MaskaFormerModel(config=__lowerCamelCase	)
			model.to(__lowerCamelCase	)
			model.eval()

			UpperCamelCase     :List[str]          =	model(pixel_values=__lowerCamelCase ,  pixel_mask=__lowerCamelCase	)
			UpperCamelCase     :Tuple          =	model(__lowerCamelCase ,  output_hidden_states=__lowerCamelCase	)

		self.parent.assertEqual(
		    output.transformer_decoder_last_hidden_state.shape ,  (self.batch_size, self.num_queries, self.hidden_dim) ,  )
		# let's ensure the other two hidden state exists
		self.parent.assertTrue(output.pixel_decoder_last_hidden_state is not None	)
		self.parent.assertTrue(output.encoder_last_hidden_state is not None	)

		if output_hidden_states:
			self.check_output_hidden_state(__lowerCamelCase ,  __lowerCamelCase	)





	def 						_A (		self				:					Dict ,  __lowerCamelCase				:					Union[str, Any] ,  __lowerCamelCase				:					Any ,  __lowerCamelCase				:					List[Any] ,  __lowerCamelCase				:					Optional[int] ,  __lowerCamelCase				:					int	):
		UpperCamelCase     :Optional[int]          =	MaskaFormerForUniversalSegmentation(config=__lowerCamelCase	)
		model.to(__lowerCamelCase	)
		model.eval()

		def comm_check_on_output(__lowerCamelCase				:					Optional[Any]	):
			# let's still check that all the required stuff is there
			self.parent.assertTrue(result.transformer_decoder_last_hidden_state is not None	)
			self.parent.assertTrue(result.pixel_decoder_last_hidden_state is not None	)
			self.parent.assertTrue(result.encoder_last_hidden_state is not None	)
			# okay, now we need to check the logits shape
			# due to the encoder compression, masks have a //4 spatial size
			self.parent.assertEqual(
			    result.masks_queries_logits.shape ,  (self.batch_size, self.num_queries, self.min_size // 4, self.max_size // 4) ,  )
			# + 1 for null class
			self.parent.assertEqual(
			    result.class_queries_logits.shape ,  (self.batch_size, self.num_queries, self.num_labels + 1)	)

		with torch.no_grad():
			UpperCamelCase     :Optional[int]          =	model(pixel_values=__lowerCamelCase ,  pixel_mask=__lowerCamelCase	)
			UpperCamelCase     :Any          =	model(__lowerCamelCase	)

			comm_check_on_output(__lowerCamelCase	)

			UpperCamelCase     :Tuple          =	model(
			    pixel_values=__lowerCamelCase ,  pixel_mask=__lowerCamelCase ,  mask_labels=__lowerCamelCase ,  class_labels=__lowerCamelCase	)

		comm_check_on_output(__lowerCamelCase	)

		self.parent.assertTrue(result.loss is not None	)
		self.parent.assertEqual(result.loss.shape ,  torch.Size([1]	)	)

@require_torch
class     _SCREAMING_SNAKE_CASE       (			_a		,   _a		,   unittest.TestCase      ):
	snake_case__							:     Dict     	=  (MaskaFormerModel, MaskaFormerForUniversalSegmentation) if is_torch_available() else ()
	snake_case__							:     List[Any]     	=  {"""feature-extraction""": MaskaFormerModel} if is_torch_available() else {}

	snake_case__							:     List[str]     	=  False
	snake_case__							:     Any     	=  False
	snake_case__							:     Optional[int]     	=  False
	snake_case__							:     Tuple     	=  False





	def 						_A (		self				:					List[str]	):
		UpperCamelCase     :str          =	MaskaFormerModelTester(self	)
		UpperCamelCase     :Union[str, Any]          =	ConfigTester(self ,  config_class=__lowerCamelCase ,  has_text_modality=__lowerCamelCase	)





	def 						_A (		self				:					Optional[Any]	):
		self.config_tester.run_common_tests()





	def 						_A (		self				:					str	):
		UpperCamelCase     ,      UpperCamelCase     :List[str]          =	self.model_tester.prepare_config_and_inputs_for_common()
		self.model_tester.create_and_check_maskaformer_model(__lowerCamelCase ,  **__lowerCamelCase ,  output_hidden_states=__lowerCamelCase	)





	def 						_A (		self				:					Union[str, Any]	):
		UpperCamelCase     :List[Any]          =	self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_maskaformer_instance_segmentation_head_model(*__lowerCamelCase	)





	@unittest.skip(reason="""Mask2Former does not use inputs_embeds"""	)
	def 						_A (		self				:					List[Any]	):
		pass





	@unittest.skip(reason="""Mask2Former does not have a get_input_embeddings method"""	)
	def 						_A (		self				:					str	):
		pass





	@unittest.skip(reason="""Mask2Former is not a generative model"""	)
	def 						_A (		self				:					str	):
		pass





	@unittest.skip(reason="""Mask2Former does not use token embeddings"""	)
	def 						_A (		self				:					Optional[Any]	):
		pass





	@require_torch_multi_gpu
	@unittest.skip(
	    reason="""Mask2Former has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""	)
	def 						_A (		self				:					Optional[Any]	):
		pass





	@unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""	)
	def 						_A (		self				:					Dict	):
		pass





	def 						_A (		self				:					str	):
		UpperCamelCase     ,      UpperCamelCase     :Optional[Any]          =	self.model_tester.prepare_config_and_inputs_for_common()

		for model_class in self.all_model_classes:
			UpperCamelCase     :List[Any]          =	model_class(__lowerCamelCase	)
			UpperCamelCase     :str          =	inspect.signature(model.forward	)
			# signature.parameters is an OrderedDict => so arg_names order is deterministic
			UpperCamelCase     :Dict          =	[*signature.parameters.keys()]

			UpperCamelCase     :Optional[int]          =	["""pixel_values"""]
			self.assertListEqual(arg_names[:1] ,  __lowerCamelCase	)





	@slow
	def 						_A (		self				:					int	):
		for model_name in ["facebook/mask2former-swin-small-coco-instance"]:
			UpperCamelCase     :int          =	MaskaFormerModel.from_pretrained(__lowerCamelCase	)
			self.assertIsNotNone(__lowerCamelCase	)





	def 						_A (		self				:					List[str]	):
		UpperCamelCase     :Dict          =	(self.model_tester.min_size,) * 2
		UpperCamelCase     :Tuple          =	{
		    """pixel_values""": torch.randn((2, 3, *size) ,  device=__lowerCamelCase	),
		    """mask_labels""": torch.randn((2, 10, *size) ,  device=__lowerCamelCase	),
		    """class_labels""": torch.zeros(2 ,  10 ,  device=__lowerCamelCase	).long(),
		}
		UpperCamelCase     :str          =	self.model_tester.get_config()

		UpperCamelCase     :str          =	MaskaFormerForUniversalSegmentation(__lowerCamelCase	).to(__lowerCamelCase	)
		UpperCamelCase     :Optional[Any]          =	model(**__lowerCamelCase	)
		self.assertTrue(outputs.loss is not None	)





	def 						_A (		self				:					Dict	):
		UpperCamelCase     ,      UpperCamelCase     :str          =	self.model_tester.prepare_config_and_inputs_for_common()
		self.model_tester.create_and_check_maskaformer_model(__lowerCamelCase ,  **__lowerCamelCase ,  output_hidden_states=__lowerCamelCase	)





	def 						_A (		self				:					Dict	):
		UpperCamelCase     ,      UpperCamelCase     :Optional[Any]          =	self.model_tester.prepare_config_and_inputs_for_common()

		for model_class in self.all_model_classes:
			UpperCamelCase     :Optional[int]          =	model_class(__lowerCamelCase	).to(__lowerCamelCase	)
			UpperCamelCase     :Union[str, Any]          =	model(**__lowerCamelCase ,  output_attentions=__lowerCamelCase	)
			self.assertTrue(outputs.attentions is not None	)





	def 						_A (		self				:					List[str]	):
		if not self.model_tester.is_training:
			return

		UpperCamelCase     :Dict          =	self.all_model_classes[1]
		UpperCamelCase     ,      UpperCamelCase     ,      UpperCamelCase     ,      UpperCamelCase     ,      UpperCamelCase     :Optional[int]          =	self.model_tester.prepare_config_and_inputs()

		UpperCamelCase     :Optional[Any]          =	model_class(__lowerCamelCase	)
		model.to(__lowerCamelCase	)
		model.train()

		UpperCamelCase     :int          =	model(__lowerCamelCase ,  mask_labels=__lowerCamelCase ,  class_labels=__lowerCamelCase	).loss
		loss.backward()





	def 						_A (		self				:					List[str]	):
		UpperCamelCase     :Optional[int]          =	self.all_model_classes[1]
		UpperCamelCase     ,      UpperCamelCase     ,      UpperCamelCase     ,      UpperCamelCase     ,      UpperCamelCase     :Any          =	self.model_tester.prepare_config_and_inputs()
		UpperCamelCase     :List[Any]          =	True
		UpperCamelCase     :str          =	True

		UpperCamelCase     :int          =	model_class(__lowerCamelCase	).to(__lowerCamelCase	)
		model.train()

		UpperCamelCase     :Union[str, Any]          =	model(__lowerCamelCase ,  mask_labels=__lowerCamelCase ,  class_labels=__lowerCamelCase	)

		UpperCamelCase     :Optional[Any]          =	outputs.encoder_hidden_states[0]
		encoder_hidden_states.retain_grad()

		UpperCamelCase     :Any          =	outputs.pixel_decoder_hidden_states[0]
		pixel_decoder_hidden_states.retain_grad()

		UpperCamelCase     :Optional[int]          =	outputs.transformer_decoder_hidden_states[0]
		transformer_decoder_hidden_states.retain_grad()

		UpperCamelCase     :Any          =	outputs.attentions[0]
		attentions.retain_grad()

		outputs.loss.backward(retain_graph=__lowerCamelCase	)

		self.assertIsNotNone(encoder_hidden_states.grad	)
		self.assertIsNotNone(pixel_decoder_hidden_states.grad	)
		self.assertIsNotNone(transformer_decoder_hidden_states.grad	)
		self.assertIsNotNone(attentions.grad	)
UpperCAmelCase_ :						Optional[Any]      =      1E-4

def    SCREAMING_SNAKE_CASE_							(							)		->			Any:






	"""simple docstring"""



	UpperCamelCase     :Union[str, Any]          =	Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""					)
	return image

@require_vision
@slow
class     _SCREAMING_SNAKE_CASE       (			unittest.TestCase      ):





	@cached_property
	def 						_A (		self				:					Tuple	):
		return "facebook/mask2former-swin-small-coco-instance"





	@cached_property
	def 						_A (		self				:					Dict	):
		return MaskaFormerImageProcessor.from_pretrained(self.model_checkpoints	) if is_vision_available() else None





	def 						_A (		self				:					Tuple	):
		UpperCamelCase     :List[Any]          =	MaskaFormerModel.from_pretrained(self.model_checkpoints	).to(__lowerCamelCase	)
		UpperCamelCase     :Optional[int]          =	self.default_image_processor
		UpperCamelCase     :Optional[Any]          =	prepare_img()
		UpperCamelCase     :Optional[Any]          =	image_processor(__lowerCamelCase ,  return_tensors="""pt"""	).to(__lowerCamelCase	)
		UpperCamelCase     :str          =	inputs["""pixel_values"""].shape
		# check size is divisible by 32
		self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0	)
		# check size
		self.assertEqual(__lowerCamelCase ,  (1, 3, 384, 384)	)

		with torch.no_grad():
			UpperCamelCase     :Optional[int]          =	model(**__lowerCamelCase	)

		UpperCamelCase     :List[str]          =	torch.tensor(
		    [[-0.2790, -1.0717, -1.1668], [-0.5128, -0.3128, -0.4987], [-0.5832, 0.1971, -0.0197]]	).to(__lowerCamelCase	)
		self.assertTrue(
		    torch.allclose(
		        outputs.encoder_last_hidden_state[0, 0, :3, :3] ,  __lowerCamelCase ,  atol=__lowerCamelCase	)	)

		UpperCamelCase     :Tuple          =	torch.tensor(
		    [[0.8973, 1.1847, 1.1776], [1.1934, 1.5040, 1.5128], [1.1153, 1.4486, 1.4951]]	).to(__lowerCamelCase	)
		self.assertTrue(
		    torch.allclose(
		        outputs.pixel_decoder_last_hidden_state[0, 0, :3, :3] ,  __lowerCamelCase ,  atol=__lowerCamelCase	)	)

		UpperCamelCase     :Any          =	torch.tensor(
		    [[2.1152, 1.7000, -0.8603], [1.5808, 1.8004, -0.9353], [1.6043, 1.7495, -0.5999]]	).to(__lowerCamelCase	)
		self.assertTrue(
		    torch.allclose(
		        outputs.transformer_decoder_last_hidden_state[0, :3, :3] ,  __lowerCamelCase ,  atol=__lowerCamelCase	)	)





	def 						_A (		self				:					Any	):
		UpperCamelCase     :Dict          =	MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints	).to(__lowerCamelCase	).eval()
		UpperCamelCase     :str          =	self.default_image_processor
		UpperCamelCase     :Dict          =	prepare_img()
		UpperCamelCase     :str          =	image_processor(__lowerCamelCase ,  return_tensors="""pt"""	).to(__lowerCamelCase	)
		UpperCamelCase     :str          =	inputs["""pixel_values"""].shape
		# check size is divisible by 32
		self.assertTrue((inputs_shape[-1] % 32) == 0 and (inputs_shape[-2] % 32) == 0	)
		# check size
		self.assertEqual(__lowerCamelCase ,  (1, 3, 384, 384)	)

		with torch.no_grad():
			UpperCamelCase     :List[Any]          =	model(**__lowerCamelCase	)
		# masks_queries_logits
		UpperCamelCase     :int          =	outputs.masks_queries_logits
		self.assertEqual(
		    masks_queries_logits.shape ,  (1, model.config.num_queries, inputs_shape[-2] // 4, inputs_shape[-1] // 4)	)
		UpperCamelCase     :Any          =	[
		    [-8.7839, -9.0056, -8.8121],
		    [-7.4104, -7.0313, -6.5401],
		    [-6.6105, -6.3427, -6.4675],
		]
		UpperCamelCase     :Optional[int]          =	torch.tensor(__lowerCamelCase	).to(__lowerCamelCase	)
		self.assertTrue(torch.allclose(masks_queries_logits[0, 0, :3, :3] ,  __lowerCamelCase ,  atol=__lowerCamelCase	)	)
		# class_queries_logits
		UpperCamelCase     :List[Any]          =	outputs.class_queries_logits
		self.assertEqual(class_queries_logits.shape ,  (1, model.config.num_queries, model.config.num_labels + 1)	)
		UpperCamelCase     :Union[str, Any]          =	torch.tensor(
		    [
		        [1.8324, -8.0835, -4.1922],
		        [0.8450, -9.0050, -3.6053],
		        [0.3045, -7.7293, -3.0275],
		    ]	).to(__lowerCamelCase	)
		self.assertTrue(torch.allclose(outputs.class_queries_logits[0, :3, :3] ,  __lowerCamelCase ,  atol=__lowerCamelCase	)	)





	def 						_A (		self				:					Tuple	):
		UpperCamelCase     :List[Any]          =	MaskaFormerForUniversalSegmentation.from_pretrained(self.model_checkpoints	).to(__lowerCamelCase	).eval()
		UpperCamelCase     :int          =	self.default_image_processor

		UpperCamelCase     :List[str]          =	image_processor(
		    [np.zeros((3, 800, 1_333)	), np.zeros((3, 800, 1_333)	)] ,  segmentation_maps=[np.zeros((384, 384)	).astype(np.floataa	), np.zeros((384, 384)	).astype(np.floataa	)] ,  return_tensors="""pt""" ,  )

		UpperCamelCase     :Optional[Any]          =	inputs["""pixel_values"""].to(__lowerCamelCase	)
		UpperCamelCase     :Optional[Any]          =	[el.to(__lowerCamelCase	) for el in inputs["""mask_labels"""]]
		UpperCamelCase     :Any          =	[el.to(__lowerCamelCase	) for el in inputs["""class_labels"""]]

		with torch.no_grad():
			UpperCamelCase     :List[str]          =	model(**__lowerCamelCase	)

		self.assertTrue(outputs.loss is not None	)








import gc
import random
import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import (
    AutoencoderKL,
    DiffusionPipeline,
    EulerDiscreteScheduler,
    StableDiffusionXLImgaImgPipeline,
    UNetaDConditionModel,
)
from diffusers.utils import floats_tensor, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    IMAGE_TO_IMAGE_IMAGE_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
)
from ..test_pipelines_common import PipelineLatentTesterMixin, PipelineTesterMixin


enable_full_determinism()

class     _SCREAMING_SNAKE_CASE       (			_a		,   _a		,   unittest.TestCase      ):
	snake_case__							:     Any     	=  StableDiffusionXLImgaImgPipeline
	snake_case__							:     Tuple     	=  TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"""height""", """width"""}
	snake_case__							:     Tuple     	=  PipelineTesterMixin.required_optional_params - {"""latents"""}
	snake_case__							:     Any     	=  TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
	snake_case__							:     List[str]     	=  IMAGE_TO_IMAGE_IMAGE_PARAMS
	snake_case__							:     Tuple     	=  IMAGE_TO_IMAGE_IMAGE_PARAMS





	def 						_A (		self				:					int	):
		torch.manual_seed(0	)
		UpperCamelCase     :Any          =	UNetaDConditionModel(
		    block_out_channels=(32, 64) ,  layers_per_block=2 ,  sample_size=32 ,  in_channels=4 ,  out_channels=4 ,  down_block_types=("""DownBlock2D""", """CrossAttnDownBlock2D""") ,  up_block_types=("""CrossAttnUpBlock2D""", """UpBlock2D""") ,  attention_head_dim=(2, 4) ,  use_linear_projection=__lowerCamelCase ,  addition_embed_type="""text_time""" ,  addition_time_embed_dim=8 ,  transformer_layers_per_block=(1, 2) ,  projection_class_embeddings_input_dim=80 ,  cross_attention_dim=64 ,  )
		UpperCamelCase     :Tuple          =	EulerDiscreteScheduler(
		    beta_start=0.00085 ,  beta_end=0.012 ,  steps_offset=1 ,  beta_schedule="""scaled_linear""" ,  timestep_spacing="""leading""" ,  )
		torch.manual_seed(0	)
		UpperCamelCase     :Union[str, Any]          =	AutoencoderKL(
		    block_out_channels=[32, 64] ,  in_channels=3 ,  out_channels=3 ,  down_block_types=["""DownEncoderBlock2D""", """DownEncoderBlock2D"""] ,  up_block_types=["""UpDecoderBlock2D""", """UpDecoderBlock2D"""] ,  latent_channels=4 ,  sample_size=128 ,  )
		torch.manual_seed(0	)
		UpperCamelCase     :Optional[int]          =	CLIPTextConfig(
		    bos_token_id=0 ,  eos_token_id=2 ,  hidden_size=32 ,  intermediate_size=37 ,  layer_norm_eps=1E-05 ,  num_attention_heads=4 ,  num_hidden_layers=5 ,  pad_token_id=1 ,  vocab_size=1_000 ,  hidden_act="""gelu""" ,  projection_dim=32 ,  )
		UpperCamelCase     :Any          =	CLIPTextModel(__lowerCamelCase	)
		UpperCamelCase     :List[Any]          =	CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ,  local_files_only=__lowerCamelCase	)

		UpperCamelCase     :List[Any]          =	CLIPTextModelWithProjection(__lowerCamelCase	)
		UpperCamelCase     :int          =	CLIPTokenizer.from_pretrained("""hf-internal-testing/tiny-random-clip""" ,  local_files_only=__lowerCamelCase	)

		UpperCamelCase     :Union[str, Any]          =	{
		    """unet""": unet,
		    """scheduler""": scheduler,
		    """vae""": vae,
		    """text_encoder""": text_encoder,
		    """tokenizer""": tokenizer,
		    """text_encoder_2""": text_encoder_a,
		    """tokenizer_2""": tokenizer_a,
		    # "safety_checker": None,
		    # "feature_extractor": None,
		}
		return components





	def 						_A (		self				:					Tuple ,  __lowerCamelCase				:					Any ,  __lowerCamelCase				:					Optional[Any]=0	):
		UpperCamelCase     :Tuple          =	floats_tensor((1, 3, 32, 32) ,  rng=random.Random(__lowerCamelCase	)	).to(__lowerCamelCase	)
		UpperCamelCase     :List[str]          =	image / 2 + 0.5
		if str(__lowerCamelCase	).startswith("""mps"""	):
			UpperCamelCase     :Any          =	torch.manual_seed(__lowerCamelCase	)
		else:
			UpperCamelCase     :List[Any]          =	torch.Generator(device=__lowerCamelCase	).manual_seed(__lowerCamelCase	)
		UpperCamelCase     :str          =	{
		    """prompt""": """A painting of a squirrel eating a burger""",
		    """image""": image,
		    """generator""": generator,
		    """num_inference_steps""": 2,
		    """guidance_scale""": 5.0,
		    """output_type""": """numpy""",
		    """strength""": 0.75,
		}
		return inputs





	def 						_A (		self				:					str	):
		UpperCamelCase     :List[str]          =	"""cpu"""  # ensure determinism for the device-dependent torch.Generator
		UpperCamelCase     :Optional[Any]          =	self.get_dummy_components()
		UpperCamelCase     :List[Any]          =	StableDiffusionXLImgaImgPipeline(**__lowerCamelCase	)
		UpperCamelCase     :Any          =	sd_pipe.to(__lowerCamelCase	)
		sd_pipe.set_progress_bar_config(disable=__lowerCamelCase	)

		UpperCamelCase     :Optional[Any]          =	self.get_dummy_inputs(__lowerCamelCase	)
		UpperCamelCase     :Union[str, Any]          =	sd_pipe(**__lowerCamelCase	).images
		UpperCamelCase     :Union[str, Any]          =	image[0, -3:, -3:, -1]

		assert image.shape == (1, 32, 32, 3)

		UpperCamelCase     :List[Any]          =	np.array([0.4656, 0.4840, 0.4439, 0.6698, 0.5574, 0.4524, 0.5799, 0.5943, 0.5165]	)

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





	def 						_A (		self				:					Dict	):
		super().test_attention_slicing_forward_pass(expected_max_diff=3E-3	)





	def 						_A (		self				:					Optional[Any]	):
		super().test_inference_batch_single_identical(expected_max_diff=3E-3	)





	def 						_A (		self				:					Union[str, Any]	):
		pass





	def 						_A (		self				:					Optional[int]	):
		UpperCamelCase     :Union[str, Any]          =	self.get_dummy_components()
		UpperCamelCase     :Dict          =	StableDiffusionXLImgaImgPipeline(**__lowerCamelCase	)
		UpperCamelCase     :List[Any]          =	sd_pipe.to(__lowerCamelCase	)
		UpperCamelCase     :List[str]          =	sd_pipe.to(__lowerCamelCase	)
		sd_pipe.set_progress_bar_config(disable=__lowerCamelCase	)

		# forward without prompt embeds
		UpperCamelCase     :List[Any]          =	self.get_dummy_inputs(__lowerCamelCase	)
		UpperCamelCase     :int          =	3 * ["""this is a negative prompt"""]
		UpperCamelCase     :Union[str, Any]          =	negative_prompt
		UpperCamelCase     :Union[str, Any]          =	3 * [inputs["""prompt"""]]

		UpperCamelCase     :Dict          =	sd_pipe(**__lowerCamelCase	)
		UpperCamelCase     :Union[str, Any]          =	output.images[0, -3:, -3:, -1]

		# forward with prompt embeds
		UpperCamelCase     :Union[str, Any]          =	self.get_dummy_inputs(__lowerCamelCase	)
		UpperCamelCase     :Optional[int]          =	3 * ["""this is a negative prompt"""]
		UpperCamelCase     :Union[str, Any]          =	3 * [inputs.pop("""prompt"""	)]

		(
		    (
		    UpperCamelCase
		)     ,      (
		    UpperCamelCase
		)     ,      (
		    UpperCamelCase
		)     ,      (
		    UpperCamelCase
		)     ,      
		)     :Union[str, Any]          =	sd_pipe.encode_prompt(__lowerCamelCase ,  negative_prompt=__lowerCamelCase	)

		UpperCamelCase     :Dict          =	sd_pipe(
		    **__lowerCamelCase ,  prompt_embeds=__lowerCamelCase ,  negative_prompt_embeds=__lowerCamelCase ,  pooled_prompt_embeds=__lowerCamelCase ,  negative_pooled_prompt_embeds=__lowerCamelCase ,  )
		UpperCamelCase     :Union[str, Any]          =	output.images[0, -3:, -3:, -1]

		# make sure that it's equal
		assert np.abs(image_slice_a.flatten() - image_slice_a.flatten()	).max() < 1E-4

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





	def 						_A (		self				:					Tuple	):
		super().tearDown()
		gc.collect()
		torch.cuda.empty_cache()





	def 						_A (		self				:					List[Any] ,  __lowerCamelCase				:					Any ,  __lowerCamelCase				:					Dict="cpu" ,  __lowerCamelCase				:					List[Any]=torch.floataa ,  __lowerCamelCase				:					Tuple=0	):
		UpperCamelCase     :Optional[int]          =	torch.Generator(device=__lowerCamelCase	).manual_seed(__lowerCamelCase	)
		UpperCamelCase     :Optional[Any]          =	np.random.RandomState(__lowerCamelCase	).standard_normal((1, 4, 64, 64)	)
		UpperCamelCase     :Dict          =	torch.from_numpy(__lowerCamelCase	).to(device=__lowerCamelCase ,  dtype=__lowerCamelCase	)
		UpperCamelCase     :str          =	{
		    """prompt""": """a photograph of an astronaut riding a horse""",
		    """latents""": latents,
		    """generator""": generator,
		    """num_inference_steps""": 3,
		    """guidance_scale""": 7.5,
		    """output_type""": """numpy""",
		}
		return inputs





	def 						_A (		self				:					Optional[Any]	):
		UpperCamelCase     :Any          =	DiffusionPipeline.from_pretrained("""stabilityai/stable-diffusion-2-base"""	)
		pipe.to(__lowerCamelCase	)
		pipe.set_progress_bar_config(disable=__lowerCamelCase	)

		UpperCamelCase     :Optional[Any]          =	self.get_inputs(__lowerCamelCase	)
		UpperCamelCase     :Optional[int]          =	pipe(**__lowerCamelCase	).images
		UpperCamelCase     :Dict          =	image[0, -3:, -3:, -1].flatten()

		assert image.shape == (1, 512, 512, 3)
		UpperCamelCase     :Union[str, Any]          =	np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506]	)
		assert np.abs(image_slice - expected_slice	).max() < 7E-3
