


import argparse

import tensorflow as tf
import torch

from transformers import BertConfig, BertForMaskedLM
from transformers.models.bert.modeling_bert import (
    BertIntermediate,
    BertLayer,
    BertOutput,
    BertPooler,
    BertSelfAttention,
    BertSelfOutput,
)
from transformers.utils import logging


logging.set_verbosity_info()



def 				UpperCamelCase_(      lowerCamelCase_							, lowerCamelCase_							, lowerCamelCase_ )    ->						Dict:
    def get_masked_lm_array(lowerCamelCase_ ):
        _lowercase       :							str      		=		F'''masked_lm/{name}/.ATTRIBUTES/VARIABLE_VALUE'''
        _lowercase       :							Dict      		=		tf.train.load_variable(lowerCamelCase_							, lowerCamelCase_ )

        if "kernel" in name:
            _lowercase       :							Any      		=		array.transpose()

        return torch.from_numpy(lowerCamelCase_ )

    def get_encoder_array(lowerCamelCase_ ):
        _lowercase       :							Dict      		=		F'''encoder/{name}/.ATTRIBUTES/VARIABLE_VALUE'''
        _lowercase       :							Union[str, Any]      		=		tf.train.load_variable(lowerCamelCase_							, lowerCamelCase_ )

        if "kernel" in name:
            _lowercase       :							Optional[Any]      		=		array.transpose()

        return torch.from_numpy(lowerCamelCase_ )

    def get_encoder_layer_array(lowerCamelCase_							, lowerCamelCase_ ):
        _lowercase       :							Optional[Any]      		=		F'''encoder/_transformer_layers/{layer_index}/{name}/.ATTRIBUTES/VARIABLE_VALUE'''
        _lowercase       :							Optional[int]      		=		tf.train.load_variable(lowerCamelCase_							, lowerCamelCase_ )

        if "kernel" in name:
            _lowercase       :							Union[str, Any]      		=		array.transpose()

        return torch.from_numpy(lowerCamelCase_ )

    def get_encoder_attention_layer_array(lowerCamelCase_							, lowerCamelCase_							, lowerCamelCase_ ):
        _lowercase       :							List[str]      		=		F'''encoder/_transformer_layers/{layer_index}/_attention_layer/{name}/.ATTRIBUTES/VARIABLE_VALUE'''
        _lowercase       :							Tuple      		=		tf.train.load_variable(lowerCamelCase_							, lowerCamelCase_ )
        _lowercase       :							Union[str, Any]      		=		array.reshape(lowerCamelCase_ )

        if "kernel" in name:
            _lowercase       :							Tuple      		=		array.transpose()

        return torch.from_numpy(lowerCamelCase_ )

    print(F'''Loading model based on config from {config_path}...''' )
    _lowercase       :							List[Any]      		=		BertConfig.from_json_file(lowerCamelCase_ )
    _lowercase       :							Optional[Any]      		=		BertForMaskedLM(lowerCamelCase_ )

    # Layers
    for layer_index in range(0							, config.num_hidden_layers ):
        _lowercase       :							BertLayer      		=		model.bert.encoder.layer[layer_index]

        # Self-attention
        _lowercase       :							BertSelfAttention      		=		layer.attention.self

        _lowercase       :							Optional[Any]      		=		get_encoder_attention_layer_array(
            lowerCamelCase_							, '_query_dense/kernel'							, self_attn.query.weight.data.shape )
        _lowercase       :							Any      		=		get_encoder_attention_layer_array(
            lowerCamelCase_							, '_query_dense/bias'							, self_attn.query.bias.data.shape )
        _lowercase       :							Tuple      		=		get_encoder_attention_layer_array(
            lowerCamelCase_							, '_key_dense/kernel'							, self_attn.key.weight.data.shape )
        _lowercase       :							Tuple      		=		get_encoder_attention_layer_array(
            lowerCamelCase_							, '_key_dense/bias'							, self_attn.key.bias.data.shape )
        _lowercase       :							str      		=		get_encoder_attention_layer_array(
            lowerCamelCase_							, '_value_dense/kernel'							, self_attn.value.weight.data.shape )
        _lowercase       :							Optional[int]      		=		get_encoder_attention_layer_array(
            lowerCamelCase_							, '_value_dense/bias'							, self_attn.value.bias.data.shape )

        # Self-attention Output
        _lowercase       :							BertSelfOutput      		=		layer.attention.output

        _lowercase       :							Tuple      		=		get_encoder_attention_layer_array(
            lowerCamelCase_							, '_output_dense/kernel'							, self_output.dense.weight.data.shape )
        _lowercase       :							List[Any]      		=		get_encoder_attention_layer_array(
            lowerCamelCase_							, '_output_dense/bias'							, self_output.dense.bias.data.shape )

        _lowercase       :							Optional[int]      		=		get_encoder_layer_array(lowerCamelCase_							, '_attention_layer_norm/gamma' )
        _lowercase       :							Union[str, Any]      		=		get_encoder_layer_array(lowerCamelCase_							, '_attention_layer_norm/beta' )

        # Intermediate
        _lowercase       :							BertIntermediate      		=		layer.intermediate

        _lowercase       :							List[str]      		=		get_encoder_layer_array(lowerCamelCase_							, '_intermediate_dense/kernel' )
        _lowercase       :							List[str]      		=		get_encoder_layer_array(lowerCamelCase_							, '_intermediate_dense/bias' )

        # Output
        _lowercase       :							BertOutput      		=		layer.output

        _lowercase       :							List[Any]      		=		get_encoder_layer_array(lowerCamelCase_							, '_output_dense/kernel' )
        _lowercase       :							Tuple      		=		get_encoder_layer_array(lowerCamelCase_							, '_output_dense/bias' )

        _lowercase       :							Optional[Any]      		=		get_encoder_layer_array(lowerCamelCase_							, '_output_layer_norm/gamma' )
        _lowercase       :							Tuple      		=		get_encoder_layer_array(lowerCamelCase_							, '_output_layer_norm/beta' )

    # Embeddings
    _lowercase       :							Union[str, Any]      		=		get_encoder_array('_position_embedding_layer/embeddings' )
    _lowercase       :							Any      		=		get_encoder_array('_type_embedding_layer/embeddings' )
    _lowercase       :							str      		=		get_encoder_array('_embedding_norm_layer/gamma' )
    _lowercase       :							List[str]      		=		get_encoder_array('_embedding_norm_layer/beta' )

    # LM Head
    _lowercase       :							Any      		=		model.cls.predictions.transform

    _lowercase       :							Dict      		=		get_masked_lm_array('dense/kernel' )
    _lowercase       :							List[Any]      		=		get_masked_lm_array('dense/bias' )

    _lowercase       :							str      		=		get_masked_lm_array('layer_norm/gamma' )
    _lowercase       :							str      		=		get_masked_lm_array('layer_norm/beta' )

    _lowercase       :							Union[str, Any]      		=		get_masked_lm_array('embedding_table' )

    # Pooling
    _lowercase       :							List[Any]      		=		BertPooler(config=lowerCamelCase_ )
    _lowercase       :							BertPooler      		=		get_encoder_array('_pooler_layer/kernel' )
    _lowercase       :							BertPooler      		=		get_encoder_array('_pooler_layer/bias' )

    # Export final model
    model.save_pretrained(lowerCamelCase_ )

    # Integration test - should load without any errors ;)
    _lowercase       :							Dict      		=		BertForMaskedLM.from_pretrained(lowerCamelCase_ )
    print(new_model.eval() )

    print('Model conversion was done sucessfully!' )


if __name__ == "__main__":
 SCREAMING_SNAKE_CASE       :      Union[str, Any]												= argparse.ArgumentParser()
 parser.add_argument(
     "--tf_checkpoint_path", type=str, required=True, help="Path to the TensorFlow Token Dropping checkpoint path."
 )
 parser.add_argument(
     "--bert_config_file",
     type=str,
     required=True,
     help="The config json file corresponding to the BERT model. This specifies the model architecture.",
 )
 parser.add_argument(
     "--pytorch_dump_path",
     type=str,
     required=True,
     help="Path to the output PyTorch model.",
 )
 SCREAMING_SNAKE_CASE       :      str												= parser.parse_args()
 convert_checkpoint_to_pytorch(args.tf_checkpoint_path, args.bert_config_file, args.pytorch_dump_path)






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 				UpperCamelCase_(      lowerCamelCase_ )    ->						Optional[int]:
    if isinstance(lowerCamelCase_							, collections.abc.Iterable ):
        return x
    return (x, x)






@require_flax
class _lowerCamelCase:
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase)       ->   Union[str, Any]:




           """simple docstring"""

           pass
       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

           pass
       def 			UpperCamelCase     (					self)       ->   Optional[int]:




           """simple docstring"""

           pass
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase)       ->   Any:




           """simple docstring"""

           _lowercase       :							str      		=		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)       ->   Union[str, Any]:




           """simple docstring"""

           _lowercase       :							Any      		=		VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase,      lowerCamelCase)

           _lowercase       :							Optional[int]      		=		FlaxVisionTextDualEncoderModel(lowerCamelCase)

           _lowercase       :							Any      		=		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)       ->   Any:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Union[str, Any]      		=		self.get_vision_text_model(lowerCamelCase,      lowerCamelCase)
           _lowercase       :							str      		=		{'vision_model': vision_model, 'text_model': text_model}
           _lowercase       :							Dict      		=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase)

           _lowercase       :							List[str]      		=		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)       ->   Union[str, Any]:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Tuple      		=		self.get_vision_text_model(lowerCamelCase,      lowerCamelCase)
           _lowercase       :							List[str]      		=		{'vision_model': vision_model, 'text_model': text_model}
           _lowercase       :							Dict      		=		FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**lowerCamelCase)

           _lowercase       :							List[str]      		=		model(input_ids=lowerCamelCase,      pixel_values=lowerCamelCase,      attention_mask=lowerCamelCase)
           _lowercase       :							Tuple      		=		output[0]

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

               _lowercase       :							Tuple      		=		model(input_ids=lowerCamelCase,      pixel_values=lowerCamelCase,      attention_mask=lowerCamelCase)
               _lowercase       :							str      		=		after_output[0]
               _lowercase       :							Optional[Any]      		=		np.amax(np.abs(out_a - out_a))
               self.assertLessEqual(lowerCamelCase,      1E-3)
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase=None,      **lowerCamelCase)       ->   str:




           """simple docstring"""

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

           _lowercase       :							Tuple      		=		model(
               input_ids=lowerCamelCase,      pixel_values=lowerCamelCase,      attention_mask=lowerCamelCase,      output_attentions=lowerCamelCase)

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

           _lowercase       :							List[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)       ->   Optional[int]:




           """simple docstring"""

           pt_model.to(lowerCamelCase)
           pt_model.eval()

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

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

           _lowercase       :							Any      		=		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)
               _lowercase       :							int      		=		FlaxVisionTextDualEncoderModel.from_pretrained(lowerCamelCase,      from_pt=lowerCamelCase)

           _lowercase       :							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)
               _lowercase       :							List[Any]      		=		VisionTextDualEncoderModel.from_pretrained(lowerCamelCase,      from_flax=lowerCamelCase)

           pt_model_loaded.to(lowerCamelCase)
           pt_model_loaded.eval()

           with torch.no_grad():
               _lowercase       :							Optional[Any]      		=		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)       ->   Tuple:




           """simple docstring"""

           _lowercase       :							Dict      		=		VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase,      lowerCamelCase)

           _lowercase       :							Optional[Any]      		=		VisionTextDualEncoderModel(lowerCamelCase)
           _lowercase       :							str      		=		FlaxVisionTextDualEncoderModel(lowerCamelCase)

           _lowercase       :							Tuple      		=		convert_pytorch_state_dict_to_flax(pt_model.state_dict(),      lowerCamelCase)
           _lowercase       :							List[Any]      		=		fx_state

           self.check_pt_flax_equivalence(lowerCamelCase,      lowerCamelCase,      lowerCamelCase)
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase,      lowerCamelCase)       ->   Dict:




           """simple docstring"""

           _lowercase       :							str      		=		VisionTextDualEncoderConfig.from_vision_text_configs(lowerCamelCase,      lowerCamelCase)

           _lowercase       :							Tuple      		=		VisionTextDualEncoderModel(lowerCamelCase)
           _lowercase       :							Optional[int]      		=		FlaxVisionTextDualEncoderModel(lowerCamelCase)

           _lowercase       :							List[str]      		=		load_flax_weights_in_pytorch_model(lowerCamelCase,      fx_model.params)

           self.check_pt_flax_equivalence(lowerCamelCase,      lowerCamelCase,      lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   List[Any]:




           """simple docstring"""

           _lowercase       :							int      		=		self.prepare_config_and_inputs()
           self.check_model_from_pretrained_configs(**lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   Tuple:




           """simple docstring"""

           _lowercase       :							List[str]      		=		self.prepare_config_and_inputs()
           self.check_vision_text_dual_encoder_from_pretrained(**lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   Union[str, Any]:




           """simple docstring"""

           _lowercase       :							Optional[int]      		=		self.prepare_config_and_inputs()
           self.check_save_load(**lowerCamelCase)
       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

           _lowercase       :							str      		=		self.prepare_config_and_inputs()
           self.check_vision_text_output_attention(**lowerCamelCase)
       @is_pt_flax_cross_test
       def 			UpperCamelCase     (					self)       ->   Tuple:




           """simple docstring"""

           _lowercase       :							List[Any]      		=		self.prepare_config_and_inputs()
           _lowercase       :							List[str]      		=		config_inputs_dict.pop('vision_config')
           _lowercase       :							str      		=		config_inputs_dict.pop('text_config')

           _lowercase       :							int      		=		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)       ->   List[str]:




           """simple docstring"""

           _lowercase		,				_lowercase       :							Optional[Any]      		=		self.get_pretrained_model_and_inputs()

           _lowercase       :							Optional[int]      		=		model_a(**lowerCamelCase)
           _lowercase       :							Tuple      		=		outputs[0]

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

               _lowercase       :							List[Any]      		=		model_a(**lowerCamelCase)
               _lowercase       :							Tuple      		=		after_outputs[0]
               _lowercase       :							Dict      		=		np.amax(np.abs(out_a - out_a))
               self.assertLessEqual(lowerCamelCase,      1E-5)






@require_flax
class _lowerCamelCase(						_a, unittest.TestCase   ):
       def 			UpperCamelCase     (					self)       ->   List[str]:




           """simple docstring"""

           _lowercase       :							Union[str, 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,      )
           _lowercase       :							List[Any]      		=		13
           _lowercase       :							str      		=		floats_tensor(
               [
                   batch_size,
                   model.config.vision_config.num_channels,
                   model.config.vision_config.image_size,
                   model.config.vision_config.image_size,
               ])
           _lowercase       :							Tuple      		=		ids_tensor([batch_size, 4],      model.config.text_config.vocab_size)
           _lowercase       :							Union[str, Any]      		=		random_attention_mask([batch_size, 4])
           _lowercase       :							int      		=		{'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

           return model, inputs
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase)       ->   Any:




           """simple docstring"""

           _lowercase       :							List[Any]      		=		FlaxViTModel(lowerCamelCase)
           _lowercase       :							Optional[Any]      		=		FlaxBertModel(lowerCamelCase)
           return vision_model, text_model




       def 			UpperCamelCase     (					self)       ->   str:




           """simple docstring"""

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

           _lowercase		,				_lowercase       :							List[str]      		=		vision_config_and_inputs

           _lowercase		,				_lowercase		,				_lowercase		,				_lowercase       :							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 _lowerCamelCase(						_a, unittest.TestCase   ):
       def 			UpperCamelCase     (					self)       ->   Tuple:




           """simple docstring"""

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

           return model, inputs
       def 			UpperCamelCase     (					self,      lowerCamelCase,      lowerCamelCase)       ->   Optional[int]:




           """simple docstring"""

           _lowercase       :							Any      		=		FlaxCLIPVisionModel(lowerCamelCase)
           _lowercase       :							Optional[Any]      		=		FlaxBertModel(lowerCamelCase)
           return vision_model, text_model




       def 			UpperCamelCase     (					self)       ->   Dict:




           """simple docstring"""

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

           _lowercase		,				_lowercase       :							Dict      		=		vision_config_and_inputs

           _lowercase		,				_lowercase		,				_lowercase		,				_lowercase       :							Optional[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 			UpperCamelCase     (					self)       ->   Optional[int]:




           """simple docstring"""

           _lowercase       :							List[str]      		=		FlaxVisionTextDualEncoderModel.from_pretrained('clip-italian/clip-italian',      logit_scale_init_value=1.0)
           _lowercase       :							List[str]      		=		VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian')

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

           _lowercase       :							List[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]),      )

           _lowercase       :							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,      lowerCamelCase,      atol=1E-3))


