



'''simple docstring'''




import gc
import unittest

import numpy as np
import torch

from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DPMSolverMultistepScheduler, TransformeraDModel
from diffusers.utils import is_xformers_available, load_numpy, slow, torch_device
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_gpu

from ..pipeline_params import (
    CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS,
    CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS,
)
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()

class 			UpperCamelCase_ (							__magic_name__      ,     unittest.TestCase			):
	lowercase          = DiTPipeline
	lowercase          = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS
	lowercase          = PipelineTesterMixin.required_optional_params - {
	    'latents',
	    'num_images_per_prompt',
	    'callback',
	    'callback_steps',
	}
	lowercase          = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS
	lowercase          = False





	def  _lowercase(  self    )			->			Optional[int]:
								torch.manual_seed(0    )
								UpperCAmelCase     :		Dict							     =		TransformeraDModel(
								    sample_size=16		,		num_layers=2		,		patch_size=4		,		attention_head_dim=8		,		num_attention_heads=2		,		in_channels=4		,		out_channels=8		,		attention_bias=A		,		activation_fn="""gelu-approximate"""		,		num_embeds_ada_norm=1000		,		norm_type="""ada_norm_zero"""		,		norm_elementwise_affine=A		,		)
								UpperCAmelCase     :		Optional[int]							     =		AutoencoderKL()
								UpperCAmelCase     :		int							     =		DDIMScheduler()
								UpperCAmelCase     :		str							     =		{"""transformer""": transformer.eval(), """vae""": vae.eval(), """scheduler""": scheduler}
								return components





	def  _lowercase(  self		,		A		,		A=0    )			->			str:
								if str(A    ).startswith("""mps"""    ):
															UpperCAmelCase     :		Optional[Any]							     =		torch.manual_seed(A    )
								else:
															UpperCAmelCase     :		Tuple							     =		torch.Generator(device=A    ).manual_seed(A    )
								UpperCAmelCase     :		Union[str, Any]							     =		{
								    """class_labels""": [1],
								    """generator""": generator,
								    """num_inference_steps""": 2,
								    """output_type""": """numpy""",
								}
								return inputs





	def  _lowercase(  self    )			->			Dict:
								UpperCAmelCase     :		Any							     =		"""cpu"""

								UpperCAmelCase     :		List[Any]							     =		self.get_dummy_components()
								UpperCAmelCase     :		List[str]							     =		self.pipeline_class(**A    )
								pipe.to(A    )
								pipe.set_progress_bar_config(disable=A    )

								UpperCAmelCase     :		int							     =		self.get_dummy_inputs(A    )
								UpperCAmelCase     :		Any							     =		pipe(**A    ).images
								UpperCAmelCase     :		Any							     =		image[0, -3:, -3:, -1]

								self.assertEqual(image.shape		,		(1, 16, 16, 3)    )
								UpperCAmelCase     :		int							     =		np.array([0.2_9_4_6, 0.6_6_0_1, 0.4_3_2_9, 0.3_2_9_6, 0.4_1_4_4, 0.5_3_1_9, 0.7_2_7_3, 0.5_0_1_3, 0.4_4_5_7]    )
								UpperCAmelCase     :		int							     =		np.abs(image_slice.flatten() - expected_slice    ).max()
								self.assertLessEqual(A		,		1e-3    )





	def  _lowercase(  self    )			->			List[str]:
								self._test_inference_batch_single_identical(relax_max_difference=A		,		expected_max_diff=1e-3    )






	@unittest.skipIf(
	    torch_device != """cuda""" or not is_xformers_available()		,		reason="""XFormers attention is only available with CUDA and `xformers` installed"""		,		)
	def  _lowercase(  self    )			->			Union[str, Any]:
								self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3    )




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





	def  _lowercase(  self    )			->			Union[str, Any]:
								super().tearDown()
								gc.collect()
								torch.cuda.empty_cache()





	def  _lowercase(  self    )			->			List[Any]:
								UpperCAmelCase     :		Any							     =		torch.manual_seed(0    )

								UpperCAmelCase     :		List[str]							     =		DiTPipeline.from_pretrained("""facebook/DiT-XL-2-256"""    )
								pipe.to("""cuda"""    )

								UpperCAmelCase     :		Tuple							     =		["""vase""", """umbrella""", """white shark""", """white wolf"""]
								UpperCAmelCase     :		str							     =		pipe.get_label_ids(A    )

								UpperCAmelCase     :		Optional[int]							     =		pipe(A		,		generator=A		,		num_inference_steps=40		,		output_type="""np"""    ).images

								for word, image in zip(A		,		A    ):
															UpperCAmelCase     :		Dict							     =		load_numpy(
															    f'''https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy'''    )
															assert np.abs((expected_image - image).max()    ) < 1e-2






	def  _lowercase(  self    )			->			Tuple:
								UpperCAmelCase     :		Optional[Any]							     =		DiTPipeline.from_pretrained("""facebook/DiT-XL-2-512"""    )
								UpperCAmelCase     :		Optional[Any]							     =		DPMSolverMultistepScheduler.from_config(pipe.scheduler.config    )
								pipe.to("""cuda"""    )

								UpperCAmelCase     :		Dict							     =		["""vase""", """umbrella"""]
								UpperCAmelCase     :		Dict							     =		pipe.get_label_ids(A    )

								UpperCAmelCase     :		List[Any]							     =		torch.manual_seed(0    )
								UpperCAmelCase     :		List[str]							     =		pipe(A		,		generator=A		,		num_inference_steps=25		,		output_type="""np"""    ).images

								for word, image in zip(A		,		A    ):
															UpperCAmelCase     :		List[Any]							     =		load_numpy(
															    """https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"""
															    f'''/dit/{word}_512.npy'''    )

															assert np.abs((expected_image - image).max()    ) < 1e-1






'''simple docstring'''




from __future__ import annotations

import unittest

import numpy as np

from transformers import BlipTextConfig
from transformers.testing_utils import require_tf, slow
from transformers.utils import is_tf_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask


if is_tf_available():
							import tensorflow as tf

							from transformers import TFBlipTextModel
							from transformers.models.blip.modeling_tf_blip import TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST

class 			UpperCamelCase_ :





	def __init__(  self		,		A		,		A=12		,		A=7		,		A=True		,		A=True		,		A=True		,		A=99		,		A=32		,		A=32		,		A=2		,		A=4		,		A=37		,		A=0.1		,		A=0.1		,		A=512		,		A=0.0_2		,		A=0		,		A=None		,		)			->			Any:
								UpperCAmelCase     :		Optional[Any]							     =		parent
								UpperCAmelCase     :		str							     =		batch_size
								UpperCAmelCase     :		Union[str, Any]							     =		seq_length
								UpperCAmelCase     :		Optional[Any]							     =		is_training
								UpperCAmelCase     :		int							     =		use_input_mask
								UpperCAmelCase     :		List[Any]							     =		use_labels
								UpperCAmelCase     :		Dict							     =		vocab_size
								UpperCAmelCase     :		str							     =		hidden_size
								UpperCAmelCase     :		List[Any]							     =		projection_dim
								UpperCAmelCase     :		Tuple							     =		num_hidden_layers
								UpperCAmelCase     :		Dict							     =		num_attention_heads
								UpperCAmelCase     :		Optional[Any]							     =		intermediate_size
								UpperCAmelCase     :		Any							     =		dropout
								UpperCAmelCase     :		List[Any]							     =		attention_dropout
								UpperCAmelCase     :		Optional[Any]							     =		max_position_embeddings
								UpperCAmelCase     :		Tuple							     =		initializer_range
								UpperCAmelCase     :		Optional[Any]							     =		scope
								UpperCAmelCase     :		Union[str, Any]							     =		bos_token_id





	def  _lowercase(  self    )			->			Tuple:
								UpperCAmelCase     :		Optional[int]							     =		ids_tensor([self.batch_size, self.seq_length]		,		self.vocab_size    )

								UpperCAmelCase     :		Union[str, Any]							     =		None
								if self.use_input_mask:
															UpperCAmelCase     :		str							     =		random_attention_mask([self.batch_size, self.seq_length]    )

								if input_mask is not None:
															UpperCAmelCase     :		Tuple							     =		input_mask.numpy()
															UpperCAmelCase     ,     UpperCAmelCase     :		int							     =		input_mask.shape
															UpperCAmelCase     :		Optional[int]							     =		np.random.randint(1		,		seq_length - 1		,		size=(batch_size,)    )
															for batch_idx, start_index in enumerate(A    ):
																						UpperCAmelCase     :		Tuple							     =		1
																						UpperCAmelCase     :		Optional[Any]							     =		0

								UpperCAmelCase     :		int							     =		self.get_config()

								return config, input_ids, tf.convert_to_tensor(A    )





	def  _lowercase(  self    )			->			int:
								return BlipTextConfig(
								    vocab_size=self.vocab_size		,		hidden_size=self.hidden_size		,		projection_dim=self.projection_dim		,		num_hidden_layers=self.num_hidden_layers		,		num_attention_heads=self.num_attention_heads		,		intermediate_size=self.intermediate_size		,		dropout=self.dropout		,		attention_dropout=self.attention_dropout		,		max_position_embeddings=self.max_position_embeddings		,		initializer_range=self.initializer_range		,		bos_token_id=self.bos_token_id		,		)





	def  _lowercase(  self		,		A		,		A		,		A    )			->			Union[str, Any]:
								UpperCAmelCase     :		int							     =		TFBlipTextModel(config=A    )
								UpperCAmelCase     :		Union[str, Any]							     =		model(A		,		attention_mask=A		,		training=A    )
								UpperCAmelCase     :		int							     =		model(A		,		training=A    )
								self.parent.assertEqual(result.last_hidden_state.shape		,		(self.batch_size, self.seq_length, self.hidden_size)    )
								self.parent.assertEqual(result.pooler_output.shape		,		(self.batch_size, self.hidden_size)    )






	def  _lowercase(  self    )			->			Optional[int]:
								UpperCAmelCase     :		Dict							     =		self.prepare_config_and_inputs()
								UpperCAmelCase     ,     UpperCAmelCase     ,     UpperCAmelCase     :		Any							     =		config_and_inputs
								UpperCAmelCase     :		Optional[Any]							     =		{"""input_ids""": input_ids, """attention_mask""": input_mask}
								return config, inputs_dict




@require_tf
class 			UpperCamelCase_ (							__magic_name__      ,     unittest.TestCase			):
	lowercase          = (TFBlipTextModel,) if is_tf_available() else ()
	lowercase          = False
	lowercase          = False
	lowercase          = False





	def  _lowercase(  self    )			->			int:
								UpperCAmelCase     :		Union[str, Any]							     =		BlipTextModelTester(self    )
								UpperCAmelCase     :		List[str]							     =		ConfigTester(self		,		config_class=A		,		hidden_size=37    )





	def  _lowercase(  self    )			->			Tuple:
								self.config_tester.run_common_tests()





	def  _lowercase(  self    )			->			List[Any]:
								UpperCAmelCase     :		List[Any]							     =		self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*A    )





	def  _lowercase(  self    )			->			List[str]:
								pass





	def  _lowercase(  self    )			->			Optional[int]:
								pass





	@unittest.skip(reason="""Blip does not use inputs_embeds"""    )
	def  _lowercase(  self    )			->			Union[str, Any]:
								pass





	@unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING"""    )
	def  _lowercase(  self    )			->			Optional[int]:
								pass





	@unittest.skip(reason="""BlipTextModel has no base class and is not available in MODEL_MAPPING"""    )
	def  _lowercase(  self    )			->			Dict:
								pass





	@slow
	def  _lowercase(  self    )			->			Dict:
								for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															UpperCAmelCase     :		Any							     =		TFBlipTextModel.from_pretrained(A    )
															self.assertIsNotNone(A    )






	def  _lowercase(  self		,		A=True    )			->			str:
								super().test_pt_tf_model_equivalence(allow_missing_keys=A    )

