



'''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      a      (			lowerCamelCase__   ):
			'''simple docstring'''





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







@require_tf
class      _lowerCAmelCase							:


	def    _a     (self	,				lowercase	,				lowercase							):
				pass


	def    _a     (self							):
				pass


	def    _a     (self							):
				pass


	def    _a     (self	,				lowercase	,				lowercase	,				lowercase	,				lowercase	,				lowercase=None	,				**lowercase							):
				A_     :						Optional[Any]     =					VisionTextDualEncoderConfig.from_vision_text_configs(lowercase	,				lowercase							)

				A_     :						Any     =					TFVisionTextDualEncoderModel(lowercase							)

				A_     :						Union[str, Any]     =					model(input_ids=lowercase	,				pixel_values=lowercase	,				attention_mask=lowercase							)

				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	,				lowercase	,				lowercase	,				lowercase	,				lowercase	,				lowercase=None	,				**lowercase							):
				A_     :						Any     =					self.get_vision_text_model(lowercase	,				lowercase							)
				A_     :						Dict     =					TFVisionTextDualEncoderModel(vision_model=lowercase	,				text_model=lowercase							)

				A_     :						int     =					model(input_ids=lowercase	,				pixel_values=lowercase	,				attention_mask=lowercase							)

				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	,				lowercase	,				lowercase	,				lowercase	,				lowercase	,				lowercase=None	,				**lowercase							):
				A_     :						str     =					self.get_vision_text_model(lowercase	,				lowercase							)
				A_     :						Optional[Any]     =					{"""vision_model""": vision_model, """text_model""": text_model}
				A_     :						List[str]     =					TFVisionTextDualEncoderModel.from_vision_text_pretrained(**lowercase							)

				A_     :						str     =					model(input_ids=lowercase	,				pixel_values=lowercase	,				attention_mask=lowercase							)

				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	,				lowercase	,				lowercase	,				lowercase	,				lowercase	,				lowercase=None	,				**lowercase							):
				A_     :						List[str]     =					self.get_vision_text_model(lowercase	,				lowercase							)
				A_     :						Union[str, Any]     =					TFVisionTextDualEncoderModel(vision_model=lowercase	,				text_model=lowercase							)

				A_     :						Optional[int]     =					model(input_ids=lowercase	,				pixel_values=lowercase	,				attention_mask=lowercase							)
				A_     :						List[Any]     =					output[0].numpy()

				with tempfile.TemporaryDirectory() as tmpdirname:
							model.save_pretrained(lowercase							)
							A_     :						Any     =					TFVisionTextDualEncoderModel.from_pretrained(lowercase							)

							A_     :						Optional[int]     =					model(input_ids=lowercase	,				pixel_values=lowercase	,				attention_mask=lowercase							)
							A_     :						Dict     =					after_output[0].numpy()
							A_     :						Union[str, Any]     =					np.amax(np.abs(out_a - out_a							)							)
							self.assertLessEqual(lowercase	,				1E-5							)


	def    _a     (self	,				lowercase	,				lowercase	,				lowercase	,				lowercase	,				lowercase=None	,				**lowercase							):
				A_     :						Dict     =					self.get_vision_text_model(lowercase	,				lowercase							)
				A_     :						Dict     =					TFVisionTextDualEncoderModel(vision_model=lowercase	,				text_model=lowercase							)

				A_     :						Any     =					model(
				    input_ids=lowercase	,				pixel_values=lowercase	,				attention_mask=lowercase	,				output_attentions=lowercase							)

				A_     :						Any     =					output.vision_model_output.attentions
				self.assertEqual(len(lowercase							)	,				vision_config.num_hidden_layers							)

				# in ViT, the seq_len equals the number of patches + 1 (we add 1 for the [CLS] token)
				A_     :						Tuple     =					to_atuple(vision_model.config.image_size							)
				A_     :						Optional[Any]     =					to_atuple(vision_model.config.patch_size							)
				A_     :						Optional[int]     =					(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
				A_     :						Union[str, Any]     =					num_patches + 1
				self.assertEqual(vision_attentions[0].shape[-3:]	,				(vision_config.num_attention_heads, seq_len, seq_len)							)

				A_     :						Dict     =					output.text_model_output.attentions
				self.assertEqual(len(lowercase							)	,				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	,				lowercase	,				lowercase	,				lowercase							):
				A_     :						Optional[Any]     =					np.abs((a - b)							).max()
				self.assertLessEqual(lowercase	,				lowercase	,				F'Difference between torch and flax is {diff} (>= {tol}).'							)


	def    _a     (self							):
				A_     :						Optional[int]     =					self.prepare_config_and_inputs()
				self.check_vision_text_dual_encoder_model(**lowercase							)


	def    _a     (self							):
				A_     :						Optional[Any]     =					self.prepare_config_and_inputs()
				self.check_model_from_pretrained_configs(**lowercase							)


	def    _a     (self							):
				A_     :						str     =					self.prepare_config_and_inputs()
				self.check_vision_text_dual_encoder_from_pretrained(**lowercase							)


	def    _a     (self							):
				A_     :						Tuple     =					self.prepare_config_and_inputs()
				self.check_save_load(**lowercase							)


	def    _a     (self							):
				A_     :						int     =					self.prepare_config_and_inputs()
				self.check_vision_text_output_attention(**lowercase							)


	@slow
	def    _a     (self							):
				A_     :						int     =					self.get_pretrained_model_and_inputs()

				A_     :						Union[str, Any]     =					model_a(**lowercase							)
				A_     :						List[str]     =					outputs[0].numpy()

				with tempfile.TemporaryDirectory() as tmp_dirname:
							model_a.save_pretrained(lowercase							)
							A_     :						Union[str, Any]     =					TFVisionTextDualEncoderModel.from_pretrained(lowercase							)

							A_     :						Union[str, Any]     =					model_a(**lowercase							)
							A_     :						Dict     =					after_outputs[0].numpy()
							A_     :						Dict     =					np.amax(np.abs(out_a - out_a							)							)
							self.assertLessEqual(lowercase	,				1E-5							)







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


	def    _a     (self							):
				A_     :						Tuple     =					TFVisionTextDualEncoderModel.from_vision_text_pretrained(
				    """hf-internal-testing/tiny-random-vit"""	,				"""hf-internal-testing/tiny-random-bert"""							)
				A_     :						Dict     =					13
				A_     :						Tuple     =					floats_tensor(
				    [
				        batch_size,
				        model.vision_model.config.num_channels,
				        model.vision_model.config.image_size,
				        model.vision_model.config.image_size,
				    ]							)
				A_     :						Dict     =					ids_tensor([batch_size, 4]	,				model.text_model.config.vocab_size							)
				A_     :						Optional[Any]     =					random_attention_mask([batch_size, 4]							)
				A_     :						str     =					{"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

				return model, inputs


	def    _a     (self	,				lowercase	,				lowercase							):
				A_     :						Union[str, Any]     =					TFViTModel(lowercase	,				name="""vision_model"""							)
				A_     :						str     =					TFBertModel(lowercase	,				name="""text_model"""							)
				return vision_model, text_model


	def    _a     (self							):
				A_     :						Optional[int]     =					TFViTModelTester(self							)
				A_     :						Union[str, Any]     =					TFBertModelTester(self							)
				A_     :						List[str]     =					vit_model_tester.prepare_config_and_inputs()
				A_     :						List[Any]     =					bert_model_tester.prepare_config_and_inputs()

				A_     :						int     =					vision_config_and_inputs

				(
				    A_   
				)     :						int     =					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      _lowerCAmelCase							(      __UpperCAmelCase				,      unittest.TestCase			):


	def    _a     (self							):
				# DeiT repo doesn't have TF weights, but we don't actually use the weights at all so let's
				# just reinitialize it.
				A_     :						Union[str, Any]     =					TFVisionTextDualEncoderModel.from_vision_text_pretrained(
				    """Rocketknight1/tiny-random-deit-tf"""	,				"""hf-internal-testing/tiny-random-roberta"""							)
				A_     :						List[Any]     =					13
				A_     :						Optional[int]     =					floats_tensor(
				    [
				        batch_size,
				        model.vision_model.config.num_channels,
				        model.vision_model.config.image_size,
				        model.vision_model.config.image_size,
				    ]							)
				A_     :						str     =					ids_tensor([batch_size, 4]	,				model.text_model.config.vocab_size							)
				A_     :						Tuple     =					random_attention_mask([batch_size, 4]							)
				A_     :						Tuple     =					{"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

				return model, inputs


	def    _a     (self	,				lowercase	,				lowercase	,				lowercase	,				lowercase	,				lowercase=None	,				**lowercase							):
				A_     :						str     =					self.get_vision_text_model(lowercase	,				lowercase							)
				A_     :						int     =					TFVisionTextDualEncoderModel(vision_model=lowercase	,				text_model=lowercase							)

				A_     :						Dict     =					model(
				    input_ids=lowercase	,				pixel_values=lowercase	,				attention_mask=lowercase	,				output_attentions=lowercase							)

				A_     :						Optional[int]     =					output.vision_model_output.attentions
				self.assertEqual(len(lowercase							)	,				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)
				A_     :						List[str]     =					to_atuple(vision_model.config.image_size							)
				A_     :						int     =					to_atuple(vision_model.config.patch_size							)
				A_     :						Optional[Any]     =					(image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
				A_     :						int     =					num_patches + 2
				self.assertEqual(vision_attentions[0].shape[-3:]	,				(vision_config.num_attention_heads, seq_len, seq_len)							)

				A_     :						Tuple     =					output.text_model_output.attentions
				self.assertEqual(len(lowercase							)	,				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	,				lowercase	,				lowercase							):
				A_     :						Optional[Any]     =					TFDeiTModel(lowercase	,				name="""vision_model"""							)
				A_     :						Union[str, Any]     =					TFRobertaModel(lowercase	,				name="""text_model"""							)
				return vision_model, text_model


	def    _a     (self							):
				A_     :						Optional[int]     =					TFDeiTModelTester(self							)
				A_     :						Optional[int]     =					TFRobertaModelTester(self							)
				A_     :						Union[str, Any]     =					vit_model_tester.prepare_config_and_inputs()
				A_     :						Optional[Any]     =					bert_model_tester.prepare_config_and_inputs()

				A_     :						Tuple     =					vision_config_and_inputs

				(
				    A_   
				)     :						Optional[Any]     =					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      _lowerCAmelCase							(      __UpperCAmelCase				,      unittest.TestCase			):


	def    _a     (self							):
				A_     :						Optional[Any]     =					TFVisionTextDualEncoderModel.from_vision_text_pretrained(
				    """Rocketknight1/tiny-random-clip-tf"""	,				"""hf-internal-testing/tiny-random-bert"""							)
				A_     :						Union[str, Any]     =					13
				A_     :						str     =					floats_tensor(
				    [
				        batch_size,
				        model.vision_model.config.num_channels,
				        model.vision_model.config.image_size,
				        model.vision_model.config.image_size,
				    ]							)
				A_     :						List[str]     =					ids_tensor([batch_size, 4]	,				model.text_model.config.vocab_size							)
				A_     :						List[Any]     =					random_attention_mask([batch_size, 4]							)
				A_     :						Optional[int]     =					{"""pixel_values""": pixel_values, """input_ids""": input_ids, """attention_mask""": attention_mask}

				return model, inputs


	def    _a     (self	,				lowercase	,				lowercase							):
				A_     :						Optional[Any]     =					TFCLIPVisionModel(lowercase	,				name="""vision_model"""							)
				A_     :						int     =					TFBertModel(lowercase	,				name="""text_model"""							)
				return vision_model, text_model


	def    _a     (self							):
				A_     :						Optional[int]     =					TFCLIPVisionModelTester(self							)
				A_     :						List[str]     =					TFBertModelTester(self							)
				A_     :						Optional[int]     =					clip_model_tester.prepare_config_and_inputs()
				A_     :						List[Any]     =					bert_model_tester.prepare_config_and_inputs()

				A_     :						int     =					vision_config_and_inputs

				(
				    A_   
				)     :						Optional[int]     =					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      _lowerCAmelCase							(      unittest.TestCase			):


	@slow
	def    _a     (self							):
				A_     :						Optional[int]     =					TFVisionTextDualEncoderModel.from_pretrained(
				    """clip-italian/clip-italian"""	,				logit_scale_init_value=1.0	,				from_pt=lowercase							)
				A_     :						Optional[Any]     =					VisionTextDualEncoderProcessor.from_pretrained("""clip-italian/clip-italian"""							)

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

				A_     :						Optional[int]     =					model(**lowercase							)

				# 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])	,				)

				A_     :						int     =					np.array([[1.2_28_47_27, 0.3_10_41_22]]							)

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




'''simple docstring'''




from typing import TYPE_CHECKING

from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


lowerCamelCase							:Dict       = {'''configuration_mmbt''': ['''MMBTConfig''']}

try:
						if not is_torch_available():
												raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
						pass
else:
						lowerCamelCase							:str       = ['''MMBTForClassification''', '''MMBTModel''', '''ModalEmbeddings''']


if TYPE_CHECKING:
						from .configuration_mmbt import MMBTConfig

						try:
												if not is_torch_available():
																		raise OptionalDependencyNotAvailable()
						except OptionalDependencyNotAvailable:
												pass
						else:
												from .modeling_mmbt import MMBTForClassification, MMBTModel, ModalEmbeddings

else:
						import sys

						lowerCamelCase							:Tuple       = _LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)