






"""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        SCREAMING_SNAKE_CASE       (      lowerCamelCase_):
					if isinstance(lowerCamelCase_ ,     collections.abc.Iterable):
										return x
					return (x, x)







@require_flax
class        _SCREAMING_SNAKE_CASE						:





							"""simple docstring"""





							def  lowercase		(   self:     List[str]				,		__A:     Dict				,		__A:     str    ):

												'''simple docstring'''

												pass




							def  lowercase		(   self:     int    ):

												'''simple docstring'''

												pass




							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												pass




							def  lowercase		(   self:     List[str]				,		__A:     np.ndarray				,		__A:     np.ndarray				,		__A:     float    ):

												'''simple docstring'''

												a__          =  np.abs((a - b)    ).max()
												self.assertLessEqual(__A				,		__A				,		F'Difference between torch and flax is {diff} (>= {tol}).'    )




							def  lowercase		(   self:     Any				,		__A:     str				,		__A:     str				,		__A:     Optional[Any]				,		__A:     List[Any]				,		__A:     Tuple=None				,		**__A:     Union[str, Any]    ):

												'''simple docstring'''

												a__          =  VisionTextDualEncoderConfig.from_vision_text_configs(__A				,		__A    )

												a__          =  FlaxVisionTextDualEncoderModel(__A    )

												a__          =  model(input_ids=__A				,		pixel_values=__A				,		attention_mask=__A    )

												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  lowercase		(   self:     int				,		__A:     Optional[Any]				,		__A:     List[str]				,		__A:     List[Any]				,		__A:     List[str]				,		__A:     Optional[int]=None				,		**__A:     Any    ):

												'''simple docstring'''

												a__       ,a__          =  self.get_vision_text_model(__A				,		__A    )
												a__          =  {'''vision_model''': vision_model, '''text_model''': text_model}
												a__          =  FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__A    )

												a__          =  model(input_ids=__A				,		pixel_values=__A				,		attention_mask=__A    )

												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  lowercase		(   self:     List[Any]				,		__A:     Tuple				,		__A:     Union[str, Any]				,		__A:     Optional[Any]				,		__A:     int				,		__A:     Dict=None				,		**__A:     List[str]    ):

												'''simple docstring'''

												a__       ,a__          =  self.get_vision_text_model(__A				,		__A    )
												a__          =  {'''vision_model''': vision_model, '''text_model''': text_model}
												a__          =  FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__A    )

												a__          =  model(input_ids=__A				,		pixel_values=__A				,		attention_mask=__A    )
												a__          =  output[0]

												with tempfile.TemporaryDirectory() as tmpdirname:
																	model.save_pretrained(__A    )
																	a__          =  FlaxVisionTextDualEncoderModel.from_pretrained(__A    )

																	a__          =  model(input_ids=__A				,		pixel_values=__A				,		attention_mask=__A    )
																	a__          =  after_output[0]
																	a__          =  np.amax(np.abs(out_a - out_a    )    )
																	self.assertLessEqual(__A				,		1e-3    )




							def  lowercase		(   self:     Any				,		__A:     Tuple				,		__A:     int				,		__A:     List[Any]				,		__A:     Union[str, Any]				,		__A:     str=None				,		**__A:     str    ):

												'''simple docstring'''

												a__       ,a__          =  self.get_vision_text_model(__A				,		__A    )
												a__          =  {'''vision_model''': vision_model, '''text_model''': text_model}
												a__          =  FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__A    )

												a__          =  model(
												    input_ids=__A				,		pixel_values=__A				,		attention_mask=__A				,		output_attentions=__A    )

												a__          =  output.vision_model_output.attentions
												self.assertEqual(len(__A    )				,		vision_config.num_hidden_layers    )

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

												a__          =  output.text_model_output.attentions
												self.assertEqual(len(__A    )				,		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  lowercase		(   self:     int				,		__A:     int				,		__A:     Any				,		__A:     Union[str, Any]    ):

												'''simple docstring'''

												pt_model.to(__A    )
												pt_model.eval()

												# prepare inputs
												a__          =  inputs_dict
												a__          =  {k: torch.tensor(v.tolist()    ) for k, v in flax_inputs.items()}

												with torch.no_grad():
																	a__          =  pt_model(**__A    ).to_tuple()

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

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

												a__          =  fx_model_loaded(**__A    ).to_tuple()
												self.assertEqual(len(__A    )				,		len(__A    )				,		'''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(__A				,		pt_output.numpy()				,		4e-2    )

												# Flax -> PT
												with tempfile.TemporaryDirectory() as tmpdirname:
																	fx_model.save_pretrained(__A    )
																	a__          =  VisionTextDualEncoderModel.from_pretrained(__A				,		from_flax=__A    )

												pt_model_loaded.to(__A    )
												pt_model_loaded.eval()

												with torch.no_grad():
																	a__          =  pt_model_loaded(**__A    ).to_tuple()

												self.assertEqual(len(__A    )				,		len(__A    )				,		'''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(__A				,		pt_output_loaded.numpy()				,		4e-2    )




							def  lowercase		(   self:     Optional[Any]				,		__A:     int				,		__A:     int				,		__A:     Any    ):

												'''simple docstring'''

												a__          =  VisionTextDualEncoderConfig.from_vision_text_configs(__A				,		__A    )

												a__          =  VisionTextDualEncoderModel(__A    )
												a__          =  FlaxVisionTextDualEncoderModel(__A    )

												a__          =  convert_pytorch_state_dict_to_flax(pt_model.state_dict()				,		__A    )
												a__          =  fx_state

												self.check_pt_flax_equivalence(__A				,		__A				,		__A    )




							def  lowercase		(   self:     Dict				,		__A:     List[Any]				,		__A:     Any				,		__A:     str    ):

												'''simple docstring'''

												a__          =  VisionTextDualEncoderConfig.from_vision_text_configs(__A				,		__A    )

												a__          =  VisionTextDualEncoderModel(__A    )
												a__          =  FlaxVisionTextDualEncoderModel(__A    )

												a__          =  load_flax_weights_in_pytorch_model(__A				,		fx_model.params    )

												self.check_pt_flax_equivalence(__A				,		__A				,		__A    )




							def  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

												a__          =  self.prepare_config_and_inputs()
												self.check_model_from_pretrained_configs(**__A    )




							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												a__          =  self.prepare_config_and_inputs()
												self.check_vision_text_dual_encoder_from_pretrained(**__A    )




							def  lowercase		(   self:     List[Any]    ):

												'''simple docstring'''

												a__          =  self.prepare_config_and_inputs()
												self.check_save_load(**__A    )




							def  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

												a__          =  self.prepare_config_and_inputs()
												self.check_vision_text_output_attention(**__A    )




							@is_pt_flax_cross_test
							def  lowercase		(   self:     Dict    ):

												'''simple docstring'''

												a__          =  self.prepare_config_and_inputs()
												a__          =  config_inputs_dict.pop('''vision_config'''    )
												a__          =  config_inputs_dict.pop('''text_config'''    )

												a__          =  config_inputs_dict

												self.check_equivalence_pt_to_flax(__A				,		__A				,		__A    )
												self.check_equivalence_flax_to_pt(__A				,		__A				,		__A    )





							@slow
							def  lowercase		(   self:     Dict    ):

												'''simple docstring'''

												a__       ,a__          =  self.get_pretrained_model_and_inputs()

												a__          =  model_a(**__A    )
												a__          =  outputs[0]

												with tempfile.TemporaryDirectory() as tmp_dirname:
																	model_a.save_pretrained(__A    )
																	a__          =  FlaxVisionTextDualEncoderModel.from_pretrained(__A    )

																	a__          =  model_a(**__A    )
																	a__          =  after_outputs[0]
																	a__          =  np.amax(np.abs(out_a - out_a    )    )
																	self.assertLessEqual(__A				,		1e-5    )







@require_flax
class        _SCREAMING_SNAKE_CASE						(  __snake_case       , unittest.TestCase							):





							"""simple docstring"""





							def  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

												a__          =  FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
												    '''hf-internal-testing/tiny-random-vit'''				,		'''hf-internal-testing/tiny-bert'''				,		vision_from_pt=__A				,		text_from_pt=__A				,		)
												a__          =  13
												a__          =  floats_tensor(
												    [
												        batch_size,
												        model.config.vision_config.num_channels,
												        model.config.vision_config.image_size,
												        model.config.vision_config.image_size,
												    ]    )
												a__          =  ids_tensor([batch_size, 4]				,		model.config.text_config.vocab_size    )
												a__          =  random_attention_mask([batch_size, 4]    )
												a__          =  {'''pixel_values''': pixel_values, '''input_ids''': input_ids, '''attention_mask''': attention_mask}

												return model, inputs




							def  lowercase		(   self:     List[Any]				,		__A:     Dict				,		__A:     Optional[Any]    ):

												'''simple docstring'''

												a__          =  FlaxViTModel(__A    )
												a__          =  FlaxBertModel(__A    )
												return vision_model, text_model





							def  lowercase		(   self:     List[str]    ):

												'''simple docstring'''

												a__          =  FlaxViTModelTester(self    )
												a__          =  FlaxBertModelTester(self    )
												a__          =  vit_model_tester.prepare_config_and_inputs()
												a__          =  bert_model_tester.prepare_config_and_inputs()

												a__       ,a__          =  vision_config_and_inputs

												a__       ,a__       ,a__       ,a__          =  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        _SCREAMING_SNAKE_CASE						(  __snake_case       , unittest.TestCase							):





							"""simple docstring"""





							def  lowercase		(   self:     Optional[Any]    ):

												'''simple docstring'''

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

												return model, inputs




							def  lowercase		(   self:     Union[str, Any]				,		__A:     Tuple				,		__A:     Tuple    ):

												'''simple docstring'''

												a__          =  FlaxCLIPVisionModel(__A    )
												a__          =  FlaxBertModel(__A    )
												return vision_model, text_model





							def  lowercase		(   self:     Dict    ):

												'''simple docstring'''

												a__          =  FlaxCLIPVisionModelTester(self    )
												a__          =  FlaxBertModelTester(self    )
												a__          =  clip_model_tester.prepare_config_and_inputs()
												a__          =  bert_model_tester.prepare_config_and_inputs()

												a__       ,a__          =  vision_config_and_inputs

												a__       ,a__       ,a__       ,a__          =  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        _SCREAMING_SNAKE_CASE						(  unittest.TestCase							):





							"""simple docstring"""





							@slow
							def  lowercase		(   self:     Optional[int]    ):

												'''simple docstring'''

												a__          =  FlaxVisionTextDualEncoderModel.from_pretrained('''clip-italian/clip-italian'''				,		logit_scale_init_value=1.0    )
												a__          =  VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian'''    )

												a__          =  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''    )
												a__          =  processor(
												    text=['''una foto di un gatto''', '''una foto di un cane''']				,		images=__A				,		padding=__A				,		return_tensors='''np'''    )

												a__          =  model(**__A    )

												# 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])				,		)

												a__          =  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				,		__A				,		atol=1e-3    )    )










"""simple docstring"""







__a       :	List[Any]             = frozenset(
    [
        'prompt',
        'height',
        'width',
        'guidance_scale',
        'negative_prompt',
        'prompt_embeds',
        'negative_prompt_embeds',
        'cross_attention_kwargs',
    ]
)

__a       :	Union[str, Any]             = frozenset(['prompt', 'negative_prompt'])

__a       :	Any             = frozenset([])

__a       :	Union[str, Any]             = frozenset(['image'])

__a       :	Dict             = frozenset(
    [
        'image',
        'height',
        'width',
        'guidance_scale',
    ]
)

__a       :	Dict             = frozenset(['image'])

__a       :	Dict             = frozenset(
    [
        'prompt',
        'image',
        'height',
        'width',
        'guidance_scale',
        'negative_prompt',
        'prompt_embeds',
        'negative_prompt_embeds',
    ]
)

__a       :	Optional[Any]             = frozenset(['prompt', 'image', 'negative_prompt'])

__a       :	List[Any]             = frozenset(
    [
        # Text guided image variation with an image mask
        'prompt',
        'image',
        'mask_image',
        'height',
        'width',
        'guidance_scale',
        'negative_prompt',
        'prompt_embeds',
        'negative_prompt_embeds',
    ]
)

__a       :	Union[str, Any]             = frozenset(['prompt', 'image', 'mask_image', 'negative_prompt'])

__a       :	Optional[Any]             = frozenset(
    [
        # image variation with an image mask
        'image',
        'mask_image',
        'height',
        'width',
        'guidance_scale',
    ]
)

__a       :	int             = frozenset(['image', 'mask_image'])

__a       :	Tuple             = frozenset(
    [
        'example_image',
        'image',
        'mask_image',
        'height',
        'width',
        'guidance_scale',
    ]
)

__a       :	Optional[Any]             = frozenset(['example_image', 'image', 'mask_image'])

__a       :	Optional[Any]             = frozenset(['class_labels'])

__a       :	Tuple             = frozenset(['class_labels'])

__a       :	int             = frozenset(['batch_size'])

__a       :	int             = frozenset([])

__a       :	Union[str, Any]             = frozenset(['batch_size'])

__a       :	Tuple             = frozenset([])

__a       :	Dict             = frozenset(
    [
        'prompt',
        'audio_length_in_s',
        'guidance_scale',
        'negative_prompt',
        'prompt_embeds',
        'negative_prompt_embeds',
        'cross_attention_kwargs',
    ]
)

__a       :	Dict             = frozenset(['prompt', 'negative_prompt'])
__a       :	Optional[int]             = frozenset(['input_tokens'])

__a       :	str             = frozenset(['input_tokens'])


