

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





@require_flax
class     snake_case	:

				def 							lowercase_     (	self							:				Optional[int]     ,  UpperCamelCase__							:				List[str]     ,  UpperCamelCase__							:				int)->   Tuple:



						'''simple docstring'''


						pass

				def 							lowercase_     (	self							:				Dict)->   int:



						'''simple docstring'''


						pass

				def 							lowercase_     (	self							:				List[Any])->   Tuple:



						'''simple docstring'''


						pass

				def 							lowercase_     (	self							:				Dict     ,  UpperCamelCase__							:				np.ndarray     ,  UpperCamelCase__							:				np.ndarray     ,  UpperCamelCase__							:				float)->   str:



						'''simple docstring'''


						__lowerCAmelCase:       List[str]          =			np.abs((a - b)).max()
						self.assertLessEqual(UpperCamelCase__     ,  UpperCamelCase__     ,  f"Difference between torch and flax is {diff} (>= {tol}).")

				def 							lowercase_     (	self							:				str     ,  UpperCamelCase__							:				Any     ,  UpperCamelCase__							:				Union[str, Any]     ,  UpperCamelCase__							:				Dict     ,  UpperCamelCase__							:				List[str]     ,  UpperCamelCase__							:				Tuple=None     ,  **UpperCamelCase__							:				Tuple)->   str:



						'''simple docstring'''


						__lowerCAmelCase:       List[Any]          =			VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase__     ,  UpperCamelCase__)

						__lowerCAmelCase:       Tuple          =			FlaxVisionTextDualEncoderModel(UpperCamelCase__)

						__lowerCAmelCase:       List[Any]          =			model(input_ids=UpperCamelCase__     ,  pixel_values=UpperCamelCase__     ,  attention_mask=UpperCamelCase__)

						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							:				List[str]     ,  UpperCamelCase__							:				int     ,  UpperCamelCase__							:				str     ,  UpperCamelCase__							:				int     ,  UpperCamelCase__							:				List[str]     ,  UpperCamelCase__							:				List[Any]=None     ,  **UpperCamelCase__							:				Optional[int])->   Union[str, Any]:



						'''simple docstring'''


						__lowerCAmelCase      , __lowerCAmelCase:       Dict          =			self.get_vision_text_model(UpperCamelCase__     ,  UpperCamelCase__)
						__lowerCAmelCase:       Optional[Any]          =			{"vision_model": vision_model, "text_model": text_model}
						__lowerCAmelCase:       Optional[Any]          =			FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase__)

						__lowerCAmelCase:       Tuple          =			model(input_ids=UpperCamelCase__     ,  pixel_values=UpperCamelCase__     ,  attention_mask=UpperCamelCase__)

						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[str]     ,  UpperCamelCase__							:				int     ,  UpperCamelCase__							:				Any     ,  UpperCamelCase__							:				int     ,  UpperCamelCase__							:				Any     ,  UpperCamelCase__							:				int=None     ,  **UpperCamelCase__							:				Any)->   Tuple:



						'''simple docstring'''


						__lowerCAmelCase      , __lowerCAmelCase:       List[Any]          =			self.get_vision_text_model(UpperCamelCase__     ,  UpperCamelCase__)
						__lowerCAmelCase:       Dict          =			{"vision_model": vision_model, "text_model": text_model}
						__lowerCAmelCase:       Optional[Any]          =			FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase__)

						__lowerCAmelCase:       int          =			model(input_ids=UpperCamelCase__     ,  pixel_values=UpperCamelCase__     ,  attention_mask=UpperCamelCase__)
						__lowerCAmelCase:       Optional[Any]          =			output[0]

						with tempfile.TemporaryDirectory() as tmpdirname:
								model.save_pretrained(UpperCamelCase__)
								__lowerCAmelCase:       List[Any]          =			FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase__)

								__lowerCAmelCase:       Any          =			model(input_ids=UpperCamelCase__     ,  pixel_values=UpperCamelCase__     ,  attention_mask=UpperCamelCase__)
								__lowerCAmelCase:       Dict          =			after_output[0]
								__lowerCAmelCase:       List[str]          =			np.amax(np.abs(out_a - out_a))
								self.assertLessEqual(UpperCamelCase__     ,  1e-3)

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



						'''simple docstring'''


						__lowerCAmelCase      , __lowerCAmelCase:       Tuple          =			self.get_vision_text_model(UpperCamelCase__     ,  UpperCamelCase__)
						__lowerCAmelCase:       List[str]          =			{"vision_model": vision_model, "text_model": text_model}
						__lowerCAmelCase:       Tuple          =			FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCamelCase__)

						__lowerCAmelCase:       Optional[int]          =			model(
						    input_ids=UpperCamelCase__     ,  pixel_values=UpperCamelCase__     ,  attention_mask=UpperCamelCase__     ,  output_attentions=UpperCamelCase__)

						__lowerCAmelCase:       Optional[int]          =			output.vision_model_output.attentions
						self.assertEqual(len(UpperCamelCase__)     ,  vision_config.num_hidden_layers)

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

						__lowerCAmelCase:       Optional[Any]          =			output.text_model_output.attentions
						self.assertEqual(len(UpperCamelCase__)     ,  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							:				str     ,  UpperCamelCase__							:				int     ,  UpperCamelCase__							:				Union[str, Any]     ,  UpperCamelCase__							:				List[Any])->   str:



						'''simple docstring'''


						pt_model.to(UpperCamelCase__)
						pt_model.eval()

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

						with torch.no_grad():
								__lowerCAmelCase:       List[str]          =			pt_model(**UpperCamelCase__).to_tuple()

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

						# PT -> Flax
						with tempfile.TemporaryDirectory() as tmpdirname:
								pt_model.save_pretrained(UpperCamelCase__)
								__lowerCAmelCase:       Optional[int]          =			FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase__     ,  from_pt=UpperCamelCase__)

						__lowerCAmelCase:       List[Any]          =			fx_model_loaded(**UpperCamelCase__).to_tuple()
						self.assertEqual(len(UpperCamelCase__)     ,  len(UpperCamelCase__)     ,  "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(UpperCamelCase__     ,  pt_output.numpy()     ,  4e-2)

						# Flax -> PT
						with tempfile.TemporaryDirectory() as tmpdirname:
								fx_model.save_pretrained(UpperCamelCase__)
								__lowerCAmelCase:       Union[str, Any]          =			VisionTextDualEncoderModel.from_pretrained(UpperCamelCase__     ,  from_flax=UpperCamelCase__)

						pt_model_loaded.to(UpperCamelCase__)
						pt_model_loaded.eval()

						with torch.no_grad():
								__lowerCAmelCase:       Union[str, Any]          =			pt_model_loaded(**UpperCamelCase__).to_tuple()

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

				def 							lowercase_     (	self							:				Union[str, Any]     ,  UpperCamelCase__							:				Optional[Any]     ,  UpperCamelCase__							:				List[Any]     ,  UpperCamelCase__							:				Tuple)->   int:



						'''simple docstring'''


						__lowerCAmelCase:       Tuple          =			VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase__     ,  UpperCamelCase__)

						__lowerCAmelCase:       Any          =			VisionTextDualEncoderModel(UpperCamelCase__)
						__lowerCAmelCase:       List[Any]          =			FlaxVisionTextDualEncoderModel(UpperCamelCase__)

						__lowerCAmelCase:       str          =			convert_pytorch_state_dict_to_flax(pt_model.state_dict()     ,  UpperCamelCase__)
						__lowerCAmelCase:       int          =			fx_state

						self.check_pt_flax_equivalence(UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__)

				def 							lowercase_     (	self							:				int     ,  UpperCamelCase__							:				Tuple     ,  UpperCamelCase__							:				Dict     ,  UpperCamelCase__							:				List[Any])->   str:



						'''simple docstring'''


						__lowerCAmelCase:       List[Any]          =			VisionTextDualEncoderConfig.from_vision_text_configs(UpperCamelCase__     ,  UpperCamelCase__)

						__lowerCAmelCase:       Any          =			VisionTextDualEncoderModel(UpperCamelCase__)
						__lowerCAmelCase:       Optional[int]          =			FlaxVisionTextDualEncoderModel(UpperCamelCase__)

						__lowerCAmelCase:       Dict          =			load_flax_weights_in_pytorch_model(UpperCamelCase__     ,  fx_model.params)

						self.check_pt_flax_equivalence(UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__)

				def 							lowercase_     (	self							:				Any)->   int:



						'''simple docstring'''


						__lowerCAmelCase:       str          =			self.prepare_config_and_inputs()
						self.check_model_from_pretrained_configs(**UpperCamelCase__)

				def 							lowercase_     (	self							:				Any)->   str:



						'''simple docstring'''


						__lowerCAmelCase:       Dict          =			self.prepare_config_and_inputs()
						self.check_vision_text_dual_encoder_from_pretrained(**UpperCamelCase__)

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



						'''simple docstring'''


						__lowerCAmelCase:       Tuple          =			self.prepare_config_and_inputs()
						self.check_save_load(**UpperCamelCase__)

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



						'''simple docstring'''


						__lowerCAmelCase:       Optional[Any]          =			self.prepare_config_and_inputs()
						self.check_vision_text_output_attention(**UpperCamelCase__)

				@is_pt_flax_cross_test
				def 							lowercase_     (	self							:				List[Any])->   Dict:



						'''simple docstring'''


						__lowerCAmelCase:       Tuple          =			self.prepare_config_and_inputs()
						__lowerCAmelCase:       Union[str, Any]          =			config_inputs_dict.pop("vision_config")
						__lowerCAmelCase:       List[Any]          =			config_inputs_dict.pop("text_config")

						__lowerCAmelCase:       List[Any]          =			config_inputs_dict

						self.check_equivalence_pt_to_flax(UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__)
						self.check_equivalence_flax_to_pt(UpperCamelCase__     ,  UpperCamelCase__     ,  UpperCamelCase__)




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



						'''simple docstring'''


						__lowerCAmelCase      , __lowerCAmelCase:       List[str]          =			self.get_pretrained_model_and_inputs()

						__lowerCAmelCase:       Tuple          =			model_a(**UpperCamelCase__)
						__lowerCAmelCase:       Dict          =			outputs[0]

						with tempfile.TemporaryDirectory() as tmp_dirname:
								model_a.save_pretrained(UpperCamelCase__)
								__lowerCAmelCase:       List[Any]          =			FlaxVisionTextDualEncoderModel.from_pretrained(UpperCamelCase__)

								__lowerCAmelCase:       Tuple          =			model_a(**UpperCamelCase__)
								__lowerCAmelCase:       Optional[Any]          =			after_outputs[0]
								__lowerCAmelCase:       Tuple          =			np.amax(np.abs(out_a - out_a))
								self.assertLessEqual(UpperCamelCase__     ,  1e-5)





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

				def 							lowercase_     (	self							:				str)->   Dict:



						'''simple docstring'''


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

						return model, inputs

				def 							lowercase_     (	self							:				Union[str, Any]     ,  UpperCamelCase__							:				Tuple     ,  UpperCamelCase__							:				Optional[Any])->   Any:



						'''simple docstring'''


						__lowerCAmelCase:       str          =			FlaxViTModel(UpperCamelCase__)
						__lowerCAmelCase:       int          =			FlaxBertModel(UpperCamelCase__)
						return vision_model, text_model




				def 							lowercase_     (	self							:				Any)->   List[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       List[str]          =			FlaxViTModelTester(self)
						__lowerCAmelCase:       Any          =			FlaxBertModelTester(self)
						__lowerCAmelCase:       Optional[Any]          =			vit_model_tester.prepare_config_and_inputs()
						__lowerCAmelCase:       str          =			bert_model_tester.prepare_config_and_inputs()

						__lowerCAmelCase      , __lowerCAmelCase:       Optional[int]          =			vision_config_and_inputs

						__lowerCAmelCase      , __lowerCAmelCase      , __lowerCAmelCase      , __lowerCAmelCase:       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     snake_case	(				__snake_case,							unittest.TestCase  ):

				def 							lowercase_     (	self							:				Any)->   Tuple:



						'''simple docstring'''


						__lowerCAmelCase:       Optional[int]          =			FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
						    "hf-internal-testing/tiny-random-clip"     ,  "hf-internal-testing/tiny-bert"     ,  vision_from_pt=UpperCamelCase__     ,  text_from_pt=UpperCamelCase__     ,  )
						__lowerCAmelCase:       int          =			1_3
						__lowerCAmelCase:       Dict          =			floats_tensor(
						    [
						        batch_size,
						        model.config.vision_config.num_channels,
						        model.config.vision_config.image_size,
						        model.config.vision_config.image_size,
						    ])
						__lowerCAmelCase:       Optional[int]          =			ids_tensor([batch_size, 4]     ,  model.config.text_config.vocab_size)
						__lowerCAmelCase:       str          =			random_attention_mask([batch_size, 4])
						__lowerCAmelCase:       str          =			{"pixel_values": pixel_values, "input_ids": input_ids, "attention_mask": attention_mask}

						return model, inputs

				def 							lowercase_     (	self							:				Optional[Any]     ,  UpperCamelCase__							:				int     ,  UpperCamelCase__							:				Union[str, Any])->   Union[str, Any]:



						'''simple docstring'''


						__lowerCAmelCase:       Union[str, Any]          =			FlaxCLIPVisionModel(UpperCamelCase__)
						__lowerCAmelCase:       Tuple          =			FlaxBertModel(UpperCamelCase__)
						return vision_model, text_model




				def 							lowercase_     (	self							:				str)->   Dict:



						'''simple docstring'''


						__lowerCAmelCase:       Optional[int]          =			FlaxCLIPVisionModelTester(self)
						__lowerCAmelCase:       Union[str, Any]          =			FlaxBertModelTester(self)
						__lowerCAmelCase:       Optional[Any]          =			clip_model_tester.prepare_config_and_inputs()
						__lowerCAmelCase:       Dict          =			bert_model_tester.prepare_config_and_inputs()

						__lowerCAmelCase      , __lowerCAmelCase:       Optional[Any]          =			vision_config_and_inputs

						__lowerCAmelCase      , __lowerCAmelCase      , __lowerCAmelCase      , __lowerCAmelCase:       Optional[Any]          =			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     snake_case	(				unittest.TestCase  ):

				@slow
				def 							lowercase_     (	self							:				Optional[Any])->   List[Any]:



						'''simple docstring'''


						__lowerCAmelCase:       Optional[Any]          =			FlaxVisionTextDualEncoderModel.from_pretrained("clip-italian/clip-italian"     ,  logit_scale_init_value=1.0)
						__lowerCAmelCase:       Optional[int]          =			VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian")

						__lowerCAmelCase:       List[str]          =			Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
						__lowerCAmelCase:       str          =			processor(
						    text=["una foto di un gatto", "una foto di un cane"]     ,  images=UpperCamelCase__     ,  padding=UpperCamelCase__     ,  return_tensors="np")

						__lowerCAmelCase:       List[str]          =			model(**UpperCamelCase__)

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

						__lowerCAmelCase:       str          =			np.array([[1.2284727, 0.3104122]])

						self.assertTrue(np.allclose(outputs.logits_per_image     ,  UpperCamelCase__     ,  atol=1e-3))





"""simple docstring"""


import copy
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, Optional, Union





@dataclass
class     snake_case	:
				SCREAMING_SNAKE_CASE_   :      Optional[Union[str, Path]]         =  None
				SCREAMING_SNAKE_CASE_   :      bool         =  False
				SCREAMING_SNAKE_CASE_   :      bool         =  False
				SCREAMING_SNAKE_CASE_   :      bool         =  False
				SCREAMING_SNAKE_CASE_   :      Optional[Dict]         =  None
				SCREAMING_SNAKE_CASE_   :      Optional[str]         =  None
				SCREAMING_SNAKE_CASE_   :      bool         =  False
				SCREAMING_SNAKE_CASE_   :      bool         =  False
				SCREAMING_SNAKE_CASE_   :      bool         =  False
				SCREAMING_SNAKE_CASE_   :      bool         =  True
				SCREAMING_SNAKE_CASE_   :      Optional[int]         =  None
				SCREAMING_SNAKE_CASE_   :      int         =  1
				SCREAMING_SNAKE_CASE_   :      Optional[Union[str, bool]]         =  None
				SCREAMING_SNAKE_CASE_   :      bool         =  False
				SCREAMING_SNAKE_CASE_   :      Optional[Dict]         =  None
				SCREAMING_SNAKE_CASE_   :      Optional[str]         =  None

				def 							lowercase_     (	self							:				str)->   "DownloadConfig":



						'''simple docstring'''


						return self.__class__(**{k: copy.deepcopy(UpperCamelCase__) for k, v in self.__dict__.items()})


