





import json
import os
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import BatchEncoding, PreTrainedTokenizer
from ...utils import logging


lowercase				:	Optional[int]      						=  logging.get_logger(__name__)

lowercase				:	Dict      						=  """▁"""

lowercase				:	List[Any]      						=  {
    """vocab_file""": """vocab.json""",
    """spm_file""": """sentencepiece.bpe.model""",
    """tokenizer_config_file""": """tokenizer_config.json""",
}

lowercase				:	List[str]      						=  {
    """vocab_file""": {
        """facebook/m2m100_418M""": """https://huggingface.co/facebook/m2m100_418M/resolve/main/vocab.json""",
        """facebook/m2m100_1.2B""": """https://huggingface.co/facebook/m2m100_1.2B/resolve/main/vocab.json""",
    },
    """spm_file""": {
        """facebook/m2m100_418M""": """https://huggingface.co/facebook/m2m100_418M/resolve/main/sentencepiece.bpe.model""",
        """facebook/m2m100_1.2B""": """https://huggingface.co/facebook/m2m100_1.2B/resolve/main/sentencepiece.bpe.model""",
    },
    """tokenizer_config_file""": {
        """facebook/m2m100_418M""": """https://huggingface.co/facebook/m2m100_418M/resolve/main/tokenizer_config.json""",
        """facebook/m2m100_1.2B""": """https://huggingface.co/facebook/m2m100_1.2B/resolve/main/tokenizer_config.json""",
    },
}

lowercase				:	str      						=  {
    """facebook/m2m100_418M""": 1_0_2_4,
}

# fmt: off
lowercase				:	List[str]      						=  {
    """m2m100""": ["""af""", """am""", """ar""", """ast""", """az""", """ba""", """be""", """bg""", """bn""", """br""", """bs""", """ca""", """ceb""", """cs""", """cy""", """da""", """de""", """el""", """en""", """es""", """et""", """fa""", """ff""", """fi""", """fr""", """fy""", """ga""", """gd""", """gl""", """gu""", """ha""", """he""", """hi""", """hr""", """ht""", """hu""", """hy""", """id""", """ig""", """ilo""", """is""", """it""", """ja""", """jv""", """ka""", """kk""", """km""", """kn""", """ko""", """lb""", """lg""", """ln""", """lo""", """lt""", """lv""", """mg""", """mk""", """ml""", """mn""", """mr""", """ms""", """my""", """ne""", """nl""", """no""", """ns""", """oc""", """or""", """pa""", """pl""", """ps""", """pt""", """ro""", """ru""", """sd""", """si""", """sk""", """sl""", """so""", """sq""", """sr""", """ss""", """su""", """sv""", """sw""", """ta""", """th""", """tl""", """tn""", """tr""", """uk""", """ur""", """uz""", """vi""", """wo""", """xh""", """yi""", """yo""", """zh""", """zu"""],
    """wmt21""": ["""en""", """ha""", """is""", """ja""", """cs""", """ru""", """zh""", """de"""]
}





class 			A__   (							__UpperCAmelCase     ):




   """simple docstring"""



   __A       :    Optional[int]	  =  VOCAB_FILES_NAMES
   __A       :    Any	  =  PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   __A       :    Any	  =  PRETRAINED_VOCAB_FILES_MAP
   __A       :    Optional[Any]	  =  ['''input_ids''', '''attention_mask''']

   __A       :    List[int]	  =  []
   __A       :    List[int]	  =  []

   def __init__( self ,  lowercase ,  lowercase ,  lowercase=None ,  lowercase=None ,  lowercase="<s>" ,  lowercase="</s>" ,  lowercase="</s>" ,  lowercase="<pad>" ,  lowercase="<unk>" ,  lowercase="m2m100" ,  lowercase = None ,  lowercase=8 ,  **lowercase ,  )      ->						None:







          '''simple docstring'''

          a__						:     Tuple			=    {} if sp_model_kwargs is None else sp_model_kwargs

          a__						:     Any			=    language_codes
          a__						:     Dict			=    FAIRSEQ_LANGUAGE_CODES[language_codes]
          a__						:     str			=    {lang_code: F'__{lang_code}__' for lang_code in fairseq_language_code}

          a__						:     Any			=    kwargs.get('additional_special_tokens' ,  [])
          kwargs["additional_special_tokens"] += [
              self.get_lang_token(lowercase)
              for lang_code in fairseq_language_code
              if self.get_lang_token(lowercase) not in kwargs["additional_special_tokens"]
          ]

          super().__init__(
              src_lang=lowercase ,  tgt_lang=lowercase ,  bos_token=lowercase ,  eos_token=lowercase ,  sep_token=lowercase ,  unk_token=lowercase ,  pad_token=lowercase ,  language_codes=lowercase ,  sp_model_kwargs=self.sp_model_kwargs ,  num_madeup_words=lowercase ,  **lowercase ,  )

          a__						:     Union[str, Any]			=    vocab_file
          a__						:     Any			=    load_json(lowercase)
          a__						:     List[str]			=    {v: k for k, v in self.encoder.items()}
          a__						:     List[str]			=    spm_file
          a__						:     Any			=    load_spm(lowercase ,  self.sp_model_kwargs)

          a__						:     List[str]			=    len(self.encoder)

          a__						:     Dict			=    {
              self.get_lang_token(lowercase): self.encoder_size + i for i, lang_code in enumerate(lowercase)
          }
          a__						:     Tuple			=    {lang_code: self.encoder_size + i for i, lang_code in enumerate(lowercase)}
          a__						:     Optional[Any]			=    {v: k for k, v in self.lang_token_to_id.items()}

          a__						:     Tuple			=    src_lang if src_lang is not None else 'en'
          a__						:     Tuple			=    tgt_lang
          a__						:     Union[str, Any]			=    self.get_lang_id(self._src_lang)
          self.set_src_lang_special_tokens(self._src_lang)

          a__						:     Dict			=    num_madeup_words

   @property
   def 							__lowercase		( self)      ->						int:







          '''simple docstring'''

          return len(self.encoder) + len(self.lang_token_to_id)

   @property
   def 							__lowercase		( self)      ->						str:







          '''simple docstring'''

          return self._src_lang

   @src_lang.setter
   def 							__lowercase		( self ,  lowercase)      ->						None:







          '''simple docstring'''

          a__						:     Tuple			=    new_src_lang
          self.set_src_lang_special_tokens(self._src_lang)

   def 							__lowercase		( self ,  lowercase)      ->						List[str]:







          '''simple docstring'''

          return self.sp_model.encode(lowercase ,  out_type=lowercase)

   def 							__lowercase		( self ,  lowercase)      ->						List[Any]:







          '''simple docstring'''

          if token in self.lang_token_to_id:
                 return self.lang_token_to_id[token]
          return self.encoder.get(lowercase ,  self.encoder[self.unk_token])

   def 							__lowercase		( self ,  lowercase)      ->						str:







          '''simple docstring'''

          if index in self.id_to_lang_token:
                 return self.id_to_lang_token[index]
          return self.decoder.get(lowercase ,  self.unk_token)

   def 							__lowercase		( self ,  lowercase)      ->						Tuple:







          '''simple docstring'''

          a__						:     Optional[Any]			=    []
          a__						:     int			=    ''
          for token in tokens:
                 # make sure that special tokens are not decoded using sentencepiece model
                 if token in self.all_special_tokens:
                        out_string += self.sp_model.decode(lowercase) + token
                        a__						:     List[str]			=    []
                 else:
                        current_sub_tokens.append(lowercase)
          out_string += self.sp_model.decode(lowercase)
          return out_string.strip()

   def 							__lowercase		( self ,  lowercase ,  lowercase = None ,  lowercase = False)      ->						List[int]:







          '''simple docstring'''

          if already_has_special_tokens:
                 return super().get_special_tokens_mask(
                     token_ids_a=lowercase ,  token_ids_a=lowercase ,  already_has_special_tokens=lowercase)

          a__						:     Tuple			=    [1] * len(self.prefix_tokens)
          a__						:     int			=    [1] * len(self.suffix_tokens)
          if token_ids_a is None:
                 return prefix_ones + ([0] * len(lowercase)) + suffix_ones
          return prefix_ones + ([0] * len(lowercase)) + ([0] * len(lowercase)) + suffix_ones

   def 							__lowercase		( self ,  lowercase ,  lowercase = None)      ->						List[int]:







          '''simple docstring'''

          if token_ids_a is None:
                 return self.prefix_tokens + token_ids_a + self.suffix_tokens
          # We don't expect to process pairs, but leave the pair logic for API consistency
          return self.prefix_tokens + token_ids_a + token_ids_a + self.suffix_tokens

   def 							__lowercase		( self)      ->						Dict:







          '''simple docstring'''

          a__						:     Union[str, Any]			=    {self.convert_ids_to_tokens(lowercase): i for i in range(self.vocab_size)}
          vocab.update(self.added_tokens_encoder)
          return vocab

   def __getstate__( self)      ->						Dict:







          '''simple docstring'''

          a__						:     str			=    self.__dict__.copy()
          a__						:     List[str]			=    None
          return state

   def __setstate__( self ,  lowercase)      ->						None:







          '''simple docstring'''

          a__						:     Union[str, Any]			=    d

          # for backward compatibility
          if not hasattr(self ,  'sp_model_kwargs'):
                 a__						:     List[str]			=    {}

          a__						:     Union[str, Any]			=    load_spm(self.spm_file ,  self.sp_model_kwargs)

   def 							__lowercase		( self ,  lowercase ,  lowercase = None)      ->						Tuple[str]:







          '''simple docstring'''

          a__						:     Optional[int]			=    Path(lowercase)
          if not save_dir.is_dir():
                 raise OSError(F'{save_directory} should be a directory')
          a__						:     Any			=    save_dir / (
              (filename_prefix + '-' if filename_prefix else '') + self.vocab_files_names['vocab_file']
          )
          a__						:     Union[str, Any]			=    save_dir / (
              (filename_prefix + '-' if filename_prefix else '') + self.vocab_files_names['spm_file']
          )

          save_json(self.encoder ,  lowercase)

          if os.path.abspath(self.spm_file) != os.path.abspath(lowercase) and os.path.isfile(self.spm_file):
                 copyfile(self.spm_file ,  lowercase)
          elif not os.path.isfile(self.spm_file):
                 with open(lowercase ,  'wb') as fi:
                        a__						:     Any			=    self.sp_model.serialized_model_proto()
                        fi.write(lowercase)

          return (str(lowercase), str(lowercase))

   def 							__lowercase		( self ,  lowercase ,  lowercase = "en" ,  lowercase = None ,  lowercase = "ro" ,  **lowercase ,  )      ->						BatchEncoding:







          '''simple docstring'''

          a__						:     Optional[Any]			=    src_lang
          a__						:     List[Any]			=    tgt_lang
          self.set_src_lang_special_tokens(self.src_lang)
          return super().prepare_seqaseq_batch(lowercase ,  lowercase ,  **lowercase)

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  **lowercase)      ->						List[str]:







          '''simple docstring'''

          if src_lang is None or tgt_lang is None:
                 raise ValueError('Translation requires a `src_lang` and a `tgt_lang` for this model')
          a__						:     int			=    src_lang
          a__						:     Tuple			=    self(lowercase ,  add_special_tokens=lowercase ,  **lowercase)
          a__						:     Optional[Any]			=    self.get_lang_id(lowercase)
          a__						:     List[Any]			=    tgt_lang_id
          return inputs

   def 							__lowercase		( self)      ->						Tuple:







          '''simple docstring'''

          self.set_src_lang_special_tokens(self.src_lang)

   def 							__lowercase		( self)      ->						Tuple:







          '''simple docstring'''

          self.set_tgt_lang_special_tokens(self.tgt_lang)

   def 							__lowercase		( self ,  lowercase)      ->						None:







          '''simple docstring'''

          a__						:     Any			=    self.get_lang_token(lowercase)
          a__						:     Optional[Any]			=    self.lang_token_to_id[lang_token]
          a__						:     List[str]			=    [self.cur_lang_id]
          a__						:     Any			=    [self.eos_token_id]

   def 							__lowercase		( self ,  lowercase)      ->						None:







          '''simple docstring'''

          a__						:     Optional[Any]			=    self.get_lang_token(lowercase)
          a__						:     Tuple			=    self.lang_token_to_id[lang_token]
          a__						:     List[str]			=    [self.cur_lang_id]
          a__						:     Tuple			=    [self.eos_token_id]

   def 							__lowercase		( self ,  lowercase)      ->						str:







          '''simple docstring'''

          return self.lang_code_to_token[lang]

   def 							__lowercase		( self ,  lowercase)      ->						int:







          '''simple docstring'''

          a__						:     str			=    self.get_lang_token(lowercase)
          return self.lang_token_to_id[lang_token]



def A_     (		A__		,				A__    )  ->		sentencepiece.SentencePieceProcessor:
       a__						:     Optional[Any]			=    sentencepiece.SentencePieceProcessor(**A__    )
       spm.Load(str(A__    )    )
       return spm



def A_     (		A__    )  ->		Union[Dict, List]:
       with open(A__		,				'r'    ) as f:
              return json.load(A__    )



def A_     (		A__		,				A__    )  ->		None:
       with open(A__		,				'w'    ) as f:
              json.dump(A__		,				A__		,				indent=2    )









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





@require_tf
class 			A__   :




   """simple docstring"""



   def 							__lowercase		( self ,  lowercase ,  lowercase)      ->						Union[str, Any]:







          '''simple docstring'''

          pass

   def 							__lowercase		( self)      ->						Dict:







          '''simple docstring'''

          pass

   def 							__lowercase		( self)      ->						Dict:







          '''simple docstring'''

          pass

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None ,  **lowercase)      ->						List[Any]:







          '''simple docstring'''

          a__						:     Any			=    VisionTextDualEncoderConfig.from_vision_text_configs(lowercase ,  lowercase)

          a__						:     Any			=    TFVisionTextDualEncoderModel(lowercase)

          a__						:     Dict			=    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 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None ,  **lowercase)      ->						List[Any]:







          '''simple docstring'''

          a__			,							a__						:     List[Any]			=    self.get_vision_text_model(lowercase ,  lowercase)
          a__						:     List[str]			=    TFVisionTextDualEncoderModel(vision_model=lowercase ,  text_model=lowercase)

          a__						:     Dict			=    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 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None ,  **lowercase)      ->						Tuple:







          '''simple docstring'''

          a__			,							a__						:     Any			=    self.get_vision_text_model(lowercase ,  lowercase)
          a__						:     Tuple			=    {'vision_model': vision_model, 'text_model': text_model}
          a__						:     Union[str, Any]			=    TFVisionTextDualEncoderModel.from_vision_text_pretrained(**lowercase)

          a__						:     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 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None ,  **lowercase)      ->						Optional[Any]:







          '''simple docstring'''

          a__			,							a__						:     int			=    self.get_vision_text_model(lowercase ,  lowercase)
          a__						:     List[Any]			=    TFVisionTextDualEncoderModel(vision_model=lowercase ,  text_model=lowercase)

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

          with tempfile.TemporaryDirectory() as tmpdirname:
                 model.save_pretrained(lowercase)
                 a__						:     str			=    TFVisionTextDualEncoderModel.from_pretrained(lowercase)

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

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None ,  **lowercase)      ->						Optional[int]:







          '''simple docstring'''

          a__			,							a__						:     Optional[Any]			=    self.get_vision_text_model(lowercase ,  lowercase)
          a__						:     Dict			=    TFVisionTextDualEncoderModel(vision_model=lowercase ,  text_model=lowercase)

          a__						:     Optional[int]			=    model(
              input_ids=lowercase ,  pixel_values=lowercase ,  attention_mask=lowercase ,  output_attentions=lowercase)

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

          a__						:     Union[str, Any]			=    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 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase)      ->						Any:







          '''simple docstring'''

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

   def 							__lowercase		( self)      ->						Optional[Any]:







          '''simple docstring'''

          a__						:     List[Any]			=    self.prepare_config_and_inputs()
          self.check_vision_text_dual_encoder_model(**lowercase)

   def 							__lowercase		( self)      ->						Dict:







          '''simple docstring'''

          a__						:     List[Any]			=    self.prepare_config_and_inputs()
          self.check_model_from_pretrained_configs(**lowercase)

   def 							__lowercase		( self)      ->						Tuple:







          '''simple docstring'''

          a__						:     Any			=    self.prepare_config_and_inputs()
          self.check_vision_text_dual_encoder_from_pretrained(**lowercase)

   def 							__lowercase		( self)      ->						Optional[Any]:







          '''simple docstring'''

          a__						:     int			=    self.prepare_config_and_inputs()
          self.check_save_load(**lowercase)

   def 							__lowercase		( self)      ->						Optional[int]:







          '''simple docstring'''

          a__						:     List[str]			=    self.prepare_config_and_inputs()
          self.check_vision_text_output_attention(**lowercase)

   @slow
   def 							__lowercase		( self)      ->						Union[str, Any]:







          '''simple docstring'''

          a__			,							a__						:     Union[str, Any]			=    self.get_pretrained_model_and_inputs()

          a__						:     Optional[int]			=    model_a(**lowercase)
          a__						:     int			=    outputs[0].numpy()

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

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





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




   """simple docstring"""



   def 							__lowercase		( self)      ->						List[Any]:







          '''simple docstring'''

          a__						:     Any			=    TFVisionTextDualEncoderModel.from_vision_text_pretrained(
              'hf-internal-testing/tiny-random-vit' ,  'hf-internal-testing/tiny-random-bert')
          a__						:     str			=    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__						:     Tuple			=    ids_tensor([batch_size, 4] ,  model.text_model.config.vocab_size)
          a__						:     Optional[int]			=    random_attention_mask([batch_size, 4])
          a__						:     str			=    {'pixel_values': pixel_values, 'input_ids': input_ids, 'attention_mask': attention_mask}

          return model, inputs

   def 							__lowercase		( self ,  lowercase ,  lowercase)      ->						List[Any]:







          '''simple docstring'''

          a__						:     Optional[Any]			=    TFViTModel(lowercase ,  name='vision_model')
          a__						:     Tuple			=    TFBertModel(lowercase ,  name='text_model')
          return vision_model, text_model

   def 							__lowercase		( self)      ->						Any:







          '''simple docstring'''

          a__						:     Tuple			=    TFViTModelTester(self)
          a__						:     int			=    TFBertModelTester(self)
          a__						:     Optional[Any]			=    vit_model_tester.prepare_config_and_inputs()
          a__						:     Any			=    bert_model_tester.prepare_config_and_inputs()

          a__			,							a__			,							a__						:     Optional[int]			=    vision_config_and_inputs

          (
              (
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							
          )						:     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     ):




   """simple docstring"""



   def 							__lowercase		( self)      ->						List[str]:







          '''simple docstring'''

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

          return model, inputs

   def 							__lowercase		( self ,  lowercase ,  lowercase ,  lowercase ,  lowercase ,  lowercase=None ,  **lowercase)      ->						Optional[Any]:







          '''simple docstring'''

          a__			,							a__						:     List[Any]			=    self.get_vision_text_model(lowercase ,  lowercase)
          a__						:     Any			=    TFVisionTextDualEncoderModel(vision_model=lowercase ,  text_model=lowercase)

          a__						:     int			=    model(
              input_ids=lowercase ,  pixel_values=lowercase ,  attention_mask=lowercase ,  output_attentions=lowercase)

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

          a__						:     List[Any]			=    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 							__lowercase		( self ,  lowercase ,  lowercase)      ->						Optional[Any]:







          '''simple docstring'''

          a__						:     List[str]			=    TFDeiTModel(lowercase ,  name='vision_model')
          a__						:     Optional[int]			=    TFRobertaModel(lowercase ,  name='text_model')
          return vision_model, text_model

   def 							__lowercase		( self)      ->						Tuple:







          '''simple docstring'''

          a__						:     Optional[int]			=    TFDeiTModelTester(self)
          a__						:     str			=    TFRobertaModelTester(self)
          a__						:     str			=    vit_model_tester.prepare_config_and_inputs()
          a__						:     Dict			=    bert_model_tester.prepare_config_and_inputs()

          a__			,							a__			,							a__						:     Any			=    vision_config_and_inputs

          (
              (
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							(
              a__
          )			,							
          )						:     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     ):




   """simple docstring"""



   def 							__lowercase		( self)      ->						Any:







          '''simple docstring'''

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

          return model, inputs

   def 							__lowercase		( self ,  lowercase ,  lowercase)      ->						Optional[Any]:







          '''simple docstring'''

          a__						:     str			=    TFCLIPVisionModel(lowercase ,  name='vision_model')
          a__						:     str			=    TFBertModel(lowercase ,  name='text_model')
          return vision_model, text_model

   def 							__lowercase		( self)      ->						List[Any]:







          '''simple docstring'''

          a__						:     List[str]			=    TFCLIPVisionModelTester(self)
          a__						:     Dict			=    TFBertModelTester(self)
          a__						:     Optional[Any]			=    clip_model_tester.prepare_config_and_inputs()
          a__						:     List[Any]			=    bert_model_tester.prepare_config_and_inputs()

          a__			,							a__						:     Union[str, Any]			=    vision_config_and_inputs

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




   """simple docstring"""



   @slow
   def 							__lowercase		( self)      ->						Any:







          '''simple docstring'''

          a__						:     Tuple			=    TFVisionTextDualEncoderModel.from_pretrained(
              'clip-italian/clip-italian' ,  logit_scale_init_value=1.0 ,  from_pt=lowercase)
          a__						:     str			=    VisionTextDualEncoderProcessor.from_pretrained('clip-italian/clip-italian')

          a__						:     Tuple			=    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__						:     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__						:     List[str]			=    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))


