





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	)		->					Dict:
 if isinstance(_lowerCAmelCase				,  collections.abc.Iterable	):
  return x
 return (x, x)



@require_tf
class    A__  :





      def 			__UpperCamelCase(					self			,				A_			,				A_  ):
       '''simple docstring'''




       pass





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       pass





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       pass





      def 			__UpperCamelCase(					self			,				A_			,				A_			,				A_			,				A_			,				A_=None			,				**A_  ):
       '''simple docstring'''




       UpperCamelCase      :   Optional[Any]			      =  VisionTextDualEncoderConfig.from_vision_text_configs(A_			,				A_  )

       UpperCamelCase      :   List[str]			      =  TFVisionTextDualEncoderModel(A_  )

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

       self.assertEqual(output["text_embeds"].shape			,				(input_ids.shape[0], config.projection_dim)  )
       self.assertEqual(output["image_embeds"].shape			,				(pixel_values.shape[0], config.projection_dim)  )





      def 			__UpperCamelCase(					self			,				A_			,				A_			,				A_			,				A_			,				A_=None			,				**A_  ):
       '''simple docstring'''




       UpperCamelCase      ,       UpperCamelCase      :   Optional[Any]			      =  self.get_vision_text_model(A_			,				A_  )
       UpperCamelCase      :   Any			      =  TFVisionTextDualEncoderModel(vision_model=A_			,				text_model=A_  )

       UpperCamelCase      :   Dict			      =  model(input_ids=A_			,				pixel_values=A_			,				attention_mask=A_  )

       self.assertEqual(output["text_embeds"].shape			,				(input_ids.shape[0], model.config.projection_dim)  )
       self.assertEqual(output["image_embeds"].shape			,				(pixel_values.shape[0], model.config.projection_dim)  )





      def 			__UpperCamelCase(					self			,				A_			,				A_			,				A_			,				A_			,				A_=None			,				**A_  ):
       '''simple docstring'''




       UpperCamelCase      ,       UpperCamelCase      :   Tuple			      =  self.get_vision_text_model(A_			,				A_  )
       UpperCamelCase      :   Tuple			      =  {"vision_model": vision_model, "text_model": text_model}
       UpperCamelCase      :   Optional[int]			      =  TFVisionTextDualEncoderModel.from_vision_text_pretrained(**A_  )

       UpperCamelCase      :   Optional[Any]			      =  model(input_ids=A_			,				pixel_values=A_			,				attention_mask=A_  )

       self.assertEqual(output["text_embeds"].shape			,				(input_ids.shape[0], model.config.projection_dim)  )
       self.assertEqual(output["image_embeds"].shape			,				(pixel_values.shape[0], model.config.projection_dim)  )





      def 			__UpperCamelCase(					self			,				A_			,				A_			,				A_			,				A_			,				A_=None			,				**A_  ):
       '''simple docstring'''




       UpperCamelCase      ,       UpperCamelCase      :   int			      =  self.get_vision_text_model(A_			,				A_  )
       UpperCamelCase      :   List[str]			      =  TFVisionTextDualEncoderModel(vision_model=A_			,				text_model=A_  )

       UpperCamelCase      :   Any			      =  model(input_ids=A_			,				pixel_values=A_			,				attention_mask=A_  )
       UpperCamelCase      :   Tuple			      =  output[0].numpy()

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

        UpperCamelCase      :   List[Any]			      =  model(input_ids=A_			,				pixel_values=A_			,				attention_mask=A_  )
        UpperCamelCase      :   List[Any]			      =  after_output[0].numpy()
        UpperCamelCase      :   List[Any]			      =  np.amax(np.abs(out_a - out_a  )  )
        self.assertLessEqual(A_			,				1e-5  )





      def 			__UpperCamelCase(					self			,				A_			,				A_			,				A_			,				A_			,				A_=None			,				**A_  ):
       '''simple docstring'''




       UpperCamelCase      ,       UpperCamelCase      :   Tuple			      =  self.get_vision_text_model(A_			,				A_  )
       UpperCamelCase      :   Union[str, Any]			      =  TFVisionTextDualEncoderModel(vision_model=A_			,				text_model=A_  )

       UpperCamelCase      :   Optional[Any]			      =  model(
           input_ids=A_			,				pixel_values=A_			,				attention_mask=A_			,				output_attentions=A_  )

       UpperCamelCase      :   Optional[int]			      =  output.vision_model_output.attentions
       self.assertEqual(len(A_  )			,				vision_config.num_hidden_layers  )

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

       UpperCamelCase      :   Optional[int]			      =  output.text_model_output.attentions
       self.assertEqual(len(A_  )			,				text_config.num_hidden_layers  )

       self.assertEqual(
           text_attentions[0].shape[-3:]			,				(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])			,				)





      def 			__UpperCamelCase(					self			,				A_			,				A_			,				A_  ):
       '''simple docstring'''




       UpperCamelCase      :   Optional[int]			      =  np.abs((a - b)  ).max()
       self.assertLessEqual(A_			,				A_			,				F"""Difference between torch and flax is {diff} (>= {tol})."""  )





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   Tuple			      =  self.prepare_config_and_inputs()
       self.check_vision_text_dual_encoder_model(**A_  )





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   Optional[int]			      =  self.prepare_config_and_inputs()
       self.check_model_from_pretrained_configs(**A_  )





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   int			      =  self.prepare_config_and_inputs()
       self.check_vision_text_dual_encoder_from_pretrained(**A_  )





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   Optional[Any]			      =  self.prepare_config_and_inputs()
       self.check_save_load(**A_  )





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   int			      =  self.prepare_config_and_inputs()
       self.check_vision_text_output_attention(**A_  )





      @slow
      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      ,       UpperCamelCase      :   Optional[Any]			      =  self.get_pretrained_model_and_inputs()

       UpperCamelCase      :   Tuple			      =  model_a(**A_  )
       UpperCamelCase      :   Any			      =  outputs[0].numpy()

       with tempfile.TemporaryDirectory() as tmp_dirname:
        model_a.save_pretrained(A_  )
        UpperCamelCase      :   str			      =  TFVisionTextDualEncoderModel.from_pretrained(A_  )

        UpperCamelCase      :   int			      =  model_a(**A_  )
        UpperCamelCase      :   int			      =  after_outputs[0].numpy()
        UpperCamelCase      :   str			      =  np.amax(np.abs(out_a - out_a  )  )
        self.assertLessEqual(A_			,				1e-5  )



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





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




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

       return model, inputs





      def 			__UpperCamelCase(					self			,				A_			,				A_  ):
       '''simple docstring'''




       UpperCamelCase      :   Dict			      =  TFViTModel(A_			,				name="vision_model"  )
       UpperCamelCase      :   List[str]			      =  TFBertModel(A_			,				name="text_model"  )
       return vision_model, text_model





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   str			      =  TFViTModelTester(self  )
       UpperCamelCase      :   Tuple			      =  TFBertModelTester(self  )
       UpperCamelCase      :   str			      =  vit_model_tester.prepare_config_and_inputs()
       UpperCamelCase      :   str			      =  bert_model_tester.prepare_config_and_inputs()

       UpperCamelCase      ,       UpperCamelCase      ,       UpperCamelCase      :   Tuple			      =  vision_config_and_inputs

       (
           (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       
       )      :   Dict			      =  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__  (			__snake_case			,  unittest.TestCase     ):





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




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

       return model, inputs





      def 			__UpperCamelCase(					self			,				A_			,				A_			,				A_			,				A_			,				A_=None			,				**A_  ):
       '''simple docstring'''




       UpperCamelCase      ,       UpperCamelCase      :   Union[str, Any]			      =  self.get_vision_text_model(A_			,				A_  )
       UpperCamelCase      :   List[str]			      =  TFVisionTextDualEncoderModel(vision_model=A_			,				text_model=A_  )

       UpperCamelCase      :   int			      =  model(
           input_ids=A_			,				pixel_values=A_			,				attention_mask=A_			,				output_attentions=A_  )

       UpperCamelCase      :   str			      =  output.vision_model_output.attentions
       self.assertEqual(len(A_  )			,				vision_config.num_hidden_layers  )

       # in DEiT, the seq_len equals the number of patches + 2 (we add 2 for the [CLS] and distillation tokens)
       UpperCamelCase      :   List[Any]			      =  to_atuple(vision_model.config.image_size  )
       UpperCamelCase      :   Any			      =  to_atuple(vision_model.config.patch_size  )
       UpperCamelCase      :   Union[str, Any]			      =  (image_size[1] // patch_size[1]) * (image_size[0] // patch_size[0])
       UpperCamelCase      :   Tuple			      =  num_patches + 2
       self.assertEqual(vision_attentions[0].shape[-3:]			,				(vision_config.num_attention_heads, seq_len, seq_len)  )

       UpperCamelCase      :   List[str]			      =  output.text_model_output.attentions
       self.assertEqual(len(A_  )			,				text_config.num_hidden_layers  )

       self.assertEqual(
           text_attentions[0].shape[-3:]			,				(text_config.num_attention_heads, input_ids.shape[-1], input_ids.shape[-1])			,				)





      def 			__UpperCamelCase(					self			,				A_			,				A_  ):
       '''simple docstring'''




       UpperCamelCase      :   Union[str, Any]			      =  TFDeiTModel(A_			,				name="vision_model"  )
       UpperCamelCase      :   str			      =  TFRobertaModel(A_			,				name="text_model"  )
       return vision_model, text_model





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   int			      =  TFDeiTModelTester(self  )
       UpperCamelCase      :   Optional[Any]			      =  TFRobertaModelTester(self  )
       UpperCamelCase      :   Tuple			      =  vit_model_tester.prepare_config_and_inputs()
       UpperCamelCase      :   Any			      =  bert_model_tester.prepare_config_and_inputs()

       UpperCamelCase      ,       UpperCamelCase      ,       UpperCamelCase      :   Tuple			      =  vision_config_and_inputs

       (
           (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       
       )      :   List[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__  (			__snake_case			,  unittest.TestCase     ):





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




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

       return model, inputs





      def 			__UpperCamelCase(					self			,				A_			,				A_  ):
       '''simple docstring'''




       UpperCamelCase      :   Dict			      =  TFCLIPVisionModel(A_			,				name="vision_model"  )
       UpperCamelCase      :   Optional[Any]			      =  TFBertModel(A_			,				name="text_model"  )
       return vision_model, text_model





      def 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   Optional[int]			      =  TFCLIPVisionModelTester(self  )
       UpperCamelCase      :   Optional[Any]			      =  TFBertModelTester(self  )
       UpperCamelCase      :   Tuple			      =  clip_model_tester.prepare_config_and_inputs()
       UpperCamelCase      :   List[str]			      =  bert_model_tester.prepare_config_and_inputs()

       UpperCamelCase      ,       UpperCamelCase      :   str			      =  vision_config_and_inputs

       (
           (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       (
           UpperCamelCase
       )      ,       
       )      :   str			      =  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 			__UpperCamelCase(					self  ):
       '''simple docstring'''




       UpperCamelCase      :   int			      =  TFVisionTextDualEncoderModel.from_pretrained(
           "clip-italian/clip-italian"			,				logit_scale_init_value=1.0			,				from_pt=A_  )
       UpperCamelCase      :   Dict			      =  VisionTextDualEncoderProcessor.from_pretrained("clip-italian/clip-italian"  )

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

       UpperCamelCase      :   Dict			      =  model(**A_  )

       # verify the logits
       self.assertEqual(outputs.logits_per_image.shape			,				(inputs.pixel_values.shape[0], inputs.input_ids.shape[0])  )
       self.assertEqual(
           outputs.logits_per_text.shape			,				(inputs.input_ids.shape[0], inputs.pixel_values.shape[0])			,				)

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

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







from typing import TYPE_CHECKING

from ...utils import _LazyModule


__lowerCamelCase			:	str					    =	{"""tokenization_byt5""": ["""ByT5Tokenizer"""]}


if TYPE_CHECKING:
    from .tokenization_byta import ByTaTokenizer
else:
    import sys

    __lowerCamelCase			:	List[str]					    =	_LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)
