





"""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 		__lowercase     (   snake_case_  :  str						)   ->List[Any]:



    '''simple docstring'''







    if isinstance(snake_case_				,collections.abc.Iterable						):
        return x
    return (x, x)






@require_flax
class 		__snake_case					:





 """simple docstring"""


 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




     pass

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     pass

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     pass

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




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

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase=None					,						**__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						Dict						 =     VisionTextDualEncoderConfig.from_vision_text_configs(__lowerCamelCase					,						__lowerCamelCase  )

     __A    :						List[Any]						 =     FlaxVisionTextDualEncoderModel(__lowerCamelCase  )

     __A    :						int						 =     model(input_ids=__lowerCamelCase					,						pixel_values=__lowerCamelCase					,						attention_mask=__lowerCamelCase  )

     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 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase=None					,						**__lowerCamelCase  ):



     '''simple docstring'''




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

     __A    :						Dict						 =     model(input_ids=__lowerCamelCase					,						pixel_values=__lowerCamelCase					,						attention_mask=__lowerCamelCase  )

     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 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase=None					,						**__lowerCamelCase  ):



     '''simple docstring'''




     __A ,       __A    :						List[Any]						 =     self.get_vision_text_model(__lowerCamelCase					,						__lowerCamelCase  )
     __A    :						int						 =     {'''vision_model''': vision_model, '''text_model''': text_model}
     __A    :						Tuple						 =     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__lowerCamelCase  )

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

     with tempfile.TemporaryDirectory() as tmpdirname:
         model.save_pretrained(__lowerCamelCase  )
         __A    :						Optional[int]						 =     FlaxVisionTextDualEncoderModel.from_pretrained(__lowerCamelCase  )

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

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase=None					,						**__lowerCamelCase  ):



     '''simple docstring'''




     __A ,       __A    :						Any						 =     self.get_vision_text_model(__lowerCamelCase					,						__lowerCamelCase  )
     __A    :						Optional[int]						 =     {'''vision_model''': vision_model, '''text_model''': text_model}
     __A    :						Optional[int]						 =     FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__lowerCamelCase  )

     __A    :						Any						 =     model(
         input_ids=__lowerCamelCase					,						pixel_values=__lowerCamelCase					,						attention_mask=__lowerCamelCase					,						output_attentions=__lowerCamelCase  )

     __A    :						Union[str, Any]						 =     output.vision_model_output.attentions
     self.assertEqual(len(__lowerCamelCase  )					,						vision_config.num_hidden_layers  )

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

     __A    :						str						 =     output.text_model_output.attentions
     self.assertEqual(len(__lowerCamelCase  )					,						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 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




     pt_model.to(__lowerCamelCase  )
     pt_model.eval()

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

     with torch.no_grad():
         __A    :						Optional[Any]						 =     pt_model(**__lowerCamelCase  ).to_tuple()

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

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

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

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

     pt_model_loaded.to(__lowerCamelCase  )
     pt_model_loaded.eval()

     with torch.no_grad():
         __A    :						Optional[int]						 =     pt_model_loaded(**__lowerCamelCase  ).to_tuple()

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

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						Optional[Any]						 =     VisionTextDualEncoderConfig.from_vision_text_configs(__lowerCamelCase					,						__lowerCamelCase  )

     __A    :						Optional[Any]						 =     VisionTextDualEncoderModel(__lowerCamelCase  )
     __A    :						Any						 =     FlaxVisionTextDualEncoderModel(__lowerCamelCase  )

     __A    :						int						 =     convert_pytorch_state_dict_to_flax(pt_model.state_dict()					,						__lowerCamelCase  )
     __A    :						Optional[Any]						 =     fx_state

     self.check_pt_flax_equivalence(__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase  )

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						Optional[Any]						 =     VisionTextDualEncoderConfig.from_vision_text_configs(__lowerCamelCase					,						__lowerCamelCase  )

     __A    :						Any						 =     VisionTextDualEncoderModel(__lowerCamelCase  )
     __A    :						List[Any]						 =     FlaxVisionTextDualEncoderModel(__lowerCamelCase  )

     __A    :						Tuple						 =     load_flax_weights_in_pytorch_model(__lowerCamelCase					,						fx_model.params  )

     self.check_pt_flax_equivalence(__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase  )

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						Union[str, Any]						 =     self.prepare_config_and_inputs()
     self.check_model_from_pretrained_configs(**__lowerCamelCase  )

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						Optional[Any]						 =     self.prepare_config_and_inputs()
     self.check_vision_text_dual_encoder_from_pretrained(**__lowerCamelCase  )

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						Optional[Any]						 =     self.prepare_config_and_inputs()
     self.check_save_load(**__lowerCamelCase  )

 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						List[Any]						 =     self.prepare_config_and_inputs()
     self.check_vision_text_output_attention(**__lowerCamelCase  )

 @is_pt_flax_cross_test
 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						Optional[int]						 =     self.prepare_config_and_inputs()
     __A    :						Optional[Any]						 =     config_inputs_dict.pop('''vision_config'''  )
     __A    :						Tuple						 =     config_inputs_dict.pop('''text_config'''  )

     __A    :						List[Any]						 =     config_inputs_dict

     self.check_equivalence_pt_to_flax(__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase  )
     self.check_equivalence_flax_to_pt(__lowerCamelCase					,						__lowerCamelCase					,						__lowerCamelCase  )







 @slow
 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A ,       __A    :						List[Any]						 =     self.get_pretrained_model_and_inputs()

     __A    :						str						 =     model_a(**__lowerCamelCase  )
     __A    :						Optional[int]						 =     outputs[0]

     with tempfile.TemporaryDirectory() as tmp_dirname:
         model_a.save_pretrained(__lowerCamelCase  )
         __A    :						Optional[Any]						 =     FlaxVisionTextDualEncoderModel.from_pretrained(__lowerCamelCase  )

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






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





 """simple docstring"""


 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




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

     return model, inputs

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						Dict						 =     FlaxViTModel(__lowerCamelCase  )
     __A    :						str						 =     FlaxBertModel(__lowerCamelCase  )
     return vision_model, text_model







 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




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

     __A ,       __A    :						int						 =     vision_config_and_inputs

     __A ,       __A ,       __A ,       __A    :						Tuple						 =     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					(		SCREAMING_SNAKE_CASE__							,							unittest.TestCase     ):





 """simple docstring"""


 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




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

     return model, inputs

 def 					UpperCamelCase__(    self					,						__lowerCamelCase					,						__lowerCamelCase  ):



     '''simple docstring'''




     __A    :						Union[str, Any]						 =     FlaxCLIPVisionModel(__lowerCamelCase  )
     __A    :						Dict						 =     FlaxBertModel(__lowerCamelCase  )
     return vision_model, text_model







 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						Union[str, Any]						 =     FlaxCLIPVisionModelTester(self  )
     __A    :						str						 =     FlaxBertModelTester(self  )
     __A    :						Union[str, Any]						 =     clip_model_tester.prepare_config_and_inputs()
     __A    :						Tuple						 =     bert_model_tester.prepare_config_and_inputs()

     __A ,       __A    :						Optional[int]						 =     vision_config_and_inputs

     __A ,       __A ,       __A ,       __A    :						List[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_flax
@require_vision
class 		__snake_case					(		unittest.TestCase     ):





 """simple docstring"""


 @slow
 def 					UpperCamelCase__(    self  ):



     '''simple docstring'''




     __A    :						str						 =     FlaxVisionTextDualEncoderModel.from_pretrained('''clip-italian/clip-italian'''					,						logit_scale_init_value=1.0  )
     __A    :						str						 =     VisionTextDualEncoderProcessor.from_pretrained('''clip-italian/clip-italian'''  )

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

     __A    :						Optional[Any]						 =     model(**__lowerCamelCase  )

     # 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    :						Optional[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					,						__lowerCamelCase					,						atol=1e-3  )  )











"""simple docstring"""



import logging

from transformers.configuration_utils import PretrainedConfig


a_ =			logging.getLogger(__name__)






class 		__snake_case					(		SCREAMING_SNAKE_CASE__     ):





 """simple docstring"""


 _lowerCamelCase        =     """masked_bert"""

 def __init__(    self					,						__lowerCamelCase=3_0522					,						__lowerCamelCase=768					,						__lowerCamelCase=12					,						__lowerCamelCase=12					,						__lowerCamelCase=3072					,						__lowerCamelCase="gelu"					,						__lowerCamelCase=0.1					,						__lowerCamelCase=0.1					,						__lowerCamelCase=512					,						__lowerCamelCase=2					,						__lowerCamelCase=0.0_2					,						__lowerCamelCase=1e-1_2					,						__lowerCamelCase=0					,						__lowerCamelCase="topK"					,						__lowerCamelCase="constant"					,						__lowerCamelCase=0.0					,						**__lowerCamelCase					,						):



     '''simple docstring'''




     super().__init__(pad_token_id=__lowerCamelCase					,						**__lowerCamelCase  )

     __A    :						Dict						 =     vocab_size
     __A    :						Union[str, Any]						 =     hidden_size
     __A    :						Tuple						 =     num_hidden_layers
     __A    :						Tuple						 =     num_attention_heads
     __A    :						Optional[Any]						 =     hidden_act
     __A    :						List[str]						 =     intermediate_size
     __A    :						Any						 =     hidden_dropout_prob
     __A    :						Optional[Any]						 =     attention_probs_dropout_prob
     __A    :						Any						 =     max_position_embeddings
     __A    :						str						 =     type_vocab_size
     __A    :						List[Any]						 =     initializer_range
     __A    :						str						 =     layer_norm_eps
     __A    :						Optional[int]						 =     pruning_method
     __A    :						str						 =     mask_init
     __A    :						Any						 =     mask_scale




