





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__       (  snake_case__  :Any     )      ->						Any:


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





@require_flax
class 				A_				:







       """simple docstring"""





       def    __UpperCAmelCase (    self	:	List[Any]						,__A	:	List[Any]						,__A	:	Any  )						->					str:
         pass







       def    __UpperCAmelCase (    self	:	Union[str, Any]  )						->					str:
         pass







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







       def    __UpperCAmelCase (    self	:	Dict						,__A	:	Optional[Any]						,__A	:	str						,__A	:	Optional[Any]  )						->					Tuple:
         _lowercase							= np.abs((a - b)  ).max()
         self.assertLessEqual(__A						,__A						,F"""Difference between torch and flax is {diff} (>= {tol})."""  )







       def    __UpperCAmelCase (    self	:	Dict						,__A	:	int						,__A	:	List[Any]						,__A	:	Optional[Any]						,__A	:	List[Any]						,__A	:	List[str]=None						,**__A	:	Dict  )						->					Dict:
         _lowercase							= VisionTextDualEncoderConfig.from_vision_text_configs(__A						,__A  )

         _lowercase							= FlaxVisionTextDualEncoderModel(__A  )

         _lowercase							= 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    __UpperCAmelCase (    self	:	Optional[Any]						,__A	:	Any						,__A	:	List[str]						,__A	:	Tuple						,__A	:	Optional[Any]						,__A	:	Union[str, Any]=None						,**__A	:	List[Any]  )						->					List[Any]:
         _lowercase							= self.get_vision_text_model(__A						,__A  )
         _lowercase							= {"vision_model": vision_model, "text_model": text_model}
         _lowercase							= FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__A  )

         _lowercase							= 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    __UpperCAmelCase (    self	:	int						,__A	:	List[Any]						,__A	:	List[Any]						,__A	:	Union[str, Any]						,__A	:	Optional[Any]						,__A	:	Tuple=None						,**__A	:	List[str]  )						->					Union[str, Any]:
         _lowercase							= self.get_vision_text_model(__A						,__A  )
         _lowercase							= {"vision_model": vision_model, "text_model": text_model}
         _lowercase							= FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__A  )

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

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

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







       def    __UpperCAmelCase (    self	:	Optional[Any]						,__A	:	Optional[int]						,__A	:	Optional[int]						,__A	:	Tuple						,__A	:	List[Any]						,__A	:	Optional[int]=None						,**__A	:	Optional[Any]  )						->					int:
         _lowercase							= self.get_vision_text_model(__A						,__A  )
         _lowercase							= {"vision_model": vision_model, "text_model": text_model}
         _lowercase							= FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**__A  )

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

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

         _lowercase							= 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    __UpperCAmelCase (    self	:	Union[str, Any]						,__A	:	Tuple						,__A	:	Tuple						,__A	:	str  )						->					Union[str, Any]:
         pt_model.to(__A  )
         pt_model.eval()

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

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

         _lowercase							= 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  )
           _lowercase							= FlaxVisionTextDualEncoderModel.from_pretrained(__A						,from_pt=__A  )

         _lowercase							= 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  )
           _lowercase							= VisionTextDualEncoderModel.from_pretrained(__A						,from_flax=__A  )

         pt_model_loaded.to(__A  )
         pt_model_loaded.eval()

         with torch.no_grad():
           _lowercase							= 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    __UpperCAmelCase (    self	:	int						,__A	:	Dict						,__A	:	Optional[int]						,__A	:	Any  )						->					Optional[int]:
         _lowercase							= VisionTextDualEncoderConfig.from_vision_text_configs(__A						,__A  )

         _lowercase							= VisionTextDualEncoderModel(__A  )
         _lowercase							= FlaxVisionTextDualEncoderModel(__A  )

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

         self.check_pt_flax_equivalence(__A						,__A						,__A  )







       def    __UpperCAmelCase (    self	:	Tuple						,__A	:	Dict						,__A	:	Optional[int]						,__A	:	Optional[int]  )						->					Optional[int]:
         _lowercase							= VisionTextDualEncoderConfig.from_vision_text_configs(__A						,__A  )

         _lowercase							= VisionTextDualEncoderModel(__A  )
         _lowercase							= FlaxVisionTextDualEncoderModel(__A  )

         _lowercase							= load_flax_weights_in_pytorch_model(__A						,fx_model.params  )

         self.check_pt_flax_equivalence(__A						,__A						,__A  )







       def    __UpperCAmelCase (    self	:	Optional[Any]  )						->					int:
         _lowercase							= self.prepare_config_and_inputs()
         self.check_model_from_pretrained_configs(**__A  )







       def    __UpperCAmelCase (    self	:	int  )						->					List[Any]:
         _lowercase							= self.prepare_config_and_inputs()
         self.check_vision_text_dual_encoder_from_pretrained(**__A  )







       def    __UpperCAmelCase (    self	:	Optional[int]  )						->					List[str]:
         _lowercase							= self.prepare_config_and_inputs()
         self.check_save_load(**__A  )







       def    __UpperCAmelCase (    self	:	Union[str, Any]  )						->					Optional[int]:
         _lowercase							= self.prepare_config_and_inputs()
         self.check_vision_text_output_attention(**__A  )







       @is_pt_flax_cross_test
       def    __UpperCAmelCase (    self	:	Union[str, Any]  )						->					int:
         _lowercase							= self.prepare_config_and_inputs()
         _lowercase							= config_inputs_dict.pop('vision_config'  )
         _lowercase							= config_inputs_dict.pop('text_config'  )

         _lowercase							= config_inputs_dict

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







       @slow
       def    __UpperCAmelCase (    self	:	Tuple  )						->					Optional[int]:
         _lowercase							= self.get_pretrained_model_and_inputs()

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

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

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





@require_flax
class 				A_				(      _A					,	unittest.TestCase	):







       """simple docstring"""





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

         return model, inputs







       def    __UpperCAmelCase (    self	:	int						,__A	:	Union[str, Any]						,__A	:	int  )						->					List[str]:
         _lowercase							= FlaxViTModel(__A  )
         _lowercase							= FlaxBertModel(__A  )
         return vision_model, text_model







       def    __UpperCAmelCase (    self	:	Union[str, Any]  )						->					List[Any]:
         _lowercase							= FlaxViTModelTester(self  )
         _lowercase							= FlaxBertModelTester(self  )
         _lowercase							= vit_model_tester.prepare_config_and_inputs()
         _lowercase							= bert_model_tester.prepare_config_and_inputs()

         _lowercase							= vision_config_and_inputs

         _lowercase							= 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 				A_				(      _A					,	unittest.TestCase	):







       """simple docstring"""





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

         return model, inputs







       def    __UpperCAmelCase (    self	:	Optional[Any]						,__A	:	List[Any]						,__A	:	Tuple  )						->					int:
         _lowercase							= FlaxCLIPVisionModel(__A  )
         _lowercase							= FlaxBertModel(__A  )
         return vision_model, text_model







       def    __UpperCAmelCase (    self	:	str  )						->					List[Any]:
         _lowercase							= FlaxCLIPVisionModelTester(self  )
         _lowercase							= FlaxBertModelTester(self  )
         _lowercase							= clip_model_tester.prepare_config_and_inputs()
         _lowercase							= bert_model_tester.prepare_config_and_inputs()

         _lowercase							= vision_config_and_inputs

         _lowercase							= 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 				A_				(      unittest.TestCase	):







       """simple docstring"""





       @slow
       def    __UpperCAmelCase (    self	:	Union[str, Any]  )						->					Dict:
         _lowercase							= FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian'						,logit_scale_init_value=1.0  )
         _lowercase							= VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'  )

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

         _lowercase							= 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])						,)

         _lowercase							= np.array([[1.2284727, 0.3104122]]  )

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









import unittest

import numpy as np

from transformers import RobertaPreLayerNormConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask


if is_flax_available():
      import jax.numpy as jnp

      from transformers.models.roberta_prelayernorm.modeling_flax_roberta_prelayernorm import (
          FlaxRobertaPreLayerNormForCausalLM,
          FlaxRobertaPreLayerNormForMaskedLM,
          FlaxRobertaPreLayerNormForMultipleChoice,
          FlaxRobertaPreLayerNormForQuestionAnswering,
          FlaxRobertaPreLayerNormForSequenceClassification,
          FlaxRobertaPreLayerNormForTokenClassification,
          FlaxRobertaPreLayerNormModel,
      )





class 				A_				(      unittest.TestCase	):







       """simple docstring"""





       def __init__(    self	:	List[Any]						,__A	:	int						,__A	:	str=13						,__A	:	str=7						,__A	:	Optional[Any]=True						,__A	:	Optional[int]=True						,__A	:	int=True						,__A	:	List[str]=True						,__A	:	Dict=99						,__A	:	Dict=32						,__A	:	Dict=5						,__A	:	Dict=4						,__A	:	int=37						,__A	:	Any="gelu"						,__A	:	int=0.1						,__A	:	int=0.1						,__A	:	Dict=512						,__A	:	List[str]=16						,__A	:	Tuple=2						,__A	:	Dict=0.02						,__A	:	int=4						,)						->					Optional[int]:
         _lowercase							= parent
         _lowercase							= batch_size
         _lowercase							= seq_length
         _lowercase							= is_training
         _lowercase							= use_attention_mask
         _lowercase							= use_token_type_ids
         _lowercase							= use_labels
         _lowercase							= vocab_size
         _lowercase							= hidden_size
         _lowercase							= num_hidden_layers
         _lowercase							= num_attention_heads
         _lowercase							= intermediate_size
         _lowercase							= hidden_act
         _lowercase							= hidden_dropout_prob
         _lowercase							= attention_probs_dropout_prob
         _lowercase							= max_position_embeddings
         _lowercase							= type_vocab_size
         _lowercase							= type_sequence_label_size
         _lowercase							= initializer_range
         _lowercase							= num_choices







       def    __UpperCAmelCase (    self	:	int  )						->					str:
         _lowercase							= ids_tensor([self.batch_size, self.seq_length]						,self.vocab_size  )

         _lowercase							= None
         if self.use_attention_mask:
           _lowercase							= random_attention_mask([self.batch_size, self.seq_length]  )

         _lowercase							= None
         if self.use_token_type_ids:
           _lowercase							= ids_tensor([self.batch_size, self.seq_length]						,self.type_vocab_size  )

         _lowercase							= RobertaPreLayerNormConfig(
             vocab_size=self.vocab_size						,hidden_size=self.hidden_size						,num_hidden_layers=self.num_hidden_layers						,num_attention_heads=self.num_attention_heads						,intermediate_size=self.intermediate_size						,hidden_act=self.hidden_act						,hidden_dropout_prob=self.hidden_dropout_prob						,attention_probs_dropout_prob=self.attention_probs_dropout_prob						,max_position_embeddings=self.max_position_embeddings						,type_vocab_size=self.type_vocab_size						,is_decoder=__A						,initializer_range=self.initializer_range						,)

         return config, input_ids, token_type_ids, attention_mask







       def    __UpperCAmelCase (    self	:	Optional[int]  )						->					Tuple:
         _lowercase							= self.prepare_config_and_inputs()
         _lowercase						,		_lowercase						,		_lowercase						,		_lowercase							= config_and_inputs
         _lowercase							= {'input_ids': input_ids, 'token_type_ids': token_type_ids, 'attention_mask': attention_mask}
         return config, inputs_dict







       def    __UpperCAmelCase (    self	:	Tuple  )						->					List[Any]:
         _lowercase							= self.prepare_config_and_inputs()
         _lowercase						,		_lowercase						,		_lowercase						,		_lowercase							= config_and_inputs

         _lowercase							= True
         _lowercase							= floats_tensor([self.batch_size, self.seq_length, self.hidden_size]  )
         _lowercase							= ids_tensor([self.batch_size, self.seq_length]						,vocab_size=2  )

         return (
             config,
             input_ids,
             token_type_ids,
             encoder_hidden_states,
             encoder_attention_mask,
         )





@require_flax
# Copied from tests.models.roberta.test_modelling_flax_roberta.FlaxRobertaPreLayerNormModelTest with ROBERTA->ROBERTA_PRELAYERNORM,Roberta->RobertaPreLayerNorm,roberta-base->andreasmadsen/efficient_mlm_m0.40
class 				A_				(      UpperCAmelCase					,	unittest.TestCase	):







       """simple docstring"""





       SCREAMING_SNAKE_CASE_      : Optional[int]      =  True

       SCREAMING_SNAKE_CASE_      : Dict      =  (
           (
               FlaxRobertaPreLayerNormModel,
               FlaxRobertaPreLayerNormForCausalLM,
               FlaxRobertaPreLayerNormForMaskedLM,
               FlaxRobertaPreLayerNormForSequenceClassification,
               FlaxRobertaPreLayerNormForTokenClassification,
               FlaxRobertaPreLayerNormForMultipleChoice,
               FlaxRobertaPreLayerNormForQuestionAnswering,
           )
           if is_flax_available()
           else ()
       )







       def    __UpperCAmelCase (    self	:	List[Any]  )						->					Any:
         _lowercase							= FlaxRobertaPreLayerNormModelTester(self  )







       @slow
       def    __UpperCAmelCase (    self	:	Dict  )						->					Dict:
         for model_class_name in self.all_model_classes:
           _lowercase							= model_class_name.from_pretrained('andreasmadsen/efficient_mlm_m0.40'						,from_pt=__A  )
           _lowercase							= model(np.ones((1, 1)  )  )
           self.assertIsNotNone(__A  )





@require_flax
class 				A_				(      unittest.TestCase	):







       """simple docstring"""





       @slow
       def    __UpperCAmelCase (    self	:	int  )						->					Optional[Any]:
         _lowercase							= FlaxRobertaPreLayerNormForMaskedLM.from_pretrained('andreasmadsen/efficient_mlm_m0.40'						,from_pt=__A  )

         _lowercase							= np.array([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]]						,dtype=jnp.intaa  )
         _lowercase							= model(__A  )[0]
         _lowercase							= [1, 11, 5_0265]
         self.assertEqual(list(output.shape  )						,__A  )
         # compare the actual values for a slice.
         _lowercase							= np.array(
             [[[40.4880, 18.0199, -5.2367], [-1.8877, -4.0885, 10.7085], [-2.2613, -5.6110, 7.2665]]]						,dtype=np.floataa  )
         self.assertTrue(np.allclose(output[:, :3, :3]						,__A						,atol=1e-4  )  )







       @slow
       def    __UpperCAmelCase (    self	:	Union[str, Any]  )						->					List[Any]:
         _lowercase							= FlaxRobertaPreLayerNormModel.from_pretrained('andreasmadsen/efficient_mlm_m0.40'						,from_pt=__A  )

         _lowercase							= np.array([[0, 3_1414, 232, 328, 740, 1140, 1_2695, 69, 4_6078, 1588, 2]]						,dtype=jnp.intaa  )
         _lowercase							= model(__A  )[0]
         # compare the actual values for a slice.
         _lowercase							= np.array(
             [[[0.0208, -0.0356, 0.0237], [-0.1569, -0.0411, -0.2626], [0.1879, 0.0125, -0.0089]]]						,dtype=np.floataa  )
         self.assertTrue(np.allclose(output[:, :3, :3]						,__A						,atol=1e-4  )  )