



"""simple docstring"""
from __future__ import annotations

import collections
import tempfile
import unittest

import numpy as np

from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import is_tf_available, is_vision_available

from ...test_modeling_tf_common import floats_tensor, ids_tensor, random_attention_mask
from ..bert.test_modeling_tf_bert import TFBertModelTester
from ..clip.test_modeling_tf_clip import TFCLIPVisionModelTester
from ..deit.test_modeling_tf_deit import TFDeiTModelTester
from ..roberta.test_modeling_tf_roberta import TFRobertaModelTester
from ..vit.test_modeling_tf_vit import TFViTModelTester


if is_tf_available():
							from transformers import (
							    TFBertModel,
							    TFCLIPVisionModel,
							    TFDeiTModel,
							    TFRobertaModel,
							    TFVisionTextDualEncoderModel,
							    TFViTModel,
							    VisionTextDualEncoderConfig,
							)

if is_vision_available():
							from PIL import Image

							from transformers import VisionTextDualEncoderProcessor


def 			_SCREAMING_SNAKE_CASE						(__lowerCAmelCase							) ->						str:







		'''simple docstring'''


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


@require_tf
class    SCREAMING_SNAKE_CASE__ :

				def 					_UpperCAmelCase	(				self			:				Tuple ,  lowerCAmelCase_			:				Union[str, Any] ,  lowerCAmelCase_			:				Tuple):







						"""simple docstring"""







						pass

				def 					_UpperCAmelCase	(				self			:				List[Any]):







						"""simple docstring"""







						pass

				def 					_UpperCAmelCase	(				self			:				Optional[int]):







						"""simple docstring"""







						pass

				def 					_UpperCAmelCase	(				self			:				str ,  lowerCAmelCase_			:				Tuple ,  lowerCAmelCase_			:				str ,  lowerCAmelCase_			:				Union[str, Any] ,  lowerCAmelCase_			:				Any ,  lowerCAmelCase_			:				Union[str, Any]=None ,  **lowerCAmelCase_			:				Union[str, Any]):







						"""simple docstring"""







						lowercase_								= VisionTextDualEncoderConfig.from_vision_text_configs(__A ,  __A)

						lowercase_								= TFVisionTextDualEncoderModel(__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			:				Tuple ,  lowerCAmelCase_			:				List[Any] ,  lowerCAmelCase_			:				Tuple ,  lowerCAmelCase_			:				List[Any] ,  lowerCAmelCase_			:				List[str] ,  lowerCAmelCase_			:				Union[str, Any]=None ,  **lowerCAmelCase_			:				List[Any]):







						"""simple docstring"""







						lowercase_								= self.get_vision_text_model(__A ,  __A)
						lowercase_								= TFVisionTextDualEncoderModel(vision_model=__A ,  text_model=__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			:				Optional[int] ,  lowerCAmelCase_			:				Optional[int] ,  lowerCAmelCase_			:				Dict ,  lowerCAmelCase_			:				Optional[Any] ,  lowerCAmelCase_			:				int ,  lowerCAmelCase_			:				Optional[int]=None ,  **lowerCAmelCase_			:				int):







						"""simple docstring"""







						lowercase_								= self.get_vision_text_model(__A ,  __A)
						lowercase_								= {"vision_model": vision_model, "text_model": text_model}
						lowercase_								= TFVisionTextDualEncoderModel.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			:				List[Any] ,  lowerCAmelCase_			:				List[str] ,  lowerCAmelCase_			:				List[Any] ,  lowerCAmelCase_			:				Optional[int] ,  lowerCAmelCase_			:				Dict ,  lowerCAmelCase_			:				Optional[int]=None ,  **lowerCAmelCase_			:				Tuple):







						"""simple docstring"""







						lowercase_								= self.get_vision_text_model(__A ,  __A)
						lowercase_								= TFVisionTextDualEncoderModel(vision_model=__A ,  text_model=__A)

						lowercase_								= model(input_ids=__A ,  pixel_values=__A ,  attention_mask=__A)
						lowercase_								= output[0].numpy()

						with tempfile.TemporaryDirectory() as tmpdirname:
								model.save_pretrained(__A)
								lowercase_								= TFVisionTextDualEncoderModel.from_pretrained(__A)

								lowercase_								= model(input_ids=__A ,  pixel_values=__A ,  attention_mask=__A)
								lowercase_								= after_output[0].numpy()
								lowercase_								= np.amax(np.abs(out_a - out_a))
								self.assertLessEqual(__A ,  1E-5)

				def 					_UpperCAmelCase	(				self			:				Tuple ,  lowerCAmelCase_			:				Optional[Any] ,  lowerCAmelCase_			:				List[str] ,  lowerCAmelCase_			:				str ,  lowerCAmelCase_			:				Dict ,  lowerCAmelCase_			:				int=None ,  **lowerCAmelCase_			:				Optional[int]):







						"""simple docstring"""







						lowercase_								= self.get_vision_text_model(__A ,  __A)
						lowercase_								= TFVisionTextDualEncoderModel(vision_model=__A ,  text_model=__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			:				int ,  lowerCAmelCase_			:				np.ndarray ,  lowerCAmelCase_			:				np.ndarray ,  lowerCAmelCase_			:				float):







						"""simple docstring"""







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

				def 					_UpperCAmelCase	(				self			:				List[Any]):







						"""simple docstring"""







						lowercase_								= self.prepare_config_and_inputs()
						self.check_vision_text_dual_encoder_model(**__A)

				def 					_UpperCAmelCase	(				self			:				List[Any]):







						"""simple docstring"""







						lowercase_								= self.prepare_config_and_inputs()
						self.check_model_from_pretrained_configs(**__A)

				def 					_UpperCAmelCase	(				self			:				Optional[Any]):







						"""simple docstring"""







						lowercase_								= self.prepare_config_and_inputs()
						self.check_vision_text_dual_encoder_from_pretrained(**__A)

				def 					_UpperCAmelCase	(				self			:				Optional[int]):







						"""simple docstring"""







						lowercase_								= self.prepare_config_and_inputs()
						self.check_save_load(**__A)

				def 					_UpperCAmelCase	(				self			:				Any):







						"""simple docstring"""







						lowercase_								= self.prepare_config_and_inputs()
						self.check_vision_text_output_attention(**__A)




				@slow
				def 					_UpperCAmelCase	(				self			:				int):







						"""simple docstring"""







						lowercase_								= self.get_pretrained_model_and_inputs()

						lowercase_								= model_a(**__A)
						lowercase_								= outputs[0].numpy()

						with tempfile.TemporaryDirectory() as tmp_dirname:
								model_a.save_pretrained(__A)
								lowercase_								= TFVisionTextDualEncoderModel.from_pretrained(__A)

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







@require_tf
class    SCREAMING_SNAKE_CASE__ (							__UpperCAmelCase      ,  unittest.TestCase   ):

				def 					_UpperCAmelCase	(				self			:				Any):







						"""simple docstring"""







						lowercase_								= TFVisionTextDualEncoderModel.from_vision_text_pretrained(
						    """hf-internal-testing/tiny-random-vit""" ,  """hf-internal-testing/tiny-random-bert""")
						lowercase_								= 1_3
						lowercase_								= floats_tensor(
						    [
						        batch_size,
						        model.vision_model.config.num_channels,
						        model.vision_model.config.image_size,
						        model.vision_model.config.image_size,
						    ])
						lowercase_								= ids_tensor([batch_size, 4] ,  model.text_model.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] ,  lowerCAmelCase_			:				List[str] ,  lowerCAmelCase_			:				Optional[Any]):







						"""simple docstring"""







						lowercase_								= TFViTModel(__A ,  name="""vision_model""")
						lowercase_								= TFBertModel(__A ,  name="""text_model""")
						return vision_model, text_model




				def 					_UpperCAmelCase	(				self			:				Tuple):







						"""simple docstring"""







						lowercase_								= TFViTModelTester(self)
						lowercase_								= TFBertModelTester(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

						return {
						    "text_config": text_config,
						    "vision_config": vision_config,
						    "pixel_values": pixel_values,
						    "attention_mask": input_mask,
						    "input_ids": input_ids,
						    "text_token_type_ids": token_type_ids,
						    "text_sequence_labels": sequence_labels,
						    "text_token_labels": token_labels,
						    "text_choice_labels": choice_labels,
						}







@require_tf
class    SCREAMING_SNAKE_CASE__ (							__UpperCAmelCase      ,  unittest.TestCase   ):

				def 					_UpperCAmelCase	(				self			:				Any):







						"""simple docstring"""







						lowercase_								= TFVisionTextDualEncoderModel.from_vision_text_pretrained(
						    """Rocketknight1/tiny-random-deit-tf""" ,  """hf-internal-testing/tiny-random-roberta""")
						lowercase_								= 1_3
						lowercase_								= floats_tensor(
						    [
						        batch_size,
						        model.vision_model.config.num_channels,
						        model.vision_model.config.image_size,
						        model.vision_model.config.image_size,
						    ])
						lowercase_								= ids_tensor([batch_size, 4] ,  model.text_model.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			:				Dict ,  lowerCAmelCase_			:				Optional[Any] ,  lowerCAmelCase_			:				str ,  lowerCAmelCase_			:				Tuple ,  lowerCAmelCase_			:				Optional[Any] ,  lowerCAmelCase_			:				str=None ,  **lowerCAmelCase_			:				List[str]):







						"""simple docstring"""







						lowercase_								= self.get_vision_text_model(__A ,  __A)
						lowercase_								= TFVisionTextDualEncoderModel(vision_model=__A ,  text_model=__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 DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
						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 + 2
						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			:				int ,  lowerCAmelCase_			:				List[str] ,  lowerCAmelCase_			:				Any):







						"""simple docstring"""







						lowercase_								= TFDeiTModel(__A ,  name="""vision_model""")
						lowercase_								= TFRobertaModel(__A ,  name="""text_model""")
						return vision_model, text_model




				def 					_UpperCAmelCase	(				self			:				int):







						"""simple docstring"""







						lowercase_								= TFDeiTModelTester(self)
						lowercase_								= TFRobertaModelTester(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

						return {
						    "text_config": text_config,
						    "vision_config": vision_config,
						    "pixel_values": pixel_values,
						    "attention_mask": input_mask,
						    "input_ids": input_ids,
						    "text_token_type_ids": token_type_ids,
						    "text_sequence_labels": sequence_labels,
						    "text_token_labels": token_labels,
						    "text_choice_labels": choice_labels,
						}







@require_tf
class    SCREAMING_SNAKE_CASE__ (							__UpperCAmelCase      ,  unittest.TestCase   ):

				def 					_UpperCAmelCase	(				self			:				Dict):







						"""simple docstring"""







						lowercase_								= TFVisionTextDualEncoderModel.from_vision_text_pretrained(
						    """Rocketknight1/tiny-random-clip-tf""" ,  """hf-internal-testing/tiny-random-bert""")
						lowercase_								= 1_3
						lowercase_								= floats_tensor(
						    [
						        batch_size,
						        model.vision_model.config.num_channels,
						        model.vision_model.config.image_size,
						        model.vision_model.config.image_size,
						    ])
						lowercase_								= ids_tensor([batch_size, 4] ,  model.text_model.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] ,  lowerCAmelCase_			:				List[Any] ,  lowerCAmelCase_			:				List[str]):







						"""simple docstring"""







						lowercase_								= TFCLIPVisionModel(__A ,  name="""vision_model""")
						lowercase_								= TFBertModel(__A ,  name="""text_model""")
						return vision_model, text_model




				def 					_UpperCAmelCase	(				self			:				List[Any]):







						"""simple docstring"""







						lowercase_								= TFCLIPVisionModelTester(self)
						lowercase_								= TFBertModelTester(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

						return {
						    "text_config": text_config,
						    "vision_config": vision_config,
						    "pixel_values": pixel_values,
						    "attention_mask": input_mask,
						    "input_ids": input_ids,
						    "text_token_type_ids": token_type_ids,
						    "text_sequence_labels": sequence_labels,
						    "text_token_labels": token_labels,
						    "text_choice_labels": choice_labels,
						}







@require_vision
@require_tf
class    SCREAMING_SNAKE_CASE__ (							unittest.TestCase   ):

				@slow
				def 					_UpperCAmelCase	(				self			:				Dict):







						"""simple docstring"""







						lowercase_								= TFVisionTextDualEncoderModel.from_pretrained(
						    """clip-italian/clip-italian""" ,  logit_scale_init_value=1.0 ,  from_pt=__A)
						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.2_284_727, 0.3_104_122]])

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






"""simple docstring"""
from typing import TYPE_CHECKING

from ...utils import _LazyModule


UpperCAmelCase						:		List[Any]			= {"tokenization_bertweet": ["BertweetTokenizer"]}


if TYPE_CHECKING:
       from .tokenization_bertweet import BertweetTokenizer

else:
       import sys

       UpperCAmelCase						:		Tuple			= _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)

