


import gc
import unittest

from diffusers import FlaxDPMSolverMultistepScheduler, FlaxStableDiffusionPipeline
from diffusers.utils import is_flax_available, slow
from diffusers.utils.testing_utils import require_flax


if is_flax_available():
			import jax
			import jax.numpy as jnp
			from flax.jax_utils import replicate
			from flax.training.common_utils import shard


@slow
@require_flax
class 			_a				(     unittest.TestCase     ):

							def  lowerCamelCase_					(				self:      Union[str, Any]				)     ->  Union[str, Any]:





									"""simple docstring"""







									super().tearDown()
									gc.collect()

							def  lowerCamelCase_					(				self:      Optional[Any]				)     ->  Optional[Any]:





									"""simple docstring"""







									lowercase__	,						lowercase__				= FlaxStableDiffusionPipeline.from_pretrained(
									    '''stabilityai/stable-diffusion-2'''       ,		revision='''bf16'''       ,		dtype=jnp.bfloataa       ,		)

									lowercase__				= '''A painting of a squirrel eating a burger'''
									lowercase__				= jax.device_count()
									lowercase__				= num_samples * [prompt]
									lowercase__				= sd_pipe.prepare_inputs(UpperCamelCase_				)

									lowercase__				= replicate(UpperCamelCase_				)
									lowercase__				= shard(UpperCamelCase_				)

									lowercase__				= jax.random.PRNGKey(0				)
									lowercase__				= jax.random.split(UpperCamelCase_       ,		jax.device_count()				)

									lowercase__				= sd_pipe(UpperCamelCase_       ,		UpperCamelCase_       ,		UpperCamelCase_       ,		num_inference_steps=25       ,		jit=UpperCamelCase_				)[0]
									assert images.shape == (jax.device_count(), 1, 768, 768, 3)

									lowercase__				= images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]				)
									lowercase__				= images[0, 253:256, 253:256, -1]

									lowercase__				= jnp.asarray(jax.device_get(image_slice.flatten()				)				)
									lowercase__				= jnp.array([0.4238, 0.4414, 0.4395, 0.4453, 0.4629, 0.4590, 0.4531, 0.45508, 0.4512]				)
									print(f'output_slice: {output_slice}'				)
									assert jnp.abs(output_slice - expected_slice				).max() < 1E-2


							def  lowerCamelCase_					(				self:      Optional[int]				)     ->  Optional[Any]:





									"""simple docstring"""







									lowercase__				= '''stabilityai/stable-diffusion-2'''
									lowercase__	,						lowercase__				= FlaxDPMSolverMultistepScheduler.from_pretrained(UpperCamelCase_       ,		subfolder='''scheduler'''				)
									lowercase__	,						lowercase__				= FlaxStableDiffusionPipeline.from_pretrained(
									    UpperCamelCase_       ,		scheduler=UpperCamelCase_       ,		revision='''bf16'''       ,		dtype=jnp.bfloataa       ,		)
									lowercase__				= scheduler_params

									lowercase__				= '''A painting of a squirrel eating a burger'''
									lowercase__				= jax.device_count()
									lowercase__				= num_samples * [prompt]
									lowercase__				= sd_pipe.prepare_inputs(UpperCamelCase_				)

									lowercase__				= replicate(UpperCamelCase_				)
									lowercase__				= shard(UpperCamelCase_				)

									lowercase__				= jax.random.PRNGKey(0				)
									lowercase__				= jax.random.split(UpperCamelCase_       ,		jax.device_count()				)

									lowercase__				= sd_pipe(UpperCamelCase_       ,		UpperCamelCase_       ,		UpperCamelCase_       ,		num_inference_steps=25       ,		jit=UpperCamelCase_				)[0]
									assert images.shape == (jax.device_count(), 1, 768, 768, 3)

									lowercase__				= images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:]				)
									lowercase__				= images[0, 253:256, 253:256, -1]

									lowercase__				= jnp.asarray(jax.device_get(image_slice.flatten()				)				)
									lowercase__				= jnp.array([0.4336, 0.42969, 0.4453, 0.4199, 0.4297, 0.4531, 0.4434, 0.4434, 0.4297]				)
									print(f'output_slice: {output_slice}'				)
									assert jnp.abs(output_slice - expected_slice				).max() < 1E-2







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   __lowerCAmelCase  :
					"""simple docstring"""






					def __init__(  self       :							Dict					,       _snake_case       :							Union[str, Any]					,       _snake_case       :							Optional[Any]=12					,       _snake_case       :							Any=7					,       _snake_case       :							List[str]=True					,       _snake_case       :							int=True					,       _snake_case       :							int=True					,       _snake_case       :							Tuple=99					,       _snake_case       :							List[Any]=32					,       _snake_case       :							Optional[int]=32					,       _snake_case       :							List[str]=2					,       _snake_case       :							List[str]=4					,       _snake_case       :							List[Any]=37					,       _snake_case       :							Union[str, Any]=0.1					,       _snake_case       :							Tuple=0.1					,       _snake_case       :							Dict=5_12					,       _snake_case       :							Union[str, Any]=0.02					,       _snake_case       :							Any=0					,       _snake_case       :							Optional[Any]=None					,       ):






								"""simple docstring"""


								A__	  =     parent
								A__	  =     batch_size
								A__	  =     seq_length
								A__	  =     is_training
								A__	  =     use_input_mask
								A__	  =     use_labels
								A__	  =     vocab_size
								A__	  =     hidden_size
								A__	  =     projection_dim
								A__	  =     num_hidden_layers
								A__	  =     num_attention_heads
								A__	  =     intermediate_size
								A__	  =     dropout
								A__	  =     attention_dropout
								A__	  =     max_position_embeddings
								A__	  =     initializer_range
								A__	  =     scope
								A__	  =     bos_token_id



					def      _a				(  self       :							Optional[Any]       ):






								"""simple docstring"""


								A__	  =     ids_tensor([self.batch_size, self.seq_length]					,       self.vocab_size       )

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

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

								A__	  =     self.get_config()

								return config, input_ids, tf.convert_to_tensor(_snake_case       )



					def      _a				(  self       :							Tuple       ):






								"""simple docstring"""


								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      _a				(  self       :							int					,       _snake_case       :							Union[str, Any]					,       _snake_case       :							Any					,       _snake_case       :							List[str]       ):






								"""simple docstring"""


								A__	  =     TFBlipTextModel(config=_snake_case       )
								A__	  =     model(_snake_case					,       attention_mask=_snake_case					,       training=_snake_case       )
								A__	  =     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      _a				(  self       :							str       ):






								"""simple docstring"""


								A__	  =     self.prepare_config_and_inputs()
								A__  ,			A__  ,			A__	  =     config_and_inputs
								A__	  =     {'input_ids': input_ids, 'attention_mask': input_mask}
								return config, inputs_dict







@require_tf
class   __lowerCAmelCase  (		UpperCAmelCase_				,  unittest.TestCase   ):
					"""simple docstring"""






					A__					:		Tuple      							=     (TFBlipTextModel,) if is_tf_available() else ()
					A__					:		Optional[int]      							=     False
					A__					:		Union[str, Any]      							=     False
					A__					:		Union[str, Any]      							=     False



					def      _a				(  self       :							Any       ):






								"""simple docstring"""


								A__	  =     BlipTextModelTester(self       )
								A__	  =     ConfigTester(self					,       config_class=_snake_case					,       hidden_size=37       )



					def      _a				(  self       :							List[str]       ):






								"""simple docstring"""


								self.config_tester.run_common_tests()



					def      _a				(  self       :							Union[str, Any]       ):






								"""simple docstring"""


								A__	  =     self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*_snake_case       )



					def      _a				(  self       :							Tuple       ):






								"""simple docstring"""


								pass



					def      _a				(  self       :							int       ):






								"""simple docstring"""


								pass



					@unittest.skip(reason='Blip does not use inputs_embeds'       )
					def      _a				(  self       :							Any       ):






								"""simple docstring"""


								pass



					@unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING'       )
					def      _a				(  self       :							str       ):






								"""simple docstring"""


								pass



					@unittest.skip(reason='BlipTextModel has no base class and is not available in MODEL_MAPPING'       )
					def      _a				(  self       :							Optional[Any]       ):






								"""simple docstring"""


								pass



					@slow
					def      _a				(  self       :							Union[str, Any]       ):






								"""simple docstring"""


								for model_name in TF_BLIP_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											A__	  =     TFBlipTextModel.from_pretrained(_snake_case       )
											self.assertIsNotNone(_snake_case       )



					def      _a				(  self       :							int					,       _snake_case       :							int=True       ):






								"""simple docstring"""


								super().test_pt_tf_model_equivalence(allow_missing_keys=_snake_case       )




