





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

@require_flax
class    lowerCAmelCase							:
 def      A_	(      self  :      Any			,     UpperCAmelCase  :      Dict			,     UpperCAmelCase  :      Optional[Any]	)			->	Union[str, Any]:
     pass
 def      A_	(      self  :      Dict	)			->	int:
     pass
 def      A_	(      self  :      List[Any]	)			->	List[str]:
     pass
 def      A_	(      self  :      Union[str, Any]			,     UpperCAmelCase  :      np.ndarray			,     UpperCAmelCase  :      np.ndarray			,     UpperCAmelCase  :      float	)			->	Union[str, Any]:
     lowerCamelCase__    :      Optional[Any]					 =		np.abs((a - b)	).max()
     self.assertLessEqual(UpperCAmelCase			,     UpperCAmelCase			,     F"""Difference between torch and flax is {diff} (>= {tol})."""	)
 def      A_	(      self  :      Any			,     UpperCAmelCase  :      Dict			,     UpperCAmelCase  :      int			,     UpperCAmelCase  :      Optional[int]			,     UpperCAmelCase  :      List[Any]			,     UpperCAmelCase  :      Any=None			,     **UpperCAmelCase  :      Dict	)			->	Tuple:
     lowerCamelCase__    :      str					 =		VisionTextDualEncoderConfig.from_vision_text_configs(UpperCAmelCase			,     UpperCAmelCase	)

     lowerCamelCase__    :      str					 =		FlaxVisionTextDualEncoderModel(UpperCAmelCase	)

     lowerCamelCase__    :      int					 =		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      A_	(      self  :      Tuple			,     UpperCAmelCase  :      Any			,     UpperCAmelCase  :      List[Any]			,     UpperCAmelCase  :      Union[str, Any]			,     UpperCAmelCase  :      str			,     UpperCAmelCase  :      Dict=None			,     **UpperCAmelCase  :      Optional[int]	)			->	Dict:
     lowerCamelCase__ ,							lowerCamelCase__    :      Optional[Any]					 =		self.get_vision_text_model(UpperCAmelCase			,     UpperCAmelCase	)
     lowerCamelCase__    :      Union[str, Any]					 =		{'vision_model': vision_model, 'text_model': text_model}
     lowerCamelCase__    :      str					 =		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCAmelCase	)

     lowerCamelCase__    :      Any					 =		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      A_	(      self  :      Tuple			,     UpperCAmelCase  :      List[Any]			,     UpperCAmelCase  :      List[Any]			,     UpperCAmelCase  :      Optional[int]			,     UpperCAmelCase  :      int			,     UpperCAmelCase  :      Optional[int]=None			,     **UpperCAmelCase  :      List[str]	)			->	Dict:
     lowerCamelCase__ ,							lowerCamelCase__    :      str					 =		self.get_vision_text_model(UpperCAmelCase			,     UpperCAmelCase	)
     lowerCamelCase__    :      str					 =		{'vision_model': vision_model, 'text_model': text_model}
     lowerCamelCase__    :      Union[str, Any]					 =		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCAmelCase	)

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

     with tempfile.TemporaryDirectory() as tmpdirname:
         model.save_pretrained(UpperCAmelCase	)
         lowerCamelCase__    :      Union[str, Any]					 =		FlaxVisionTextDualEncoderModel.from_pretrained(UpperCAmelCase	)

         lowerCamelCase__    :      int					 =		model(input_ids=UpperCAmelCase			,     pixel_values=UpperCAmelCase			,     attention_mask=UpperCAmelCase	)
         lowerCamelCase__    :      List[Any]					 =		after_output[0]
         lowerCamelCase__    :      Optional[Any]					 =		np.amax(np.abs(out_a - out_a	)	)
         self.assertLessEqual(UpperCAmelCase			,     1e-3	)
 def      A_	(      self  :      Optional[int]			,     UpperCAmelCase  :      Optional[int]			,     UpperCAmelCase  :      Dict			,     UpperCAmelCase  :      str			,     UpperCAmelCase  :      str			,     UpperCAmelCase  :      str=None			,     **UpperCAmelCase  :      List[Any]	)			->	str:
     lowerCamelCase__ ,							lowerCamelCase__    :      Tuple					 =		self.get_vision_text_model(UpperCAmelCase			,     UpperCAmelCase	)
     lowerCamelCase__    :      Tuple					 =		{'vision_model': vision_model, 'text_model': text_model}
     lowerCamelCase__    :      Any					 =		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**UpperCAmelCase	)

     lowerCamelCase__    :      int					 =		model(
         input_ids=UpperCAmelCase			,     pixel_values=UpperCAmelCase			,     attention_mask=UpperCAmelCase			,     output_attentions=UpperCAmelCase	)

     lowerCamelCase__    :      Optional[Any]					 =		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__    :      str					 =		to_atuple(vision_model.config.image_size	)
     lowerCamelCase__    :      Optional[int]					 =		to_atuple(vision_model.config.patch_size	)
     lowerCamelCase__    :      Tuple					 =		(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
     lowerCamelCase__    :      Optional[Any]					 =		num_patches + 1
     self.assertEqual(vision_attentions[0].shape[-3:]			,     (vision_config.num_attention_heads, seq_len, seq_len)	)

     lowerCamelCase__    :      List[str]					 =		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      A_	(      self  :      Any			,     UpperCAmelCase  :      int			,     UpperCAmelCase  :      Optional[Any]			,     UpperCAmelCase  :      List[Any]	)			->	str:
     pt_model.to(UpperCAmelCase	)
     pt_model.eval()

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

     with torch.no_grad():
         lowerCamelCase__    :      Optional[int]					 =		pt_model(**UpperCAmelCase	).to_tuple()

     lowerCamelCase__    :      Tuple					 =		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[Any]					 =		FlaxVisionTextDualEncoderModel.from_pretrained(UpperCAmelCase			,     from_pt=UpperCAmelCase	)

     lowerCamelCase__    :      Optional[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__    :      Optional[int]					 =		VisionTextDualEncoderModel.from_pretrained(UpperCAmelCase			,     from_flax=UpperCAmelCase	)

     pt_model_loaded.to(UpperCAmelCase	)
     pt_model_loaded.eval()

     with torch.no_grad():
         lowerCamelCase__    :      Optional[int]					 =		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      A_	(      self  :      str			,     UpperCAmelCase  :      Tuple			,     UpperCAmelCase  :      int			,     UpperCAmelCase  :      Optional[int]	)			->	Dict:
     lowerCamelCase__    :      List[Any]					 =		VisionTextDualEncoderConfig.from_vision_text_configs(UpperCAmelCase			,     UpperCAmelCase	)

     lowerCamelCase__    :      Dict					 =		VisionTextDualEncoderModel(UpperCAmelCase	)
     lowerCamelCase__    :      Tuple					 =		FlaxVisionTextDualEncoderModel(UpperCAmelCase	)

     lowerCamelCase__    :      Optional[int]					 =		convert_pytorch_state_dict_to_flax(pt_model.state_dict()			,     UpperCAmelCase	)
     lowerCamelCase__    :      Dict					 =		fx_state

     self.check_pt_flax_equivalence(UpperCAmelCase			,     UpperCAmelCase			,     UpperCAmelCase	)
 def      A_	(      self  :      Tuple			,     UpperCAmelCase  :      int			,     UpperCAmelCase  :      Optional[Any]			,     UpperCAmelCase  :      Optional[int]	)			->	str:
     lowerCamelCase__    :      str					 =		VisionTextDualEncoderConfig.from_vision_text_configs(UpperCAmelCase			,     UpperCAmelCase	)

     lowerCamelCase__    :      Any					 =		VisionTextDualEncoderModel(UpperCAmelCase	)
     lowerCamelCase__    :      Dict					 =		FlaxVisionTextDualEncoderModel(UpperCAmelCase	)

     lowerCamelCase__    :      Dict					 =		load_flax_weights_in_pytorch_model(UpperCAmelCase			,     fx_model.params	)

     self.check_pt_flax_equivalence(UpperCAmelCase			,     UpperCAmelCase			,     UpperCAmelCase	)
 def      A_	(      self  :      List[Any]	)			->	int:
     lowerCamelCase__    :      Optional[int]					 =		self.prepare_config_and_inputs()
     self.check_model_from_pretrained_configs(**UpperCAmelCase	)
 def      A_	(      self  :      Any	)			->	Any:
     lowerCamelCase__    :      List[str]					 =		self.prepare_config_and_inputs()
     self.check_vision_text_dual_encoder_from_pretrained(**UpperCAmelCase	)
 def      A_	(      self  :      Any	)			->	Optional[int]:
     lowerCamelCase__    :      Tuple					 =		self.prepare_config_and_inputs()
     self.check_save_load(**UpperCAmelCase	)
 def      A_	(      self  :      Dict	)			->	str:
     lowerCamelCase__    :      int					 =		self.prepare_config_and_inputs()
     self.check_vision_text_output_attention(**UpperCAmelCase	)
 @is_pt_flax_cross_test
 def      A_	(      self  :      int	)			->	List[str]:
     lowerCamelCase__    :      str					 =		self.prepare_config_and_inputs()
     lowerCamelCase__    :      Dict					 =		config_inputs_dict.pop('vision_config'	)
     lowerCamelCase__    :      List[Any]					 =		config_inputs_dict.pop('text_config'	)

     lowerCamelCase__    :      Optional[Any]					 =		config_inputs_dict

     self.check_equivalence_pt_to_flax(UpperCAmelCase			,     UpperCAmelCase			,     UpperCAmelCase	)
     self.check_equivalence_flax_to_pt(UpperCAmelCase			,     UpperCAmelCase			,     UpperCAmelCase	)







 @slow
 def      A_	(      self  :      Any	)			->	Dict:
     lowerCamelCase__ ,							lowerCamelCase__    :      Tuple					 =		self.get_pretrained_model_and_inputs()

     lowerCamelCase__    :      int					 =		model_a(**UpperCAmelCase	)
     lowerCamelCase__    :      List[Any]					 =		outputs[0]

     with tempfile.TemporaryDirectory() as tmp_dirname:
         model_a.save_pretrained(UpperCAmelCase	)
         lowerCamelCase__    :      Tuple					 =		FlaxVisionTextDualEncoderModel.from_pretrained(UpperCAmelCase	)

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


@require_flax
class    lowerCAmelCase							(					__UpperCamelCase,  unittest.TestCase			):
 def      A_	(      self  :      Dict	)			->	Tuple:
     lowerCamelCase__    :      Optional[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__    :      List[str]					 =		13
     lowerCamelCase__    :      Optional[int]					 =		floats_tensor(
         [
             batch_size,
             model.config.vision_config.num_channels,
             model.config.vision_config.image_size,
             model.config.vision_config.image_size,
         ]	)
     lowerCamelCase__    :      Union[str, Any]					 =		ids_tensor([batch_size, 4]			,     model.config.text_config.vocab_size	)
     lowerCamelCase__    :      Union[str, Any]					 =		random_attention_mask([batch_size, 4]	)
     lowerCamelCase__    :      Tuple					 =		{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

     return model, inputs
 def      A_	(      self  :      Union[str, Any]			,     UpperCAmelCase  :      Union[str, Any]			,     UpperCAmelCase  :      str	)			->	Optional[int]:
     lowerCamelCase__    :      str					 =		FlaxViTModel(UpperCAmelCase	)
     lowerCamelCase__    :      int					 =		FlaxBertModel(UpperCAmelCase	)
     return vision_model, text_model







 def      A_	(      self  :      Any	)			->	Optional[int]:
     lowerCamelCase__    :      Any					 =		FlaxViTModelTester(self	)
     lowerCamelCase__    :      Tuple					 =		FlaxBertModelTester(self	)
     lowerCamelCase__    :      Union[str, Any]					 =		vit_model_tester.prepare_config_and_inputs()
     lowerCamelCase__    :      Tuple					 =		bert_model_tester.prepare_config_and_inputs()

     lowerCamelCase__ ,							lowerCamelCase__    :      Dict					 =		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_torch
class    lowerCAmelCase							(					__UpperCamelCase,  unittest.TestCase			):
 def      A_	(      self  :      Tuple	)			->	Union[str, Any]:
     lowerCamelCase__    :      List[str]					 =		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__    :      List[Any]					 =		13
     lowerCamelCase__    :      int					 =		floats_tensor(
         [
             batch_size,
             model.config.vision_config.num_channels,
             model.config.vision_config.image_size,
             model.config.vision_config.image_size,
         ]	)
     lowerCamelCase__    :      Optional[Any]					 =		ids_tensor([batch_size, 4]			,     model.config.text_config.vocab_size	)
     lowerCamelCase__    :      Optional[int]					 =		random_attention_mask([batch_size, 4]	)
     lowerCamelCase__    :      Optional[Any]					 =		{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

     return model, inputs
 def      A_	(      self  :      Any			,     UpperCAmelCase  :      Tuple			,     UpperCAmelCase  :      Tuple	)			->	Any:
     lowerCamelCase__    :      Any					 =		FlaxCLIPVisionModel(UpperCAmelCase	)
     lowerCamelCase__    :      Any					 =		FlaxBertModel(UpperCAmelCase	)
     return vision_model, text_model







 def      A_	(      self  :      List[Any]	)			->	List[Any]:
     lowerCamelCase__    :      Any					 =		FlaxCLIPVisionModelTester(self	)
     lowerCamelCase__    :      List[str]					 =		FlaxBertModelTester(self	)
     lowerCamelCase__    :      Optional[Any]					 =		clip_model_tester.prepare_config_and_inputs()
     lowerCamelCase__    :      int					 =		bert_model_tester.prepare_config_and_inputs()

     lowerCamelCase__ ,							lowerCamelCase__    :      Tuple					 =		vision_config_and_inputs

     lowerCamelCase__ ,							lowerCamelCase__ ,							lowerCamelCase__ ,							lowerCamelCase__    :      int					 =		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			):
 @slow
 def      A_	(      self  :      int	)			->	str:
     lowerCamelCase__    :      Tuple					 =		FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian'			,     logit_scale_init_value=1.0	)
     lowerCamelCase__    :      int					 =		VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'	)

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

     lowerCamelCase__    :      int					 =		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__    :      Optional[int]					 =		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			,     UpperCAmelCase			,     atol=1e-3	)	)











from torch import nn


def 						lowerCamelCase__    (		_A							):







	'''simple docstring'''





	if act_fn in ["swish", "silu"]:
		return nn.SiLU()
	elif act_fn == "mish":
		return nn.Mish()
	elif act_fn == "gelu":
		return nn.GELU()
	else:
		raise ValueError(f"Unsupported activation function: {act_fn}"							)
