



"""simple docstring"""

import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_flax_cross_test,
    require_flax,
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available

from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester


if is_flax_available():
							from transformers import (
							    FlaxBertModel,
							    FlaxCLIPVisionModel,
							    FlaxVisionTextDualEncoderModel,
							    FlaxViTModel,
							    VisionTextDualEncoderConfig,
							    VisionTextDualEncoderProcessor,
							)
							from transformers.modeling_flax_pytorch_utils import (
							    convert_pytorch_state_dict_to_flax,
							    load_flax_weights_in_pytorch_model,
							)


if is_torch_available():
							import torch

							from transformers import VisionTextDualEncoderModel

if is_vision_available():
							from PIL import Image
def  __snake_case							(	__A      :						Dict     )     ->       Dict:






				'''simple docstring'''
				if isinstance(__A							,		collections.abc.Iterable     ):
								return x
				return (x, x)
@require_flax
class     lowerCAmelCase__						:


	'''simple docstring'''







	def 			_lowerCAmelCase     (      self				:       int     ,       _SCREAMING_SNAKE_CASE				:       Optional[Any]     ,       _SCREAMING_SNAKE_CASE				:       List[str]    )						->	Any:





					"""simple docstring"""


					pass





	def 			_lowerCAmelCase     (      self				:       int    )						->	str:





					"""simple docstring"""


					pass





	def 			_lowerCAmelCase     (      self				:       Any    )						->	Any:





					"""simple docstring"""


					pass





	def 			_lowerCAmelCase     (      self				:       Optional[int]     ,       _SCREAMING_SNAKE_CASE				:       np.ndarray     ,       _SCREAMING_SNAKE_CASE				:       np.ndarray     ,       _SCREAMING_SNAKE_CASE				:       float    )						->	Union[str, Any]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Optional[int]							=     np.abs((a - b)    ).max()
					self.assertLessEqual(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       f"""Difference between torch and flax is {diff} (>= {tol})."""    )





	def 			_lowerCAmelCase     (      self				:       Union[str, Any]     ,       _SCREAMING_SNAKE_CASE				:       Optional[Any]     ,       _SCREAMING_SNAKE_CASE				:       Any     ,       _SCREAMING_SNAKE_CASE				:       Tuple     ,       _SCREAMING_SNAKE_CASE				:       Dict     ,       _SCREAMING_SNAKE_CASE				:       Tuple=None     ,       **_SCREAMING_SNAKE_CASE				:       Dict    )						->	List[Any]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Tuple							=     VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )

					SCREAMING_SNAKE_CASE						:							str							=     FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE    )

					SCREAMING_SNAKE_CASE						:							Optional[int]							=     model(input_ids=_SCREAMING_SNAKE_CASE     ,       pixel_values=_SCREAMING_SNAKE_CASE     ,       attention_mask=_SCREAMING_SNAKE_CASE    )

					self.assertEqual(output['text_embeds'].shape     ,       (input_ids.shape[0], config.projection_dim)    )
					self.assertEqual(output['image_embeds'].shape     ,       (pixel_values.shape[0], config.projection_dim)    )





	def 			_lowerCAmelCase     (      self				:       Any     ,       _SCREAMING_SNAKE_CASE				:       Union[str, Any]     ,       _SCREAMING_SNAKE_CASE				:       int     ,       _SCREAMING_SNAKE_CASE				:       Dict     ,       _SCREAMING_SNAKE_CASE				:       Tuple     ,       _SCREAMING_SNAKE_CASE				:       Dict=None     ,       **_SCREAMING_SNAKE_CASE				:       Optional[Any]    )						->	List[Any]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						:							List[Any]							=     self.get_vision_text_model(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )
					SCREAMING_SNAKE_CASE						:							Any							=     {'vision_model': vision_model, 'text_model': text_model}
					SCREAMING_SNAKE_CASE						:							Any							=     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE    )

					SCREAMING_SNAKE_CASE						:							Any							=     model(input_ids=_SCREAMING_SNAKE_CASE     ,       pixel_values=_SCREAMING_SNAKE_CASE     ,       attention_mask=_SCREAMING_SNAKE_CASE    )

					self.assertEqual(output['text_embeds'].shape     ,       (input_ids.shape[0], model.config.projection_dim)    )
					self.assertEqual(output['image_embeds'].shape     ,       (pixel_values.shape[0], model.config.projection_dim)    )





	def 			_lowerCAmelCase     (      self				:       Optional[Any]     ,       _SCREAMING_SNAKE_CASE				:       Any     ,       _SCREAMING_SNAKE_CASE				:       Any     ,       _SCREAMING_SNAKE_CASE				:       Tuple     ,       _SCREAMING_SNAKE_CASE				:       List[str]     ,       _SCREAMING_SNAKE_CASE				:       str=None     ,       **_SCREAMING_SNAKE_CASE				:       Optional[Any]    )						->	int:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						:							int							=     self.get_vision_text_model(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )
					SCREAMING_SNAKE_CASE						:							List[str]							=     {'vision_model': vision_model, 'text_model': text_model}
					SCREAMING_SNAKE_CASE						:							List[str]							=     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE    )

					SCREAMING_SNAKE_CASE						:							Any							=     model(input_ids=_SCREAMING_SNAKE_CASE     ,       pixel_values=_SCREAMING_SNAKE_CASE     ,       attention_mask=_SCREAMING_SNAKE_CASE    )
					SCREAMING_SNAKE_CASE						:							Any							=     output[0]

					with tempfile.TemporaryDirectory() as tmpdirname:
									model.save_pretrained(_SCREAMING_SNAKE_CASE    )
									SCREAMING_SNAKE_CASE						:							str							=     FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE    )

									SCREAMING_SNAKE_CASE						:							Optional[int]							=     model(input_ids=_SCREAMING_SNAKE_CASE     ,       pixel_values=_SCREAMING_SNAKE_CASE     ,       attention_mask=_SCREAMING_SNAKE_CASE    )
									SCREAMING_SNAKE_CASE						:							List[Any]							=     after_output[0]
									SCREAMING_SNAKE_CASE						:							List[Any]							=     np.amax(np.abs(out_a - out_a    )    )
									self.assertLessEqual(_SCREAMING_SNAKE_CASE     ,       1E-3    )





	def 			_lowerCAmelCase     (      self				:       Dict     ,       _SCREAMING_SNAKE_CASE				:       Union[str, Any]     ,       _SCREAMING_SNAKE_CASE				:       List[Any]     ,       _SCREAMING_SNAKE_CASE				:       Tuple     ,       _SCREAMING_SNAKE_CASE				:       Optional[Any]     ,       _SCREAMING_SNAKE_CASE				:       Dict=None     ,       **_SCREAMING_SNAKE_CASE				:       Optional[Any]    )						->	str:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						:							Optional[int]							=     self.get_vision_text_model(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )
					SCREAMING_SNAKE_CASE						:							List[Any]							=     {'vision_model': vision_model, 'text_model': text_model}
					SCREAMING_SNAKE_CASE						:							Dict							=     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**_SCREAMING_SNAKE_CASE    )

					SCREAMING_SNAKE_CASE						:							Dict							=     model(
					    input_ids=_SCREAMING_SNAKE_CASE     ,       pixel_values=_SCREAMING_SNAKE_CASE     ,       attention_mask=_SCREAMING_SNAKE_CASE     ,       output_attentions=_SCREAMING_SNAKE_CASE    )

					SCREAMING_SNAKE_CASE						:							Dict							=     output.vision_model_output.attentions
					self.assertEqual(len(_SCREAMING_SNAKE_CASE    )     ,       vision_config.num_hidden_layers    )

					# in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
					SCREAMING_SNAKE_CASE						:							Dict							=     to_atuple(vision_model.config.image_size    )
					SCREAMING_SNAKE_CASE						:							str							=     to_atuple(vision_model.config.patch_size    )
					SCREAMING_SNAKE_CASE						:							List[str]							=     (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
					SCREAMING_SNAKE_CASE						:							Optional[Any]							=     num_patches + 1
					self.assertEqual(vision_attentions[0].shape[-3:]     ,       (vision_config.num_attention_heads, seq_len, seq_len)    )

					SCREAMING_SNAKE_CASE						:							List[str]							=     output.text_model_output.attentions
					self.assertEqual(len(_SCREAMING_SNAKE_CASE    )     ,       text_config.num_hidden_layers    )

					self.assertEqual(
					    text_attentions[0].shape[-3:]     ,       (text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])     ,       )





	def 			_lowerCAmelCase     (      self				:       Tuple     ,       _SCREAMING_SNAKE_CASE				:       Optional[Any]     ,       _SCREAMING_SNAKE_CASE				:       Optional[Any]     ,       _SCREAMING_SNAKE_CASE				:       str    )						->	Any:





					"""simple docstring"""


					pt_model.to(_SCREAMING_SNAKE_CASE    )
					pt_model.eval()

					# prepare inputs
					SCREAMING_SNAKE_CASE						:							Any							=     inputs_dict
					SCREAMING_SNAKE_CASE						:							List[str]							=     {k: torch.tensor(v.tolist()    ) for k, v in flax_inputs.items()}

					with torch.no_grad():
									SCREAMING_SNAKE_CASE						:							Any							=     pt_model(**_SCREAMING_SNAKE_CASE    ).to_tuple()

					SCREAMING_SNAKE_CASE						:							Tuple							=     fx_model(**_SCREAMING_SNAKE_CASE    ).to_tuple()
					self.assertEqual(len(_SCREAMING_SNAKE_CASE    )     ,       len(_SCREAMING_SNAKE_CASE    )     ,       'Output lengths differ between Flax and PyTorch'    )
					for fx_output, pt_output in zip(fx_outputs[:4]     ,       pt_outputs[:4]    ):
									self.assert_almost_equals(_SCREAMING_SNAKE_CASE     ,       pt_output.numpy()     ,       4E-2    )

					# PT -> Flax
					with tempfile.TemporaryDirectory() as tmpdirname:
									pt_model.save_pretrained(_SCREAMING_SNAKE_CASE    )
									SCREAMING_SNAKE_CASE						:							Dict							=     FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE     ,       from_pt=_SCREAMING_SNAKE_CASE    )

					SCREAMING_SNAKE_CASE						:							Optional[int]							=     fx_model_loaded(**_SCREAMING_SNAKE_CASE    ).to_tuple()
					self.assertEqual(len(_SCREAMING_SNAKE_CASE    )     ,       len(_SCREAMING_SNAKE_CASE    )     ,       'Output lengths differ between Flax and PyTorch'    )
					for fx_output_loaded, pt_output in zip(fx_outputs_loaded[:4]     ,       pt_outputs[:4]    ):
									self.assert_almost_equals(_SCREAMING_SNAKE_CASE     ,       pt_output.numpy()     ,       4E-2    )

					# Flax -> PT
					with tempfile.TemporaryDirectory() as tmpdirname:
									fx_model.save_pretrained(_SCREAMING_SNAKE_CASE    )
									SCREAMING_SNAKE_CASE						:							List[str]							=     VisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE     ,       from_flax=_SCREAMING_SNAKE_CASE    )

					pt_model_loaded.to(_SCREAMING_SNAKE_CASE    )
					pt_model_loaded.eval()

					with torch.no_grad():
									SCREAMING_SNAKE_CASE						:							Tuple							=     pt_model_loaded(**_SCREAMING_SNAKE_CASE    ).to_tuple()

					self.assertEqual(len(_SCREAMING_SNAKE_CASE    )     ,       len(_SCREAMING_SNAKE_CASE    )     ,       'Output lengths differ between Flax and PyTorch'    )
					for fx_output, pt_output_loaded in zip(fx_outputs[:4]     ,       pt_outputs_loaded[:4]    ):
									self.assert_almost_equals(_SCREAMING_SNAKE_CASE     ,       pt_output_loaded.numpy()     ,       4E-2    )





	def 			_lowerCAmelCase     (      self				:       Dict     ,       _SCREAMING_SNAKE_CASE				:       Dict     ,       _SCREAMING_SNAKE_CASE				:       Dict     ,       _SCREAMING_SNAKE_CASE				:       str    )						->	List[str]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )

					SCREAMING_SNAKE_CASE						:							Dict							=     VisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE    )
					SCREAMING_SNAKE_CASE						:							Dict							=     FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE    )

					SCREAMING_SNAKE_CASE						:							List[str]							=     convert_pytorch_state_dict_to_flax(pt_model.state_dict()     ,       _SCREAMING_SNAKE_CASE    )
					SCREAMING_SNAKE_CASE						:							Any							=     fx_state

					self.check_pt_flax_equivalence(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )





	def 			_lowerCAmelCase     (      self				:       Optional[Any]     ,       _SCREAMING_SNAKE_CASE				:       Dict     ,       _SCREAMING_SNAKE_CASE				:       Union[str, Any]     ,       _SCREAMING_SNAKE_CASE				:       str    )						->	List[Any]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							List[Any]							=     VisionTextDualEncoderConfig.from_vision_text_configs(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )

					SCREAMING_SNAKE_CASE						:							Dict							=     VisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE    )
					SCREAMING_SNAKE_CASE						:							List[Any]							=     FlaxVisionTextDualEncoderModel(_SCREAMING_SNAKE_CASE    )

					SCREAMING_SNAKE_CASE						:							Any							=     load_flax_weights_in_pytorch_model(_SCREAMING_SNAKE_CASE     ,       fx_model.params    )

					self.check_pt_flax_equivalence(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )





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





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Optional[Any]							=     self.prepare_config_and_inputs()
					self.check_model_from_pretrained_configs(**_SCREAMING_SNAKE_CASE    )





	def 			_lowerCAmelCase     (      self				:       str    )						->	Optional[int]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Tuple							=     self.prepare_config_and_inputs()
					self.check_vision_text_dual_encoder_from_pretrained(**_SCREAMING_SNAKE_CASE    )





	def 			_lowerCAmelCase     (      self				:       Optional[int]    )						->	Optional[int]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     self.prepare_config_and_inputs()
					self.check_save_load(**_SCREAMING_SNAKE_CASE    )





	def 			_lowerCAmelCase     (      self				:       str    )						->	List[Any]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     self.prepare_config_and_inputs()
					self.check_vision_text_output_attention(**_SCREAMING_SNAKE_CASE    )





	@is_pt_flax_cross_test
	def 			_lowerCAmelCase     (      self				:       Union[str, Any]    )						->	Any:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Dict							=     self.prepare_config_and_inputs()
					SCREAMING_SNAKE_CASE						:							int							=     config_inputs_dict.pop('vision_config'    )
					SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     config_inputs_dict.pop('text_config'    )

					SCREAMING_SNAKE_CASE						:							Any							=     config_inputs_dict

					self.check_equivalence_pt_to_flax(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )
					self.check_equivalence_flax_to_pt(_SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE     ,       _SCREAMING_SNAKE_CASE    )







	@slow
	def 			_lowerCAmelCase     (      self				:       Optional[int]    )						->	Dict:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						:							Tuple							=     self.get_pretrained_model_and_inputs()

					SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     model_a(**_SCREAMING_SNAKE_CASE    )
					SCREAMING_SNAKE_CASE						:							Dict							=     outputs[0]

					with tempfile.TemporaryDirectory() as tmp_dirname:
									model_a.save_pretrained(_SCREAMING_SNAKE_CASE    )
									SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     FlaxVisionTextDualEncoderModel.from_pretrained(_SCREAMING_SNAKE_CASE    )

									SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     model_a(**_SCREAMING_SNAKE_CASE    )
									SCREAMING_SNAKE_CASE						:							List[Any]							=     after_outputs[0]
									SCREAMING_SNAKE_CASE						:							Tuple							=     np.amax(np.abs(out_a - out_a    )    )
									self.assertLessEqual(_SCREAMING_SNAKE_CASE     ,       1E-5    )




@require_flax
class     lowerCAmelCase__						(	_lowerCamelCase							,							unittest.TestCase ):


	'''simple docstring'''







	def 			_lowerCAmelCase     (      self				:       str    )						->	List[Any]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Dict							=     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
					    'hf-internal-testing/tiny-random-vit'     ,       'hf-internal-testing/tiny-bert'     ,       vision_from_pt=_SCREAMING_SNAKE_CASE     ,       text_from_pt=_SCREAMING_SNAKE_CASE     ,       )
					SCREAMING_SNAKE_CASE						:							int							=     13
					SCREAMING_SNAKE_CASE						:							List[Any]							=     floats_tensor(
					    [
					        batch_size,
					        model.config.vision_config.num_channels,
					        model.config.vision_config.image_size,
					        model.config.vision_config.image_size,
					    ]    )
					SCREAMING_SNAKE_CASE						:							Optional[Any]							=     ids_tensor([batch_size, 4]     ,       model.config.text_config.vocab_size    )
					SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     random_attention_mask([batch_size, 4]    )
					SCREAMING_SNAKE_CASE						:							Optional[Any]							=     {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

					return model, inputs





	def 			_lowerCAmelCase     (      self				:       Any     ,       _SCREAMING_SNAKE_CASE				:       Optional[Any]     ,       _SCREAMING_SNAKE_CASE				:       Dict    )						->	Dict:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							List[str]							=     FlaxViTModel(_SCREAMING_SNAKE_CASE    )
					SCREAMING_SNAKE_CASE						:							List[str]							=     FlaxBertModel(_SCREAMING_SNAKE_CASE    )
					return vision_model, text_model







	def 			_lowerCAmelCase     (      self				:       Optional[int]    )						->	List[str]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Dict							=     FlaxViTModelTester(self    )
					SCREAMING_SNAKE_CASE						:							Tuple							=     FlaxBertModelTester(self    )
					SCREAMING_SNAKE_CASE						:							Optional[Any]							=     vit_model_tester.prepare_config_and_inputs()
					SCREAMING_SNAKE_CASE						:							List[Any]							=     bert_model_tester.prepare_config_and_inputs()

					SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						:							List[str]							=     vision_config_and_inputs

					SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						:							str							=     text_config_and_inputs

					# make sure that cross attention layers are added
					return {
					    "text_config": text_config,
					    "vision_config": vision_config,
					    "pixel_values": pixel_values,
					    "attention_mask": attention_mask,
					    "input_ids": input_ids,
					    "token_type_ids": token_type_ids,
					}




@require_torch
class     lowerCAmelCase__						(	_lowerCamelCase							,							unittest.TestCase ):


	'''simple docstring'''







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





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Tuple							=     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
					    'hf-internal-testing/tiny-random-clip'     ,       'hf-internal-testing/tiny-bert'     ,       vision_from_pt=_SCREAMING_SNAKE_CASE     ,       text_from_pt=_SCREAMING_SNAKE_CASE     ,       )
					SCREAMING_SNAKE_CASE						:							str							=     13
					SCREAMING_SNAKE_CASE						:							str							=     floats_tensor(
					    [
					        batch_size,
					        model.config.vision_config.num_channels,
					        model.config.vision_config.image_size,
					        model.config.vision_config.image_size,
					    ]    )
					SCREAMING_SNAKE_CASE						:							Any							=     ids_tensor([batch_size, 4]     ,       model.config.text_config.vocab_size    )
					SCREAMING_SNAKE_CASE						:							List[str]							=     random_attention_mask([batch_size, 4]    )
					SCREAMING_SNAKE_CASE						:							Dict							=     {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

					return model, inputs





	def 			_lowerCAmelCase     (      self				:       List[Any]     ,       _SCREAMING_SNAKE_CASE				:       List[Any]     ,       _SCREAMING_SNAKE_CASE				:       List[str]    )						->	List[str]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							List[Any]							=     FlaxCLIPVisionModel(_SCREAMING_SNAKE_CASE    )
					SCREAMING_SNAKE_CASE						:							Optional[int]							=     FlaxBertModel(_SCREAMING_SNAKE_CASE    )
					return vision_model, text_model







	def 			_lowerCAmelCase     (      self				:       str    )						->	List[str]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Tuple							=     FlaxCLIPVisionModelTester(self    )
					SCREAMING_SNAKE_CASE						:							Any							=     FlaxBertModelTester(self    )
					SCREAMING_SNAKE_CASE						:							Optional[int]							=     clip_model_tester.prepare_config_and_inputs()
					SCREAMING_SNAKE_CASE						:							Optional[Any]							=     bert_model_tester.prepare_config_and_inputs()

					SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						:							int							=     vision_config_and_inputs

					SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE				,						SCREAMING_SNAKE_CASE						:							Dict							=     text_config_and_inputs

					# make sure that cross attention layers are added
					return {
					    "text_config": text_config,
					    "vision_config": vision_config,
					    "pixel_values": pixel_values,
					    "attention_mask": attention_mask,
					    "input_ids": input_ids,
					    "token_type_ids": token_type_ids,
					}




@require_flax
@require_vision
class     lowerCAmelCase__						(	unittest.TestCase ):


	'''simple docstring'''







	@slow
	def 			_lowerCAmelCase     (      self				:       List[Any]    )						->	List[str]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Dict							=     FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian'     ,       logit_scale_init_value=1.0    )
					SCREAMING_SNAKE_CASE						:							Tuple							=     VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'    )

					SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'    )
					SCREAMING_SNAKE_CASE						:							Any							=     processor(
					    text=['una foto di un gatto', 'una foto di un cane']     ,       images=_SCREAMING_SNAKE_CASE     ,       padding=_SCREAMING_SNAKE_CASE     ,       return_tensors='np'    )

					SCREAMING_SNAKE_CASE						:							Optional[Any]							=     model(**_SCREAMING_SNAKE_CASE    )

					# verify the logits
					self.assertEqual(outputs.logits_per_image.shape     ,       (inputs.pixel_values.shape[0], inputs.input_ids.shape[0])    )
					self.assertEqual(
					    outputs.logits_per_text.shape     ,       (inputs.input_ids.shape[0], inputs.pixel_values.shape[0])     ,       )

					SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     np.array([[1.2_2_8_4_7_2_7, 0.3_1_0_4_1_2_2]]    )

					self.assertTrue(np.allclose(outputs.logits_per_image     ,       _SCREAMING_SNAKE_CASE     ,       atol=1E-3    )    )










"""simple docstring"""

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     lowerCAmelCase__						(	unittest.TestCase ):


	'''simple docstring'''







	def 			_lowerCAmelCase     (      self				:       List[Any]    )						->	str:





					"""simple docstring"""


					super().tearDown()
					gc.collect()
					torch.cuda.empty_cache()





	def 			_lowerCAmelCase     (      self				:       Any    )						->	str:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							int							=     StableDiffusionKDiffusionPipeline.from_pretrained('CompVis/stable-diffusion-v1-4'    )
					SCREAMING_SNAKE_CASE						:							Dict							=     sd_pipe.to(_SCREAMING_SNAKE_CASE    )
					sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE    )

					sd_pipe.set_scheduler('sample_euler'    )

					SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     'A painting of a squirrel eating a burger'
					SCREAMING_SNAKE_CASE						:							Optional[Any]							=     torch.manual_seed(0    )
					SCREAMING_SNAKE_CASE						:							Optional[Any]							=     sd_pipe([prompt]     ,       generator=_SCREAMING_SNAKE_CASE     ,       guidance_scale=9.0     ,       num_inference_steps=20     ,       output_type='np'    )

					SCREAMING_SNAKE_CASE						:							str							=     output.images

					SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     image[0, -3:, -3:, -1]

					assert image.shape == (1, 512, 512, 3)
					SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     np.array([0.0_4_4_7, 0.0_4_9_2, 0.0_4_6_8, 0.0_4_0_8, 0.0_3_8_3, 0.0_4_0_8, 0.0_3_5_4, 0.0_3_8_0, 0.0_3_3_9]    )

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





	def 			_lowerCAmelCase     (      self				:       Dict    )						->	Optional[int]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Optional[Any]							=     StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'    )
					SCREAMING_SNAKE_CASE						:							List[Any]							=     sd_pipe.to(_SCREAMING_SNAKE_CASE    )
					sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE    )

					sd_pipe.set_scheduler('sample_euler'    )

					SCREAMING_SNAKE_CASE						:							List[str]							=     'A painting of a squirrel eating a burger'
					SCREAMING_SNAKE_CASE						:							Optional[int]							=     torch.manual_seed(0    )
					SCREAMING_SNAKE_CASE						:							Dict							=     sd_pipe([prompt]     ,       generator=_SCREAMING_SNAKE_CASE     ,       guidance_scale=9.0     ,       num_inference_steps=20     ,       output_type='np'    )

					SCREAMING_SNAKE_CASE						:							Optional[int]							=     output.images

					SCREAMING_SNAKE_CASE						:							List[str]							=     image[0, -3:, -3:, -1]

					assert image.shape == (1, 512, 512, 3)
					SCREAMING_SNAKE_CASE						:							List[Any]							=     np.array([0.1_2_3_7, 0.1_3_2_0, 0.1_4_3_8, 0.1_3_5_9, 0.1_3_9_0, 0.1_1_3_2, 0.1_2_7_7, 0.1_1_7_5, 0.1_1_1_2]    )

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







	def 			_lowerCAmelCase     (      self				:       Dict    )						->	Optional[Any]:





					"""simple docstring"""


					SCREAMING_SNAKE_CASE						:							Optional[int]							=     StableDiffusionKDiffusionPipeline.from_pretrained('stabilityai/stable-diffusion-2-1-base'    )
					SCREAMING_SNAKE_CASE						:							Union[str, Any]							=     sd_pipe.to(_SCREAMING_SNAKE_CASE    )
					sd_pipe.set_progress_bar_config(disable=_SCREAMING_SNAKE_CASE    )

					sd_pipe.set_scheduler('sample_dpmpp_2m'    )

					SCREAMING_SNAKE_CASE						:							Optional[int]							=     'A painting of a squirrel eating a burger'
					SCREAMING_SNAKE_CASE						:							str							=     torch.manual_seed(0    )
					SCREAMING_SNAKE_CASE						:							Optional[Any]							=     sd_pipe(
					    [prompt]     ,       generator=_SCREAMING_SNAKE_CASE     ,       guidance_scale=7.5     ,       num_inference_steps=15     ,       output_type='np'     ,       use_karras_sigmas=_SCREAMING_SNAKE_CASE     ,       )

					SCREAMING_SNAKE_CASE						:							int							=     output.images

					SCREAMING_SNAKE_CASE						:							List[Any]							=     image[0, -3:, -3:, -1]

					assert image.shape == (1, 512, 512, 3)
					SCREAMING_SNAKE_CASE						:							int							=     np.array(
					    [0.1_1_3_8_1_6_8_9, 0.1_2_1_1_2_9_2_1, 0.1_3_8_9_4_5_7, 0.1_2_5_4_9_6_0_6, 0.1_2_4_4_9_6_4, 0.1_0_8_3_1_5_1_7, 0.1_1_5_6_2_8_6_6, 0.1_0_8_6_7_8_1_6, 0.1_0_4_9_9_0_4_8]    )

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





