






from __future__ import annotations

import unittest

from transformers import MobileBertConfig, is_tf_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
						import tensorflow as tf

						from transformers import (
						    TF_MODEL_FOR_PRETRAINING_MAPPING,
						    TFMobileBertForMaskedLM,
						    TFMobileBertForMultipleChoice,
						    TFMobileBertForNextSentencePrediction,
						    TFMobileBertForPreTraining,
						    TFMobileBertForQuestionAnswering,
						    TFMobileBertForSequenceClassification,
						    TFMobileBertForTokenClassification,
						    TFMobileBertModel,
						)


@require_tf
class        __UpperCamelCase    (     _lowerCAmelCase   ,			_lowerCAmelCase   ,			unittest.TestCase   ):
	__snake_case	:Any   =       (
	    (
	        TFMobileBertModel,
	        TFMobileBertForMaskedLM,
	        TFMobileBertForNextSentencePrediction,
	        TFMobileBertForPreTraining,
	        TFMobileBertForQuestionAnswering,
	        TFMobileBertForSequenceClassification,
	        TFMobileBertForTokenClassification,
	        TFMobileBertForMultipleChoice,
	    )
	    if is_tf_available()
	    else ()
	)
	__snake_case	:Any   =       (
	    {
	        'feature-extraction': TFMobileBertModel,
	        'fill-mask': TFMobileBertForMaskedLM,
	        'question-answering': TFMobileBertForQuestionAnswering,
	        'text-classification': TFMobileBertForSequenceClassification,
	        'token-classification': TFMobileBertForTokenClassification,
	        'zero-shot': TFMobileBertForSequenceClassification,
	    }
	    if is_tf_available()
	    else {}
	)
	__snake_case	:Optional[Any]   =       False
	__snake_case	:Dict   =       False







	def  _a   (  self      :							Dict       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							List[Any]       ,				_lowerCAmelCase      :							List[str]=False			)		-> List[Any]:
		"""simple docstring"""







		__lowercase             =  super()._prepare_for_class(_lowerCAmelCase       ,				_lowerCAmelCase       ,				return_labels=_lowerCAmelCase			)

		if return_labels:
			if model_class in get_values(_lowerCAmelCase			):
				__lowercase             =  tf.zeros(self.model_tester.batch_size       ,				dtype=tf.intaa			)

		return inputs_dict


	class        __UpperCamelCase    (     _lowerCAmelCase   ):







		def __init__(  self      :							int       ,				_lowerCAmelCase      :							Union[str, Any]       ,				_lowerCAmelCase      :							Tuple=13       ,				_lowerCAmelCase      :							Dict=7       ,				_lowerCAmelCase      :							Optional[int]=True       ,				_lowerCAmelCase      :							List[str]=True       ,				_lowerCAmelCase      :							Dict=True       ,				_lowerCAmelCase      :							Tuple=True       ,				_lowerCAmelCase      :							int=99       ,				_lowerCAmelCase      :							Optional[int]=32       ,				_lowerCAmelCase      :							Tuple=32       ,				_lowerCAmelCase      :							Union[str, Any]=2       ,				_lowerCAmelCase      :							Optional[int]=4       ,				_lowerCAmelCase      :							int=37       ,				_lowerCAmelCase      :							List[Any]="gelu"       ,				_lowerCAmelCase      :							Any=0.1       ,				_lowerCAmelCase      :							Union[str, Any]=0.1       ,				_lowerCAmelCase      :							Optional[int]=512       ,				_lowerCAmelCase      :							List[str]=16       ,				_lowerCAmelCase      :							Any=2       ,				_lowerCAmelCase      :							List[str]=0.02       ,				_lowerCAmelCase      :							Dict=3       ,				_lowerCAmelCase      :							int=4       ,				_lowerCAmelCase      :							str=None       ,				)		-> Tuple:
			"""simple docstring"""







			__lowercase             =  parent
			__lowercase             =  batch_size
			__lowercase             =  seq_length
			__lowercase             =  is_training
			__lowercase             =  use_input_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_labels
			__lowercase             =  num_choices
			__lowercase             =  scope
			__lowercase             =  embedding_size







		def  _a   (  self      :							Tuple			)		-> Dict:
			"""simple docstring"""







			__lowercase             =  ids_tensor([self.batch_size, self.seq_length]       ,				self.vocab_size			)

			__lowercase             =  None
			if self.use_input_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             =  None
			__lowercase             =  None
			__lowercase             =  None
			if self.use_labels:
				__lowercase             =  ids_tensor([self.batch_size]       ,				self.type_sequence_label_size			)
				__lowercase             =  ids_tensor([self.batch_size, self.seq_length]       ,				self.num_labels			)
				__lowercase             =  ids_tensor([self.batch_size]       ,				self.num_choices			)

			__lowercase             =  MobileBertConfig(
			    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       ,				initializer_range=self.initializer_range       ,				embedding_size=self.embedding_size       ,				)

			return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels







		def  _a   (  self      :							Optional[int]       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							List[str]       ,				_lowerCAmelCase      :							Dict			)		-> Dict:
			"""simple docstring"""







			__lowercase             =  TFMobileBertModel(config=_lowerCAmelCase			)
			__lowercase             =  {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
			__lowercase             =  model(_lowerCAmelCase			)

			__lowercase             =  [input_ids, input_mask]
			__lowercase             =  model(_lowerCAmelCase			)

			__lowercase             =  model(_lowerCAmelCase			)

			self.parent.assertEqual(
			    result.last_hidden_state.shape       ,				(self.batch_size, self.seq_length, self.hidden_size)			)
			self.parent.assertEqual(result.pooler_output.shape       ,				(self.batch_size, self.hidden_size)			)







		def  _a   (  self      :							Dict       ,				_lowerCAmelCase      :							Optional[int]       ,				_lowerCAmelCase      :							List[Any]       ,				_lowerCAmelCase      :							Optional[int]       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							List[str]       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							str			)		-> Dict:
			"""simple docstring"""







			__lowercase             =  TFMobileBertForMaskedLM(config=_lowerCAmelCase			)
			__lowercase             =  {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
			__lowercase             =  model(_lowerCAmelCase			)
			self.parent.assertEqual(result.logits.shape       ,				(self.batch_size, self.seq_length, self.vocab_size)			)







		def  _a   (  self      :							Union[str, Any]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							List[Any]       ,				_lowerCAmelCase      :							Optional[int]			)		-> Union[str, Any]:
			"""simple docstring"""







			__lowercase             =  TFMobileBertForNextSentencePrediction(config=_lowerCAmelCase			)
			__lowercase             =  {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
			__lowercase             =  model(_lowerCAmelCase			)
			self.parent.assertEqual(result.logits.shape       ,				(self.batch_size, 2)			)







		def  _a   (  self      :							List[str]       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							List[Any]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							Dict       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							Dict			)		-> Optional[int]:
			"""simple docstring"""







			__lowercase             =  TFMobileBertForPreTraining(config=_lowerCAmelCase			)
			__lowercase             =  {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
			__lowercase             =  model(_lowerCAmelCase			)
			self.parent.assertEqual(
			    result.prediction_logits.shape       ,				(self.batch_size, self.seq_length, self.vocab_size)			)
			self.parent.assertEqual(result.seq_relationship_logits.shape       ,				(self.batch_size, 2)			)







		def  _a   (  self      :							Optional[Any]       ,				_lowerCAmelCase      :							List[Any]       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							List[str]       ,				_lowerCAmelCase      :							List[Any]       ,				_lowerCAmelCase      :							Union[str, Any]       ,				_lowerCAmelCase      :							Union[str, Any]       ,				_lowerCAmelCase      :							Optional[Any]			)		-> str:
			"""simple docstring"""







			__lowercase             =  self.num_labels
			__lowercase             =  TFMobileBertForSequenceClassification(config=_lowerCAmelCase			)
			__lowercase             =  {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
			__lowercase             =  model(_lowerCAmelCase			)
			self.parent.assertEqual(result.logits.shape       ,				(self.batch_size, self.num_labels)			)







		def  _a   (  self      :							List[Any]       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							Union[str, Any]       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							Union[str, Any]       ,				_lowerCAmelCase      :							Dict			)		-> int:
			"""simple docstring"""







			__lowercase             =  self.num_choices
			__lowercase             =  TFMobileBertForMultipleChoice(config=_lowerCAmelCase			)
			__lowercase             =  tf.tile(tf.expand_dims(_lowerCAmelCase       ,				1			)       ,				(1, self.num_choices, 1)			)
			__lowercase             =  tf.tile(tf.expand_dims(_lowerCAmelCase       ,				1			)       ,				(1, self.num_choices, 1)			)
			__lowercase             =  tf.tile(tf.expand_dims(_lowerCAmelCase       ,				1			)       ,				(1, self.num_choices, 1)			)
			__lowercase             =  {
			    """input_ids""": multiple_choice_inputs_ids,
			    """attention_mask""": multiple_choice_input_mask,
			    """token_type_ids""": multiple_choice_token_type_ids,
			}
			__lowercase             =  model(_lowerCAmelCase			)
			self.parent.assertEqual(result.logits.shape       ,				(self.batch_size, self.num_choices)			)







		def  _a   (  self      :							Dict       ,				_lowerCAmelCase      :							Dict       ,				_lowerCAmelCase      :							Optional[int]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							Dict       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							Optional[int]			)		-> List[Any]:
			"""simple docstring"""







			__lowercase             =  self.num_labels
			__lowercase             =  TFMobileBertForTokenClassification(config=_lowerCAmelCase			)
			__lowercase             =  {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
			__lowercase             =  model(_lowerCAmelCase			)
			self.parent.assertEqual(result.logits.shape       ,				(self.batch_size, self.seq_length, self.num_labels)			)







		def  _a   (  self      :							int       ,				_lowerCAmelCase      :							Union[str, Any]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							List[str]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							str			)		-> Any:
			"""simple docstring"""







			__lowercase             =  TFMobileBertForQuestionAnswering(config=_lowerCAmelCase			)
			__lowercase             =  {"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
			__lowercase             =  model(_lowerCAmelCase			)
			self.parent.assertEqual(result.start_logits.shape       ,				(self.batch_size, self.seq_length)			)
			self.parent.assertEqual(result.end_logits.shape       ,				(self.batch_size, self.seq_length)			)







		def  _a   (  self      :							Union[str, Any]			)		-> Tuple:
			"""simple docstring"""







			__lowercase             =  self.prepare_config_and_inputs()
			(
			    (
			    __lowercase
			)       ,						(
			    __lowercase
			)       ,						(
			    __lowercase
			)       ,						(
			    __lowercase
			)       ,						(
			    __lowercase
			)       ,						(
			    __lowercase
			)       ,						(
			    __lowercase
			)       ,						
			)             =  config_and_inputs
			__lowercase             =  {"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
			return config, inputs_dict







	def  _a   (  self      :							List[str]			)		-> Dict:
		"""simple docstring"""







		__lowercase             =  TFMobileBertModelTest.TFMobileBertModelTester(self			)
		__lowercase             =  ConfigTester(self       ,				config_class=_lowerCAmelCase       ,				hidden_size=37			)







	def  _a   (  self      :							Any			)		-> Tuple:
		"""simple docstring"""







		self.config_tester.run_common_tests()







	def  _a   (  self      :							Optional[int]			)		-> int:
		"""simple docstring"""







		__lowercase             =  self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_mobilebert_model(*_lowerCAmelCase			)







	def  _a   (  self      :							List[Any]			)		-> Optional[int]:
		"""simple docstring"""







		__lowercase             =  self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_mobilebert_for_masked_lm(*_lowerCAmelCase			)







	def  _a   (  self      :							str			)		-> List[Any]:
		"""simple docstring"""







		__lowercase             =  self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_mobilebert_for_multiple_choice(*_lowerCAmelCase			)







	def  _a   (  self      :							str			)		-> Dict:
		"""simple docstring"""







		__lowercase             =  self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_mobilebert_for_next_sequence_prediction(*_lowerCAmelCase			)







	def  _a   (  self      :							int			)		-> int:
		"""simple docstring"""







		__lowercase             =  self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_mobilebert_for_pretraining(*_lowerCAmelCase			)







	def  _a   (  self      :							Union[str, Any]			)		-> Tuple:
		"""simple docstring"""







		__lowercase             =  self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_mobilebert_for_question_answering(*_lowerCAmelCase			)







	def  _a   (  self      :							List[Any]			)		-> List[str]:
		"""simple docstring"""







		__lowercase             =  self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_mobilebert_for_sequence_classification(*_lowerCAmelCase			)







	def  _a   (  self      :							int			)		-> List[Any]:
		"""simple docstring"""







		__lowercase             =  self.model_tester.prepare_config_and_inputs()
		self.model_tester.create_and_check_mobilebert_for_token_classification(*_lowerCAmelCase			)







	@slow
	def  _a   (  self      :							Dict			)		-> Union[str, Any]:
		"""simple docstring"""







		for model_name in ["google/mobilebert-uncased"]:
			__lowercase             =  TFMobileBertModel.from_pretrained(_lowerCAmelCase			)
			self.assertIsNotNone(_lowerCAmelCase			)


@require_tf
class        __UpperCamelCase    (     unittest.TestCase   ):







	@slow
	def  _a   (  self      :							Any			)		-> Any:
		"""simple docstring"""







		__lowercase             =  TFMobileBertForPreTraining.from_pretrained("""google/mobilebert-uncased"""			)
		__lowercase             =  tf.constant([[0, 1, 2, 3, 4, 5]]			)
		__lowercase             =  model(_lowerCAmelCase			)[0]

		__lowercase             =  [1, 6, 3_0522]
		self.assertEqual(output.shape       ,				_lowerCAmelCase			)

		__lowercase             =  tf.constant(
		    [
		        [
		            [-4.5_919_547, -9.248_295, -9.645_256],
		            [-6.7_306_175, -6.440_284, -6.6_052_837],
		            [-7.2_743_506, -6.7_847_915, -6.024_673],
		        ]
		    ]			)
		tf.debugging.assert_near(output[:, :3, :3]       ,				_lowerCAmelCase       ,				atol=1e-4			)









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 				snake_case  (     lowerCamelCase					):




	'''simple docstring'''







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


@require_tf
class        __UpperCamelCase    :







	def  _a   (  self      :							List[Any]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							Optional[Any]			)		-> Union[str, Any]:
		"""simple docstring"""







		pass







	def  _a   (  self      :							Dict			)		-> Optional[int]:
		"""simple docstring"""







		pass







	def  _a   (  self      :							Any			)		-> Optional[Any]:
		"""simple docstring"""







		pass







	def  _a   (  self      :							int       ,				_lowerCAmelCase      :							Optional[int]       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							Optional[Any]       ,				_lowerCAmelCase      :							Dict=None       ,				**_lowerCAmelCase      :							int			)		-> str:
		"""simple docstring"""







		__lowercase             =  VisionTextDualEncoderConfig.from_vision_text_configs(_lowerCAmelCase       ,				_lowerCAmelCase			)

		__lowercase             =  TFVisionTextDualEncoderModel(_lowerCAmelCase			)

		__lowercase             =  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  _a   (  self      :							str       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							List[Any]       ,				_lowerCAmelCase      :							List[str]       ,				_lowerCAmelCase      :							int=None       ,				**_lowerCAmelCase      :							Dict			)		-> Tuple:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.get_vision_text_model(_lowerCAmelCase       ,				_lowerCAmelCase			)
		__lowercase             =  TFVisionTextDualEncoderModel(vision_model=_lowerCAmelCase       ,				text_model=_lowerCAmelCase			)

		__lowercase             =  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  _a   (  self      :							Optional[Any]       ,				_lowerCAmelCase      :							List[Any]       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							Dict       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							Any=None       ,				**_lowerCAmelCase      :							str			)		-> Tuple:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.get_vision_text_model(_lowerCAmelCase       ,				_lowerCAmelCase			)
		__lowercase             =  {"""vision_model""": vision_model, """text_model""": text_model}
		__lowercase             =  TFVisionTextDualEncoderModel.from_vision_text_pretrained(**_lowerCAmelCase			)

		__lowercase             =  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  _a   (  self      :							Dict       ,				_lowerCAmelCase      :							Union[str, Any]       ,				_lowerCAmelCase      :							List[str]       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							Optional[int]       ,				_lowerCAmelCase      :							List[Any]=None       ,				**_lowerCAmelCase      :							Any			)		-> Optional[int]:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.get_vision_text_model(_lowerCAmelCase       ,				_lowerCAmelCase			)
		__lowercase             =  TFVisionTextDualEncoderModel(vision_model=_lowerCAmelCase       ,				text_model=_lowerCAmelCase			)

		__lowercase             =  model(input_ids=_lowerCAmelCase       ,				pixel_values=_lowerCAmelCase       ,				attention_mask=_lowerCAmelCase			)
		__lowercase             =  output[0].numpy()

		with tempfile.TemporaryDirectory() as tmpdirname:
			model.save_pretrained(_lowerCAmelCase			)
			__lowercase             =  TFVisionTextDualEncoderModel.from_pretrained(_lowerCAmelCase			)

			__lowercase             =  model(input_ids=_lowerCAmelCase       ,				pixel_values=_lowerCAmelCase       ,				attention_mask=_lowerCAmelCase			)
			__lowercase             =  after_output[0].numpy()
			__lowercase             =  np.amax(np.abs(out_a - out_a			)			)
			self.assertLessEqual(_lowerCAmelCase       ,				1e-5			)







	def  _a   (  self      :							int       ,				_lowerCAmelCase      :							Any       ,				_lowerCAmelCase      :							Optional[int]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							Optional[int]       ,				_lowerCAmelCase      :							Optional[int]=None       ,				**_lowerCAmelCase      :							Optional[int]			)		-> List[Any]:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.get_vision_text_model(_lowerCAmelCase       ,				_lowerCAmelCase			)
		__lowercase             =  TFVisionTextDualEncoderModel(vision_model=_lowerCAmelCase       ,				text_model=_lowerCAmelCase			)

		__lowercase             =  model(
		    input_ids=_lowerCAmelCase       ,				pixel_values=_lowerCAmelCase       ,				attention_mask=_lowerCAmelCase       ,				output_attentions=_lowerCAmelCase			)

		__lowercase             =  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             =  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(_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  _a   (  self      :							List[Any]       ,				_lowerCAmelCase      :							np.ndarray       ,				_lowerCAmelCase      :							np.ndarray       ,				_lowerCAmelCase      :							float			)		-> Optional[int]:
		"""simple docstring"""







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







	def  _a   (  self      :							List[Any]			)		-> List[Any]:
		"""simple docstring"""







		__lowercase             =  self.prepare_config_and_inputs()
		self.check_vision_text_dual_encoder_model(**_lowerCAmelCase			)







	def  _a   (  self      :							int			)		-> List[Any]:
		"""simple docstring"""







		__lowercase             =  self.prepare_config_and_inputs()
		self.check_model_from_pretrained_configs(**_lowerCAmelCase			)







	def  _a   (  self      :							Union[str, Any]			)		-> int:
		"""simple docstring"""







		__lowercase             =  self.prepare_config_and_inputs()
		self.check_vision_text_dual_encoder_from_pretrained(**_lowerCAmelCase			)







	def  _a   (  self      :							List[str]			)		-> str:
		"""simple docstring"""







		__lowercase             =  self.prepare_config_and_inputs()
		self.check_save_load(**_lowerCAmelCase			)







	def  _a   (  self      :							Dict			)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase             =  self.prepare_config_and_inputs()
		self.check_vision_text_output_attention(**_lowerCAmelCase			)







	@slow
	def  _a   (  self      :							Optional[int]			)		-> Optional[Any]:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.get_pretrained_model_and_inputs()

		__lowercase             =  model_a(**_lowerCAmelCase			)
		__lowercase             =  outputs[0].numpy()

		with tempfile.TemporaryDirectory() as tmp_dirname:
			model_a.save_pretrained(_lowerCAmelCase			)
			__lowercase             =  TFVisionTextDualEncoderModel.from_pretrained(_lowerCAmelCase			)

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


@require_tf
class        __UpperCamelCase    (     _lowerCAmelCase   ,			unittest.TestCase   ):







	def  _a   (  self      :							Optional[int]			)		-> List[str]:
		"""simple docstring"""







		__lowercase             =  TFVisionTextDualEncoderModel.from_vision_text_pretrained(
		    """hf-internal-testing/tiny-random-vit"""       ,				"""hf-internal-testing/tiny-random-bert"""			)
		__lowercase             =  13
		__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  _a   (  self      :							Tuple       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							List[str]			)		-> List[str]:
		"""simple docstring"""







		__lowercase             =  TFViTModel(_lowerCAmelCase       ,				name="""vision_model"""			)
		__lowercase             =  TFBertModel(_lowerCAmelCase       ,				name="""text_model"""			)
		return vision_model, text_model







	def  _a   (  self      :							Dict			)		-> Optional[Any]:
		"""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       ,						__lowercase       ,						__lowercase             =  vision_config_and_inputs

		(
		    (
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __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        __UpperCamelCase    (     _lowerCAmelCase   ,			unittest.TestCase   ):







	def  _a   (  self      :							Tuple			)		-> Any:
		"""simple docstring"""







		__lowercase             =  TFVisionTextDualEncoderModel.from_vision_text_pretrained(
		    """Rocketknight1/tiny-random-deit-tf"""       ,				"""hf-internal-testing/tiny-random-roberta"""			)
		__lowercase             =  13
		__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  _a   (  self      :							Optional[Any]       ,				_lowerCAmelCase      :							Union[str, Any]       ,				_lowerCAmelCase      :							str       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							Tuple       ,				_lowerCAmelCase      :							int=None       ,				**_lowerCAmelCase      :							Tuple			)		-> Dict:
		"""simple docstring"""







		__lowercase       ,						__lowercase             =  self.get_vision_text_model(_lowerCAmelCase       ,				_lowerCAmelCase			)
		__lowercase             =  TFVisionTextDualEncoderModel(vision_model=_lowerCAmelCase       ,				text_model=_lowerCAmelCase			)

		__lowercase             =  model(
		    input_ids=_lowerCAmelCase       ,				pixel_values=_lowerCAmelCase       ,				attention_mask=_lowerCAmelCase       ,				output_attentions=_lowerCAmelCase			)

		__lowercase             =  output.vision_model_output.attentions
		self.assertEqual(len(_lowerCAmelCase			)       ,				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(_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  _a   (  self      :							Tuple       ,				_lowerCAmelCase      :							List[str]       ,				_lowerCAmelCase      :							Dict			)		-> int:
		"""simple docstring"""







		__lowercase             =  TFDeiTModel(_lowerCAmelCase       ,				name="""vision_model"""			)
		__lowercase             =  TFRobertaModel(_lowerCAmelCase       ,				name="""text_model"""			)
		return vision_model, text_model







	def  _a   (  self      :							Tuple			)		-> str:
		"""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       ,						__lowercase       ,						__lowercase             =  vision_config_and_inputs

		(
		    (
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __lowercase
		)       ,						(
		    __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        __UpperCamelCase    (     _lowerCAmelCase   ,			unittest.TestCase   ):







	def  _a   (  self      :							int			)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase             =  TFVisionTextDualEncoderModel.from_vision_text_pretrained(
		    """Rocketknight1/tiny-random-clip-tf"""       ,				"""hf-internal-testing/tiny-random-bert"""			)
		__lowercase             =  13
		__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  _a   (  self      :							Optional[int]       ,				_lowerCAmelCase      :							Dict       ,				_lowerCAmelCase      :							Union[str, Any]			)		-> Dict:
		"""simple docstring"""







		__lowercase             =  TFCLIPVisionModel(_lowerCAmelCase       ,				name="""vision_model"""			)
		__lowercase             =  TFBertModel(_lowerCAmelCase       ,				name="""text_model"""			)
		return vision_model, text_model







	def  _a   (  self      :							Union[str, Any]			)		-> Optional[int]:
		"""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       ,						__lowercase             =  vision_config_and_inputs

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







	@slow
	def  _a   (  self      :							int			)		-> Tuple:
		"""simple docstring"""







		__lowercase             =  TFVisionTextDualEncoderModel.from_pretrained(
		    """clip-italian/clip-italian"""       ,				logit_scale_init_value=1.0       ,				from_pt=_lowerCAmelCase			)
		__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=_lowerCAmelCase       ,				padding=_lowerCAmelCase       ,				return_tensors="""np"""			)

		__lowercase             =  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             =  np.array([[1.2_284_727, 0.3_104_122]]			)

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

