
"""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    __lowerCAmelCase    (_UpperCamelCase		):
	if isinstance(UpperCAmelCase__	,  collections.abc.Iterable		):
		return x
	return (x, x)




@require_tf
class 			A__	:

		def 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE			):
			pass

		def 							__lowerCamelCase							(				self			):
			pass

		def 							__lowerCamelCase							(				self			):
			pass

		def 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE=None	,		**_SCREAMING_SNAKE_CASE			):
			__lowerCAmelCase      :						Any						      =				VisionTextDualEncoderConfig.from_vision_text_configs(lowercase_	,		lowercase_			)

			__lowerCAmelCase      :						Dict						      =				TFVisionTextDualEncoderModel(lowercase_			)

			__lowerCAmelCase      :						int						      =				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 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE=None	,		**_SCREAMING_SNAKE_CASE			):
			__lowerCAmelCase      :						Optional[int]						      =				self.get_vision_text_model(lowercase_	,		lowercase_			)
			__lowerCAmelCase      :						Union[str, Any]						      =				TFVisionTextDualEncoderModel(vision_model=lowercase_	,		text_model=lowercase_			)

			__lowerCAmelCase      :						Union[str, Any]						      =				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 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE=None	,		**_SCREAMING_SNAKE_CASE			):
			__lowerCAmelCase      :						str						      =				self.get_vision_text_model(lowercase_	,		lowercase_			)
			__lowerCAmelCase      :						List[str]						      =				{"""vision_model""": vision_model, """text_model""": text_model}
			__lowerCAmelCase      :						List[str]						      =				TFVisionTextDualEncoderModel.from_vision_text_pretrained(**lowercase_			)

			__lowerCAmelCase      :						Tuple						      =				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 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE=None	,		**_SCREAMING_SNAKE_CASE			):
			__lowerCAmelCase      :						Tuple						      =				self.get_vision_text_model(lowercase_	,		lowercase_			)
			__lowerCAmelCase      :						Optional[int]						      =				TFVisionTextDualEncoderModel(vision_model=lowercase_	,		text_model=lowercase_			)

			__lowerCAmelCase      :						int						      =				model(input_ids=lowercase_	,		pixel_values=lowercase_	,		attention_mask=lowercase_			)
			__lowerCAmelCase      :						str						      =				output[0].numpy()

			with tempfile.TemporaryDirectory() as tmpdirname:
				model.save_pretrained(lowercase_			)
				__lowerCAmelCase      :						List[Any]						      =				TFVisionTextDualEncoderModel.from_pretrained(lowercase_			)

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

		def 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE=None	,		**_SCREAMING_SNAKE_CASE			):
			__lowerCAmelCase      :						List[str]						      =				self.get_vision_text_model(lowercase_	,		lowercase_			)
			__lowerCAmelCase      :						Any						      =				TFVisionTextDualEncoderModel(vision_model=lowercase_	,		text_model=lowercase_			)

			__lowerCAmelCase      :						Optional[int]						      =				model(
			    input_ids=lowercase_	,		pixel_values=lowercase_	,		attention_mask=lowercase_	,		output_attentions=lowercase_			)

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

			__lowerCAmelCase      :						Optional[int]						      =				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 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE			):
			__lowerCAmelCase      :						str						      =				np.abs((a - b)			).max()
			self.assertLessEqual(lowercase_	,		lowercase_	,		f"Difference between torch and flax is {diff} (>= {tol})."			)

		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						str						      =				self.prepare_config_and_inputs()
			self.check_vision_text_dual_encoder_model(**lowercase_			)

		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						Dict						      =				self.prepare_config_and_inputs()
			self.check_model_from_pretrained_configs(**lowercase_			)

		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						Dict						      =				self.prepare_config_and_inputs()
			self.check_vision_text_dual_encoder_from_pretrained(**lowercase_			)

		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						Dict						      =				self.prepare_config_and_inputs()
			self.check_save_load(**lowercase_			)

		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						List[Any]						      =				self.prepare_config_and_inputs()
			self.check_vision_text_output_attention(**lowercase_			)







		@slow
		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						Tuple						      =				self.get_pretrained_model_and_inputs()

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

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

				__lowerCAmelCase      :						int						      =				model_a(**lowercase_			)
				__lowerCAmelCase      :						str						      =				after_outputs[0].numpy()
				__lowerCAmelCase      :						Dict						      =				np.amax(np.abs(out_a - out_a			)			)
				self.assertLessEqual(lowercase_	,		1E-5			)




@require_tf
class 			A__	(     _UpperCAmelCase	,					unittest.TestCase):

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

			return model, inputs

		def 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE			):
			__lowerCAmelCase      :						Any						      =				TFViTModel(lowercase_	,		name='vision_model'			)
			__lowerCAmelCase      :						Optional[Any]						      =				TFBertModel(lowercase_	,		name='text_model'			)
			return vision_model, text_model







		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						Optional[int]						      =				TFViTModelTester(self			)
			__lowerCAmelCase      :						Tuple						      =				TFBertModelTester(self			)
			__lowerCAmelCase      :						Optional[int]						      =				vit_model_tester.prepare_config_and_inputs()
			__lowerCAmelCase      :						Union[str, Any]						      =				bert_model_tester.prepare_config_and_inputs()

			__lowerCAmelCase      :						Tuple						      =				vision_config_and_inputs

			(
			    __lowerCAmelCase						
			)      :						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 			A__	(     _UpperCAmelCase	,					unittest.TestCase):

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

			return model, inputs

		def 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE=None	,		**_SCREAMING_SNAKE_CASE			):
			__lowerCAmelCase      :						Any						      =				self.get_vision_text_model(lowercase_	,		lowercase_			)
			__lowerCAmelCase      :						Dict						      =				TFVisionTextDualEncoderModel(vision_model=lowercase_	,		text_model=lowercase_			)

			__lowerCAmelCase      :						int						      =				model(
			    input_ids=lowercase_	,		pixel_values=lowercase_	,		attention_mask=lowercase_	,		output_attentions=lowercase_			)

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

			__lowerCAmelCase      :						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 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE			):
			__lowerCAmelCase      :						Dict						      =				TFDeiTModel(lowercase_	,		name='vision_model'			)
			__lowerCAmelCase      :						Tuple						      =				TFRobertaModel(lowercase_	,		name='text_model'			)
			return vision_model, text_model







		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						Optional[Any]						      =				TFDeiTModelTester(self			)
			__lowerCAmelCase      :						int						      =				TFRobertaModelTester(self			)
			__lowerCAmelCase      :						Optional[int]						      =				vit_model_tester.prepare_config_and_inputs()
			__lowerCAmelCase      :						int						      =				bert_model_tester.prepare_config_and_inputs()

			__lowerCAmelCase      :						int						      =				vision_config_and_inputs

			(
			    __lowerCAmelCase						
			)      :						Tuple						      =				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 			A__	(     _UpperCAmelCase	,					unittest.TestCase):

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

			return model, inputs

		def 							__lowerCamelCase							(				self	,		_SCREAMING_SNAKE_CASE	,		_SCREAMING_SNAKE_CASE			):
			__lowerCAmelCase      :						Dict						      =				TFCLIPVisionModel(lowercase_	,		name='vision_model'			)
			__lowerCAmelCase      :						Dict						      =				TFBertModel(lowercase_	,		name='text_model'			)
			return vision_model, text_model







		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						Optional[int]						      =				TFCLIPVisionModelTester(self			)
			__lowerCAmelCase      :						Union[str, Any]						      =				TFBertModelTester(self			)
			__lowerCAmelCase      :						int						      =				clip_model_tester.prepare_config_and_inputs()
			__lowerCAmelCase      :						Dict						      =				bert_model_tester.prepare_config_and_inputs()

			__lowerCAmelCase      :						int						      =				vision_config_and_inputs

			(
			    __lowerCAmelCase						
			)      :						Tuple						      =				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 			A__	(     unittest.TestCase):

		@slow
		def 							__lowerCamelCase							(				self			):
			__lowerCAmelCase      :						Tuple						      =				TFVisionTextDualEncoderModel.from_pretrained(
			    'clip-italian/clip-italian'	,		logit_scale_init_value=1.0	,		from_pt=lowercase_			)
			__lowerCAmelCase      :						Optional[Any]						      =				VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian'			)

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

			__lowerCAmelCase      :						Dict						      =				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])	,		)

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

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

"""simple docstring"""







lowerCamelCase__        =		"""0.21.0"""

from .accelerator import Accelerator
from .big_modeling import (
    cpu_offload,
    cpu_offload_with_hook,
    disk_offload,
    dispatch_model,
    init_empty_weights,
    init_on_device,
    load_checkpoint_and_dispatch,
)
from .data_loader import skip_first_batches
from .launchers import debug_launcher, notebook_launcher
from .state import PartialState
from .utils import (
    DeepSpeedPlugin,
    DistributedDataParallelKwargs,
    DistributedType,
    FullyShardedDataParallelPlugin,
    GradScalerKwargs,
    InitProcessGroupKwargs,
    find_executable_batch_size,
    infer_auto_device_map,
    is_rich_available,
    load_checkpoint_in_model,
    synchronize_rng_states,
)


if is_rich_available():
							from .utils import rich