






import warnings
from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig, OnnxConfigWithPast, OnnxSeqaSeqConfigWithPast
from ...onnx.utils import compute_effective_axis_dimension
from ...utils import TensorType, is_torch_available, logging


__UpperCamelCase      :      Optional[Any]     						=						logging.get_logger(__name__)

__UpperCamelCase      :      Any     						=						{
    """facebook/bart-large""": """https://huggingface.co/facebook/bart-large/resolve/main/config.json""",
    # See all BART models at https://huggingface.co/models?filter=bart
}


class        __UpperCamelCase    (     UpperCamelCase_   ):
	__snake_case	:Dict   =       'bart'
	__snake_case	:List[str]   =       ['past_key_values']
	__snake_case	:Dict   =       {'num_attention_heads': 'encoder_attention_heads', 'hidden_size': 'd_model'}







	def __init__(  self      :							int       ,				_lowerCAmelCase      :							Dict=5_0265       ,				_lowerCAmelCase      :							Dict=1024       ,				_lowerCAmelCase      :							Tuple=12       ,				_lowerCAmelCase      :							Union[str, Any]=4096       ,				_lowerCAmelCase      :							Tuple=16       ,				_lowerCAmelCase      :							Tuple=12       ,				_lowerCAmelCase      :							str=4096       ,				_lowerCAmelCase      :							Union[str, Any]=16       ,				_lowerCAmelCase      :							Optional[int]=0.0       ,				_lowerCAmelCase      :							Optional[Any]=0.0       ,				_lowerCAmelCase      :							List[str]="gelu"       ,				_lowerCAmelCase      :							Optional[Any]=1024       ,				_lowerCAmelCase      :							Any=0.1       ,				_lowerCAmelCase      :							Optional[int]=0.0       ,				_lowerCAmelCase      :							int=0.0       ,				_lowerCAmelCase      :							Tuple=0.02       ,				_lowerCAmelCase      :							str=0.0       ,				_lowerCAmelCase      :							Optional[Any]=False       ,				_lowerCAmelCase      :							Optional[int]=True       ,				_lowerCAmelCase      :							List[Any]=3       ,				_lowerCAmelCase      :							Union[str, Any]=1       ,				_lowerCAmelCase      :							Dict=0       ,				_lowerCAmelCase      :							int=2       ,				_lowerCAmelCase      :							int=True       ,				_lowerCAmelCase      :							Optional[Any]=2       ,				_lowerCAmelCase      :							Tuple=2       ,				**_lowerCAmelCase      :							Any       ,				)		-> Dict:
		"""simple docstring"""







		__lowercase             =  vocab_size
		__lowercase             =  max_position_embeddings
		__lowercase             =  d_model
		__lowercase             =  encoder_ffn_dim
		__lowercase             =  encoder_layers
		__lowercase             =  encoder_attention_heads
		__lowercase             =  decoder_ffn_dim
		__lowercase             =  decoder_layers
		__lowercase             =  decoder_attention_heads
		__lowercase             =  dropout
		__lowercase             =  attention_dropout
		__lowercase             =  activation_dropout
		__lowercase             =  activation_function
		__lowercase             =  init_std
		__lowercase             =  encoder_layerdrop
		__lowercase             =  decoder_layerdrop
		__lowercase             =  classifier_dropout
		__lowercase             =  use_cache
		__lowercase             =  encoder_layers
		__lowercase             =  scale_embedding  # scale factor will be sqrt(d_model) if True

		super().__init__(
		    num_labels=__A       ,				pad_token_id=__A       ,				bos_token_id=__A       ,				eos_token_id=__A       ,				is_encoder_decoder=__A       ,				decoder_start_token_id=__A       ,				forced_eos_token_id=__A       ,				**__A       ,				)

		# ensure backward compatibility for BART CNN models
		if self.forced_bos_token_id is None and kwargs.get("""force_bos_token_to_be_generated"""       ,				__A			):
			__lowercase             =  self.bos_token_id
			warnings.warn(
			    F'Please make sure the config includes `forced_bos_token_id={self.bos_token_id}` in future versions. '
			    """The config can simply be saved and uploaded again to be fixed."""			)


class        __UpperCamelCase    (     UpperCamelCase_   ):







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







		if self.task in ["default", "seq2seq-lm"]:
			__lowercase             =  OrderedDict(
			    [
			        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
			        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
			    ]			)

			if self.use_past:
				__lowercase             =  {0: "batch"}
				__lowercase             =  {0: "batch", 1: "past_decoder_sequence + sequence"}
			else:
				__lowercase             =  {0: "batch", 1: "decoder_sequence"}
				__lowercase             =  {0: "batch", 1: "decoder_sequence"}

			if self.use_past:
				self.fill_with_past_key_values_(__A       ,				direction="""inputs"""			)
		elif self.task == "causal-lm":
			# TODO: figure this case out.
			__lowercase             =  OrderedDict(
			    [
			        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
			        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
			    ]			)
			if self.use_past:
				__lowercase             =  self.num_layers
				for i in range(__A			):
					__lowercase             =  {0: "batch", 2: "past_sequence + sequence"}
					__lowercase             =  {0: "batch", 2: "past_sequence + sequence"}
		else:
			__lowercase             =  OrderedDict(
			    [
			        ("""input_ids""", {0: """batch""", 1: """encoder_sequence"""}),
			        ("""attention_mask""", {0: """batch""", 1: """encoder_sequence"""}),
			        ("""decoder_input_ids""", {0: """batch""", 1: """decoder_sequence"""}),
			        ("""decoder_attention_mask""", {0: """batch""", 1: """decoder_sequence"""}),
			    ]			)

		return common_inputs







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







		if self.task in ["default", "seq2seq-lm"]:
			__lowercase             =  super().outputs
		else:
			__lowercase             =  super(__A       ,				self			).outputs
			if self.use_past:
				__lowercase             =  self.num_layers
				for i in range(__A			):
					__lowercase             =  {0: "batch", 2: "past_sequence + sequence"}
					__lowercase             =  {0: "batch", 2: "past_sequence + sequence"}
		return common_outputs







	def  _a   (  self      :							Any       ,				_lowerCAmelCase      :							PreTrainedTokenizer       ,				_lowerCAmelCase      :							int = -1       ,				_lowerCAmelCase      :							int = -1       ,				_lowerCAmelCase      :							bool = False       ,				_lowerCAmelCase      :							Optional[TensorType] = None       ,				)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase             =  self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
		    __A       ,				__A       ,				__A       ,				__A       ,				__A			)

		# Generate decoder inputs
		__lowercase             =  seq_length if not self.use_past else 1
		__lowercase             =  self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
		    __A       ,				__A       ,				__A       ,				__A       ,				__A			)
		__lowercase             =  {F'decoder_{name}': tensor for name, tensor in decoder_inputs.items()}
		__lowercase             =  dict(**__A       ,				**__A			)

		if self.use_past:
			if not is_torch_available():
				raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""			)
			else:
				import torch
			__lowercase             =  common_inputs["input_ids"].shape
			__lowercase             =  common_inputs["decoder_input_ids"].shape[1]
			__lowercase             =  self.num_attention_heads
			__lowercase             =  (
			    batch,
			    num_encoder_attention_heads,
			    encoder_seq_length,
			    self._config.hidden_size // num_encoder_attention_heads,
			)
			__lowercase             =  decoder_seq_length + 3
			__lowercase             =  (
			    batch,
			    num_decoder_attention_heads,
			    decoder_past_length,
			    self._config.hidden_size // num_decoder_attention_heads,
			)

			__lowercase             =  torch.cat(
			    [common_inputs["""decoder_attention_mask"""], torch.ones(__A       ,				__A			)]       ,				dim=1			)

			__lowercase             =  []
			# If the number of encoder and decoder layers are present in the model configuration, both are considered
			__lowercase             =  self.num_layers
			__lowercase             =  min(__A       ,				__A			)
			__lowercase             =  max(__A       ,				__A			) - min_num_layers
			__lowercase             =  "encoder" if num_encoder_layers > num_decoder_layers else "decoder"

			for _ in range(__A			):
				common_inputs["past_key_values"].append(
				    (
				        torch.zeros(__A			),
				        torch.zeros(__A			),
				        torch.zeros(__A			),
				        torch.zeros(__A			),
				    )			)
			# TODO: test this.
			__lowercase             =  encoder_shape if remaining_side_name == "encoder" else decoder_shape
			for _ in range(__A       ,				__A			):
				common_inputs["past_key_values"].append((torch.zeros(__A			), torch.zeros(__A			))			)
		return common_inputs







	def  _a   (  self      :							List[Any]       ,				_lowerCAmelCase      :							PreTrainedTokenizer       ,				_lowerCAmelCase      :							int = -1       ,				_lowerCAmelCase      :							int = -1       ,				_lowerCAmelCase      :							bool = False       ,				_lowerCAmelCase      :							Optional[TensorType] = None       ,				)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase             =  self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
		    __A       ,				__A       ,				__A       ,				__A       ,				__A			)

		if self.use_past:
			if not is_torch_available():
				raise ValueError("""Cannot generate dummy past_keys inputs without PyTorch installed."""			)
			else:
				import torch
			__lowercase             =  common_inputs["input_ids"].shape
			# Not using the same length for past_key_values
			__lowercase             =  seqlen + 2
			__lowercase             =  self.num_layers
			__lowercase             =  self.num_attention_heads
			__lowercase             =  (
			    batch,
			    num_encoder_attention_heads,
			    past_key_values_length,
			    self._config.hidden_size // num_encoder_attention_heads,
			)

			__lowercase             =  common_inputs["attention_mask"].dtype
			__lowercase             =  torch.cat(
			    [common_inputs["""attention_mask"""], torch.ones(__A       ,				__A       ,				dtype=__A			)]       ,				dim=1			)
			__lowercase             =  [
			    (torch.zeros(__A			), torch.zeros(__A			)) for _ in range(__A			)
			]
		return common_inputs







	def  _a   (  self      :							str       ,				_lowerCAmelCase      :							PreTrainedTokenizer       ,				_lowerCAmelCase      :							int = -1       ,				_lowerCAmelCase      :							int = -1       ,				_lowerCAmelCase      :							bool = False       ,				_lowerCAmelCase      :							Optional[TensorType] = None       ,				)		-> Optional[int]:
		"""simple docstring"""







		__lowercase             =  compute_effective_axis_dimension(
		    __A       ,				fixed_dimension=OnnxConfig.default_fixed_batch       ,				num_token_to_add=0			)

		# If dynamic axis (-1) we forward with a fixed dimension of 8 tokens to avoid optimizations made by ONNX
		__lowercase             =  tokenizer.num_special_tokens_to_add(__A			)
		__lowercase             =  compute_effective_axis_dimension(
		    __A       ,				fixed_dimension=OnnxConfig.default_fixed_sequence       ,				num_token_to_add=__A			)

		# Generate dummy inputs according to compute batch and sequence
		__lowercase             =  [" ".join([tokenizer.unk_token]			) * seq_length] * batch_size
		__lowercase             =  dict(tokenizer(__A       ,				return_tensors=__A			)			)
		return common_inputs







	def  _a   (  self      :							Tuple       ,				_lowerCAmelCase      :							PreTrainedTokenizer       ,				_lowerCAmelCase      :							int = -1       ,				_lowerCAmelCase      :							int = -1       ,				_lowerCAmelCase      :							bool = False       ,				_lowerCAmelCase      :							Optional[TensorType] = None       ,				)		-> Optional[Any]:
		"""simple docstring"""







		if self.task in ["default", "seq2seq-lm"]:
			__lowercase             =  self._generate_dummy_inputs_for_default_and_seqaseq_lm(
			    __A       ,				batch_size=__A       ,				seq_length=__A       ,				is_pair=__A       ,				framework=__A			)

		elif self.task == "causal-lm":
			__lowercase             =  self._generate_dummy_inputs_for_causal_lm(
			    __A       ,				batch_size=__A       ,				seq_length=__A       ,				is_pair=__A       ,				framework=__A			)
		else:
			__lowercase             =  self._generate_dummy_inputs_for_sequence_classification_and_question_answering(
			    __A       ,				batch_size=__A       ,				seq_length=__A       ,				is_pair=__A       ,				framework=__A			)

		return common_inputs







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







		if self.task in ["default", "seq2seq-lm"]:
			__lowercase             =  super()._flatten_past_key_values_(__A       ,				__A       ,				__A       ,				__A			)
		else:
			__lowercase             =  super(__A       ,				self			)._flatten_past_key_values_(
			    __A       ,				__A       ,				__A       ,				__A			)














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			)			)

