

import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import (
    is_pt_flax_cross_test,
    require_flax,
    require_torch,
    require_vision,
    slow,
    torch_device,
)
from transformers.utils import is_flax_available, is_torch_available, is_vision_available

from ...test_modeling_flax_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_flax_bert import FlaxBertModelTester
from ..clip.test_modeling_flax_clip import FlaxCLIPVisionModelTester
from ..vit.test_modeling_flax_vit import FlaxViTModelTester


if is_flax_available():
						from transformers import (
						    FlaxBertModel,
						    FlaxCLIPVisionModel,
						    FlaxVisionTextDualEncoderModel,
						    FlaxViTModel,
						    VisionTextDualEncoderConfig,
						    VisionTextDualEncoderProcessor,
						)
						from transformers.modeling_flax_pytorch_utils import (
						    convert_pytorch_state_dict_to_flax,
						    load_flax_weights_in_pytorch_model,
						)


if is_torch_available():
						import torch

						from transformers import VisionTextDualEncoderModel

if is_vision_available():
						from PIL import Image







def 			A_      (    _UpperCAmelCase    ):
						if isinstance(lowercase_				,	collections.abc.Iterable    ):
												return x
						return (x, x)



@require_flax
class   __lowercase				:




			"""simple docstring"""







			def        _SCREAMING_SNAKE_CASE			( self  :     Any   ,						lowerCAmelCase__  :     Dict   ,						lowerCAmelCase__  :     List[str]):
									pass



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]):
									pass



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									pass



			def        _SCREAMING_SNAKE_CASE			( self  :     Any   ,						lowerCAmelCase__  :     str   ,						lowerCAmelCase__  :     Union[str, Any]   ,						lowerCAmelCase__  :     Optional[int]):
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       np.abs((a - b)).max()
									self.assertLessEqual(A__   ,						A__   ,						F"Difference between torch and flax is {diff} (>= {tol}).")



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]   ,						lowerCAmelCase__  :     List[Any]   ,						lowerCAmelCase__  :     Optional[int]   ,						lowerCAmelCase__  :     Optional[Any]   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     Union[str, Any]=None   ,						**lowerCAmelCase__  :     Dict):
									SCREAMING_SNAKE_CASE_: List[str]  		=       VisionTextDualEncoderConfig.from_vision_text_configs(A__   ,						A__)

									SCREAMING_SNAKE_CASE_: Optional[int]  		=       FlaxVisionTextDualEncoderModel(A__)

									SCREAMING_SNAKE_CASE_: List[str]  		=       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        _SCREAMING_SNAKE_CASE			( self  :     Dict   ,						lowerCAmelCase__  :     Optional[int]   ,						lowerCAmelCase__  :     Dict   ,						lowerCAmelCase__  :     Union[str, Any]   ,						lowerCAmelCase__  :     List[str]   ,						lowerCAmelCase__  :     Optional[int]=None   ,						**lowerCAmelCase__  :     Optional[Any]):
									SCREAMING_SNAKE_CASE_: int  		=       self.get_vision_text_model(A__   ,						A__)
									SCREAMING_SNAKE_CASE_: List[str]  		=       {"""vision_model""": vision_model, """text_model""": text_model}
									SCREAMING_SNAKE_CASE_: str  		=       FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**A__)

									SCREAMING_SNAKE_CASE_: str  		=       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        _SCREAMING_SNAKE_CASE			( self  :     int   ,						lowerCAmelCase__  :     str   ,						lowerCAmelCase__  :     Optional[Any]   ,						lowerCAmelCase__  :     Optional[int]   ,						lowerCAmelCase__  :     Optional[Any]   ,						lowerCAmelCase__  :     str=None   ,						**lowerCAmelCase__  :     Optional[int]):
									SCREAMING_SNAKE_CASE_: List[str]  		=       self.get_vision_text_model(A__   ,						A__)
									SCREAMING_SNAKE_CASE_: Any  		=       {"""vision_model""": vision_model, """text_model""": text_model}
									SCREAMING_SNAKE_CASE_: Dict  		=       FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**A__)

									SCREAMING_SNAKE_CASE_: List[Any]  		=       model(input_ids=A__   ,						pixel_values=A__   ,						attention_mask=A__)
									SCREAMING_SNAKE_CASE_: List[Any]  		=       output[0]

									with tempfile.TemporaryDirectory() as tmpdirname:
															model.save_pretrained(A__)
															SCREAMING_SNAKE_CASE_: Dict  		=       FlaxVisionTextDualEncoderModel.from_pretrained(A__)

															SCREAMING_SNAKE_CASE_: List[str]  		=       model(input_ids=A__   ,						pixel_values=A__   ,						attention_mask=A__)
															SCREAMING_SNAKE_CASE_: Dict  		=       after_output[0]
															SCREAMING_SNAKE_CASE_: Optional[int]  		=       np.amax(np.abs(out_a - out_a))
															self.assertLessEqual(A__   ,						1E-3)



			def        _SCREAMING_SNAKE_CASE			( self  :     List[str]   ,						lowerCAmelCase__  :     str   ,						lowerCAmelCase__  :     List[Any]   ,						lowerCAmelCase__  :     Dict   ,						lowerCAmelCase__  :     Tuple   ,						lowerCAmelCase__  :     List[str]=None   ,						**lowerCAmelCase__  :     Optional[int]):
									SCREAMING_SNAKE_CASE_: Dict  		=       self.get_vision_text_model(A__   ,						A__)
									SCREAMING_SNAKE_CASE_: List[str]  		=       {"""vision_model""": vision_model, """text_model""": text_model}
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(**A__)

									SCREAMING_SNAKE_CASE_: Optional[int]  		=       model(
									    input_ids=A__   ,						pixel_values=A__   ,						attention_mask=A__   ,						output_attentions=A__)

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

									SCREAMING_SNAKE_CASE_: str  		=       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        _SCREAMING_SNAKE_CASE			( self  :     str   ,						lowerCAmelCase__  :     Union[str, Any]   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     str):
									pt_model.to(A__)
									pt_model.eval()

									# prepare inputs
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       inputs_dict
									SCREAMING_SNAKE_CASE_: Dict  		=       {k: torch.tensor(v.tolist()) for k, v in flax_inputs.items()}

									with torch.no_grad():
															SCREAMING_SNAKE_CASE_: Tuple  		=       pt_model(**A__).to_tuple()

									SCREAMING_SNAKE_CASE_: str  		=       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__)
															SCREAMING_SNAKE_CASE_: Any  		=       FlaxVisionTextDualEncoderModel.from_pretrained(A__   ,						from_pt=A__)

									SCREAMING_SNAKE_CASE_: List[str]  		=       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__)
															SCREAMING_SNAKE_CASE_: List[str]  		=       VisionTextDualEncoderModel.from_pretrained(A__   ,						from_flax=A__)

									pt_model_loaded.to(A__)
									pt_model_loaded.eval()

									with torch.no_grad():
															SCREAMING_SNAKE_CASE_: int  		=       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        _SCREAMING_SNAKE_CASE			( self  :     str   ,						lowerCAmelCase__  :     List[Any]   ,						lowerCAmelCase__  :     Tuple   ,						lowerCAmelCase__  :     Dict):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       VisionTextDualEncoderConfig.from_vision_text_configs(A__   ,						A__)

									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       VisionTextDualEncoderModel(A__)
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       FlaxVisionTextDualEncoderModel(A__)

									SCREAMING_SNAKE_CASE_: List[str]  		=       convert_pytorch_state_dict_to_flax(pt_model.state_dict()   ,						A__)
									SCREAMING_SNAKE_CASE_: List[str]  		=       fx_state

									self.check_pt_flax_equivalence(A__   ,						A__   ,						A__)



			def        _SCREAMING_SNAKE_CASE			( self  :     Dict   ,						lowerCAmelCase__  :     Tuple   ,						lowerCAmelCase__  :     Optional[int]   ,						lowerCAmelCase__  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       VisionTextDualEncoderConfig.from_vision_text_configs(A__   ,						A__)

									SCREAMING_SNAKE_CASE_: Dict  		=       VisionTextDualEncoderModel(A__)
									SCREAMING_SNAKE_CASE_: Dict  		=       FlaxVisionTextDualEncoderModel(A__)

									SCREAMING_SNAKE_CASE_: str  		=       load_flax_weights_in_pytorch_model(A__   ,						fx_model.params)

									self.check_pt_flax_equivalence(A__   ,						A__   ,						A__)



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]):
									SCREAMING_SNAKE_CASE_: int  		=       self.prepare_config_and_inputs()
									self.check_model_from_pretrained_configs(**A__)



			def        _SCREAMING_SNAKE_CASE			( self  :     List[str]):
									SCREAMING_SNAKE_CASE_: Any  		=       self.prepare_config_and_inputs()
									self.check_vision_text_dual_encoder_from_pretrained(**A__)



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: List[Any]  		=       self.prepare_config_and_inputs()
									self.check_save_load(**A__)



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]):
									SCREAMING_SNAKE_CASE_: int  		=       self.prepare_config_and_inputs()
									self.check_vision_text_output_attention(**A__)



			@is_pt_flax_cross_test
			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]):
									SCREAMING_SNAKE_CASE_: Dict  		=       self.prepare_config_and_inputs()
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       config_inputs_dict.pop("vision_config")
									SCREAMING_SNAKE_CASE_: Dict  		=       config_inputs_dict.pop("text_config")

									SCREAMING_SNAKE_CASE_: Any  		=       config_inputs_dict

									self.check_equivalence_pt_to_flax(A__   ,						A__   ,						A__)
									self.check_equivalence_flax_to_pt(A__   ,						A__   ,						A__)




			@slow
			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]):
									SCREAMING_SNAKE_CASE_: str  		=       self.get_pretrained_model_and_inputs()

									SCREAMING_SNAKE_CASE_: List[str]  		=       model_a(**A__)
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       outputs[0]

									with tempfile.TemporaryDirectory() as tmp_dirname:
															model_a.save_pretrained(A__)
															SCREAMING_SNAKE_CASE_: Tuple  		=       FlaxVisionTextDualEncoderModel.from_pretrained(A__)

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







@require_flax
class   __lowercase				( UpperCAmelCase_		,       unittest.TestCase	):




			"""simple docstring"""







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

									return model, inputs



			def        _SCREAMING_SNAKE_CASE			( self  :     Dict   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     Optional[int]):
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       FlaxViTModel(A__)
									SCREAMING_SNAKE_CASE_: List[str]  		=       FlaxBertModel(A__)
									return vision_model, text_model




			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]):
									SCREAMING_SNAKE_CASE_: Tuple  		=       FlaxViTModelTester(self)
									SCREAMING_SNAKE_CASE_: List[str]  		=       FlaxBertModelTester(self)
									SCREAMING_SNAKE_CASE_: int  		=       vit_model_tester.prepare_config_and_inputs()
									SCREAMING_SNAKE_CASE_: List[Any]  		=       bert_model_tester.prepare_config_and_inputs()

									SCREAMING_SNAKE_CASE_: List[Any]  		=       vision_config_and_inputs

									SCREAMING_SNAKE_CASE_: 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   __lowercase				( UpperCAmelCase_		,       unittest.TestCase	):




			"""simple docstring"""







			def        _SCREAMING_SNAKE_CASE			( self  :     Tuple):
									SCREAMING_SNAKE_CASE_: Tuple  		=       FlaxVisionTextDualEncoderModel.from_vision_text_pretrained(
									    "hf-internal-testing/tiny-random-clip"   ,						"hf-internal-testing/tiny-bert"   ,						vision_from_pt=A__   ,						text_from_pt=A__   ,						)
									SCREAMING_SNAKE_CASE_: Dict  		=       13
									SCREAMING_SNAKE_CASE_: List[Any]  		=       floats_tensor(
									    [
									        batch_size,
									        model.config.vision_config.num_channels,
									        model.config.vision_config.image_size,
									        model.config.vision_config.image_size,
									    ])
									SCREAMING_SNAKE_CASE_: List[Any]  		=       ids_tensor([batch_size, 4]   ,						model.config.text_config.vocab_size)
									SCREAMING_SNAKE_CASE_: int  		=       random_attention_mask([batch_size, 4])
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       {"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

									return model, inputs



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]   ,						lowerCAmelCase__  :     Tuple   ,						lowerCAmelCase__  :     Optional[Any]):
									SCREAMING_SNAKE_CASE_: int  		=       FlaxCLIPVisionModel(A__)
									SCREAMING_SNAKE_CASE_: str  		=       FlaxBertModel(A__)
									return vision_model, text_model




			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       FlaxCLIPVisionModelTester(self)
									SCREAMING_SNAKE_CASE_: Dict  		=       FlaxBertModelTester(self)
									SCREAMING_SNAKE_CASE_: Dict  		=       clip_model_tester.prepare_config_and_inputs()
									SCREAMING_SNAKE_CASE_: Any  		=       bert_model_tester.prepare_config_and_inputs()

									SCREAMING_SNAKE_CASE_: Optional[int]  		=       vision_config_and_inputs

									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       text_config_and_inputs

									# make sure that cross attention layers are added
									return {
									    "text_config": text_config,
									    "vision_config": vision_config,
									    "pixel_values": pixel_values,
									    "attention_mask": attention_mask,
									    "input_ids": input_ids,
									    "token_type_ids": token_type_ids,
									}







@require_flax
@require_vision
class   __lowercase				( unittest.TestCase	):




			"""simple docstring"""







			@slow
			def        _SCREAMING_SNAKE_CASE			( self  :     str):
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       FlaxVisionTextDualEncoderModel.from_pretrained("clip-italian/clip-italian"   ,						logit_scale_init_value=1.0)
									SCREAMING_SNAKE_CASE_: Dict  		=       VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian")

									SCREAMING_SNAKE_CASE_: Dict  		=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       processor(
									    text=["una foto di un gatto", "una foto di un cane"]   ,						images=A__   ,						padding=A__   ,						return_tensors="np")

									SCREAMING_SNAKE_CASE_: int  		=       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])   ,						)

									SCREAMING_SNAKE_CASE_: List[Any]  		=       np.array([[1.228_4727, 0.310_4122]])

									self.assertTrue(np.allclose(outputs.logits_per_image   ,						A__   ,						atol=1E-3))









import argparse

import torch

from ...utils import logging
from . import AlbertConfig, AlbertForPreTraining, load_tf_weights_in_albert


logging.set_verbosity_info()

def 						UpperCamelCase					(lowercase_: Optional[int]    ,      lowercase_: Union[str, Any]    ,      lowercase_: Optional[Any]					)     ->      Tuple:
	# Initialise PyTorch model
	A__							:    str        =		AlbertConfig.from_json_file(lowercase_					)
	print(f"""Building PyTorch model from configuration: {config}"""					)
	A__							:    List[Any]        =		AlbertForPreTraining(lowercase_					)

	# Load weights from tf checkpoint
	load_tf_weights_in_albert(lowercase_    ,      lowercase_    ,      lowercase_					)

	# Save pytorch-model
	print(f"""Save PyTorch model to {pytorch_dump_path}"""					)
	torch.save(model.state_dict()    ,      lowercase_					)


if __name__ == "__main__":
	A_       : int         =			argparse.ArgumentParser()
	# Required parameters
	parser.add_argument(
	    '--tf_checkpoint_path', default=None, type=str, required=True, help='Path to the TensorFlow checkpoint path.'
	)
	parser.add_argument(
	    '--albert_config_file',
	    default=None,
	    type=str,
	    required=True,
	    help=(
	        'The config json file corresponding to the pre-trained ALBERT model. \n'
	        'This specifies the model architecture.'
	    ),
	)
	parser.add_argument(
	    '--pytorch_dump_path', default=None, type=str, required=True, help='Path to the output PyTorch model.'
	)
	A_       : int         =			parser.parse_args()
	convert_tf_checkpoint_to_pytorch(args.tf_checkpoint_path, args.albert_config_file, args.pytorch_dump_path)



