




import unittest

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

from diffusers import DDIMScheduler, LDMPipeline, UNetaDModel, VQModel
from diffusers.utils.testing_utils import enable_full_determinism, require_torch, slow, torch_device


enable_full_determinism()






class 		_lowerCAmelCase       (							unittest.TestCase	):
			"""simple docstring"""
			@property
			def 					UpperCAmelCase     (					self       )		->							List[str]:





				"""simple docstring"""







				torch.manual_seed(0       )
				snake_case__						:     Dict		=UNetaDModel(
				    block_out_channels=(32, 64)     ,		layers_per_block=2     ,		sample_size=32     ,		in_channels=3     ,		out_channels=3     ,		down_block_types=('''DownBlock2D''', '''AttnDownBlock2D''')     ,		up_block_types=('''AttnUpBlock2D''', '''UpBlock2D''')     ,		)
				return model
			@property
			def 					UpperCAmelCase     (					self       )		->							Optional[Any]:





				"""simple docstring"""







				torch.manual_seed(0       )
				snake_case__						:     Optional[int]		=VQModel(
				    block_out_channels=[32, 64]     ,		in_channels=3     ,		out_channels=3     ,		down_block_types=['''DownEncoderBlock2D''', '''DownEncoderBlock2D''']     ,		up_block_types=['''UpDecoderBlock2D''', '''UpDecoderBlock2D''']     ,		latent_channels=3     ,		)
				return model
			@property
			def 					UpperCAmelCase     (					self       )		->							List[str]:





				"""simple docstring"""







				torch.manual_seed(0       )
				snake_case__						:     List[Any]		=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=1000     ,		)
				return CLIPTextModel(snake_case_       )


			def 					UpperCAmelCase     (					self       )		->							str:





				"""simple docstring"""







				snake_case__						:     Any		=self.dummy_uncond_unet
				snake_case__						:     int		=DDIMScheduler()
				snake_case__						:     List[Any]		=self.dummy_vq_model

				snake_case__						:     List[Any]		=LDMPipeline(unet=snake_case_     ,		vqvae=snake_case_     ,		scheduler=snake_case_       )
				ldm.to(snake_case_       )
				ldm.set_progress_bar_config(disable=snake_case_       )

				snake_case__						:     Union[str, Any]		=torch.manual_seed(0       )
				snake_case__						:     Dict		=ldm(generator=snake_case_     ,		num_inference_steps=2     ,		output_type='''numpy'''       ).images

				snake_case__						:     List[str]		=torch.manual_seed(0       )
				snake_case__						:     Dict		=ldm(generator=snake_case_     ,		num_inference_steps=2     ,		output_type='''numpy'''     ,		return_dict=snake_case_       )[0]

				snake_case__						:     int		=image[0, -3:, -3:, -1]
				snake_case__						:     str		=image_from_tuple[0, -3:, -3:, -1]

				assert image.shape == (1, 64, 64, 3)
				snake_case__						:     List[Any]		=np.array([0.8512, 0.818, 0.6411, 0.6808, 0.4465, 0.5618, 0.46, 0.6231, 0.5172]       )
				snake_case__						:     str		=1e-2 if torch_device != '''mps''' else 3e-2

				assert np.abs(image_slice.flatten() - expected_slice       ).max() < tolerance
				assert np.abs(image_from_tuple_slice.flatten() - expected_slice       ).max() < tolerance






@slow
@require_torch
class 		_lowerCAmelCase       (							unittest.TestCase	):
			"""simple docstring"""
			def 					UpperCAmelCase     (					self       )		->							Tuple:





				"""simple docstring"""







				snake_case__						:     str		=LDMPipeline.from_pretrained('''CompVis/ldm-celebahq-256'''       )
				ldm.to(snake_case_       )
				ldm.set_progress_bar_config(disable=snake_case_       )

				snake_case__						:     List[Any]		=torch.manual_seed(0       )
				snake_case__						:     Any		=ldm(generator=snake_case_     ,		num_inference_steps=5     ,		output_type='''numpy'''       ).images

				snake_case__						:     Optional[Any]		=image[0, -3:, -3:, -1]

				assert image.shape == (1, 256, 256, 3)
				snake_case__						:     List[str]		=np.array([0.4399, 0.4_4975, 0.4_6825, 0.474, 0.4359, 0.4581, 0.4_5095, 0.4341, 0.4447]       )
				snake_case__						:     int		=1e-2 if torch_device != '''mps''' else 3e-2

				assert np.abs(image_slice.flatten() - expected_slice       ).max() < tolerance









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     __a			:



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



	def 		UpperCamelCase				(    self				:     List[Any])->				Optional[int]:
						__lowerCAmelCase						 =ids_tensor([self.batch_size, self.seq_length]					,						self.vocab_size)

						__lowerCAmelCase						 =None
						if self.use_input_mask:
											__lowerCAmelCase						 =random_attention_mask([self.batch_size, self.seq_length])

						if input_mask is not None:
											__lowerCAmelCase						 =input_mask.numpy()
											__lowerCAmelCase ,						__lowerCAmelCase						 =input_mask.shape
											__lowerCAmelCase						 =np.random.randint(1					,						seq_length - 1					,						size=(batch_size,))
											for batch_idx, start_index in enumerate(snake_case_):
																__lowerCAmelCase						 =1
																__lowerCAmelCase						 =0

						__lowerCAmelCase						 =self.get_config()

						return config, input_ids, tf.convert_to_tensor(snake_case_)



	def 		UpperCamelCase				(    self				:     List[str])->				str:
						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 		UpperCamelCase				(    self				:     Union[str, Any]					,						snake_case_				:     Tuple					,						snake_case_				:     List[Any]					,						snake_case_				:     List[Any])->				List[str]:
						__lowerCAmelCase						 =TFBlipTextModel(config=snake_case_)
						__lowerCAmelCase						 =model(snake_case_					,						attention_mask=snake_case_					,						training=snake_case_)
						__lowerCAmelCase						 =model(snake_case_					,						training=snake_case_)
						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 		UpperCamelCase				(    self				:     Dict)->				Tuple:
						__lowerCAmelCase						 =self.prepare_config_and_inputs()
						__lowerCAmelCase ,						__lowerCAmelCase ,						__lowerCAmelCase						 =config_and_inputs
						__lowerCAmelCase						 ={"""input_ids""": input_ids, """attention_mask""": input_mask}
						return config, inputs_dict






@require_tf
class     __a			(  SCREAMING_SNAKE_CASE						,     unittest.TestCase					):
	SCREAMING_SNAKE_CASE  	=							(TFBlipTextModel,) if is_tf_available() else ()
	SCREAMING_SNAKE_CASE  	=							False
	SCREAMING_SNAKE_CASE  	=							False
	SCREAMING_SNAKE_CASE  	=							False



	def 		UpperCamelCase				(    self				:     Optional[Any])->				Any:
						__lowerCAmelCase						 =BlipTextModelTester(self)
						__lowerCAmelCase						 =ConfigTester(self					,						config_class=snake_case_					,						hidden_size=37)



	def 		UpperCamelCase				(    self				:     List[Any])->				List[str]:
						self.config_tester.run_common_tests()



	def 		UpperCamelCase				(    self				:     List[str])->				Dict:
						__lowerCAmelCase						 =self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*snake_case_)



	def 		UpperCamelCase				(    self				:     Optional[Any])->				str:
						pass



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



	@unittest.skip(reason="""Blip does not use inputs_embeds""")
	def 		UpperCamelCase				(    self				:     Optional[Any])->				int:
						pass



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



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



	@slow
	def 		UpperCamelCase				(    self				:     int)->				str:
						for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											__lowerCAmelCase						 =TFBlipTextModel.from_pretrained(snake_case_)
											self.assertIsNotNone(snake_case_)



	def 		UpperCamelCase				(    self				:     str					,						snake_case_				:     List[str]=True)->				int:
						super().test_pt_tf_model_equivalence(allow_missing_keys=snake_case_)




