





import argparse
import json

import requests
import torch
from huggingface_hub import hf_hub_download
from PIL import Image

from transformers import ViTImageProcessor, ViTMSNConfig, ViTMSNModel
from transformers.image_utils import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD


torch.set_grad_enabled(False)



def A_     (		A__		,				A__=False    )  ->		str:
       a__						:     Any			=    []
       for i in range(config.num_hidden_layers    ):
              # encoder layers: output projection, 2 feedforward neural networks and 2 layernorms
              rename_keys.append((F'module.blocks.{i}.norm1.weight', F'vit.encoder.layer.{i}.layernorm_before.weight')    )
              rename_keys.append((F'module.blocks.{i}.norm1.bias', F'vit.encoder.layer.{i}.layernorm_before.bias')    )
              rename_keys.append(
                  (F'module.blocks.{i}.attn.proj.weight', F'vit.encoder.layer.{i}.attention.output.dense.weight')    )
              rename_keys.append((F'module.blocks.{i}.attn.proj.bias', F'vit.encoder.layer.{i}.attention.output.dense.bias')    )
              rename_keys.append((F'module.blocks.{i}.norm2.weight', F'vit.encoder.layer.{i}.layernorm_after.weight')    )
              rename_keys.append((F'module.blocks.{i}.norm2.bias', F'vit.encoder.layer.{i}.layernorm_after.bias')    )
              rename_keys.append((F'module.blocks.{i}.mlp.fc1.weight', F'vit.encoder.layer.{i}.intermediate.dense.weight')    )
              rename_keys.append((F'module.blocks.{i}.mlp.fc1.bias', F'vit.encoder.layer.{i}.intermediate.dense.bias')    )
              rename_keys.append((F'module.blocks.{i}.mlp.fc2.weight', F'vit.encoder.layer.{i}.output.dense.weight')    )
              rename_keys.append((F'module.blocks.{i}.mlp.fc2.bias', F'vit.encoder.layer.{i}.output.dense.bias')    )

       # projection layer + position embeddings
       rename_keys.extend(
           [
               ('module.cls_token', 'vit.embeddings.cls_token'),
               ('module.patch_embed.proj.weight', 'vit.embeddings.patch_embeddings.projection.weight'),
               ('module.patch_embed.proj.bias', 'vit.embeddings.patch_embeddings.projection.bias'),
               ('module.pos_embed', 'vit.embeddings.position_embeddings'),
           ]    )

       if base_model:
              # layernorm + pooler
              rename_keys.extend(
                  [
                      ('module.norm.weight', 'layernorm.weight'),
                      ('module.norm.bias', 'layernorm.bias'),
                  ]    )

              # if just the base model, we should remove "vit" from all keys that start with "vit"
              a__						:     Tuple			=    [(pair[0], pair[1][4:]) if pair[1].startswith('vit'    ) else pair for pair in rename_keys]
       else:
              # layernorm + classification head
              rename_keys.extend(
                  [
                      ('norm.weight', 'vit.layernorm.weight'),
                      ('norm.bias', 'vit.layernorm.bias'),
                      ('head.weight', 'classifier.weight'),
                      ('head.bias', 'classifier.bias'),
                  ]    )

       return rename_keys



def A_     (		A__		,				A__		,				A__=False    )  ->		Tuple:
       for i in range(config.num_hidden_layers    ):
              if base_model:
                     a__						:     List[str]			=    ''
              else:
                     a__						:     Tuple			=    'vit.'
              # read in weights + bias of input projection layer (in timm, this is a single matrix + bias)
              a__						:     List[str]			=    state_dict.pop(F'module.blocks.{i}.attn.qkv.weight'    )
              a__						:     Optional[Any]			=    state_dict.pop(F'module.blocks.{i}.attn.qkv.bias'    )
              # next, add query, keys and values (in that order) to the state dict
              a__						:     List[str]			=    in_proj_weight[
                  : config.hidden_size, :
              ]
              a__						:     List[Any]			=    in_proj_bias[: config.hidden_size]
              a__						:     Optional[Any]			=    in_proj_weight[
                  config.hidden_size : config.hidden_size * 2, :
              ]
              a__						:     Tuple			=    in_proj_bias[
                  config.hidden_size : config.hidden_size * 2
              ]
              a__						:     Optional[Any]			=    in_proj_weight[
                  -config.hidden_size :, :
              ]
              a__						:     str			=    in_proj_bias[-config.hidden_size :]



def A_     (		A__    )  ->		Optional[int]:
       a__						:     List[str]			=    ['head.weight', 'head.bias']
       for k in ignore_keys:
              state_dict.pop(A__		,				A__    )



def A_     (		A__    )  ->		Optional[int]:
       # projection head is used in the self-supervised pre-training in MSN,
       # for downstream task it's not needed.
       a__						:     Dict			=    [
           'module.fc.fc1.weight',
           'module.fc.fc1.bias',
           'module.fc.bn1.weight',
           'module.fc.bn1.bias',
           'module.fc.bn1.running_mean',
           'module.fc.bn1.running_var',
           'module.fc.bn1.num_batches_tracked',
           'module.fc.fc2.weight',
           'module.fc.fc2.bias',
           'module.fc.bn2.weight',
           'module.fc.bn2.bias',
           'module.fc.bn2.running_mean',
           'module.fc.bn2.running_var',
           'module.fc.bn2.num_batches_tracked',
           'module.fc.fc3.weight',
           'module.fc.fc3.bias',
       ]
       for k in ignore_keys:
              state_dict.pop(A__		,				A__    )



def A_     (		A__		,				A__		,				A__    )  ->		int:
       a__						:     List[Any]			=    dct.pop(A__    )
       a__						:     Union[str, Any]			=    val



def A_     (		A__		,				A__    )  ->		Dict:
       a__						:     Tuple			=    ViTMSNConfig()
       a__						:     Dict			=    1000

       a__						:     Optional[Any]			=    'datasets/huggingface/label-files'
       a__						:     str			=    'imagenet-1k-id2label.json'
       a__						:     Optional[Any]			=    json.load(open(hf_hub_download(A__		,				A__    )		,				'r'    )    )
       a__						:     Tuple			=    {int(A__    ): v for k, v in idalabel.items()}
       a__						:     str			=    idalabel
       a__						:     List[str]			=    {v: k for k, v in idalabel.items()}

       if "s16" in checkpoint_url:
              a__						:     int			=    384
              a__						:     Optional[int]			=    1536
              a__						:     int			=    6
       elif "l16" in checkpoint_url:
              a__						:     str			=    1024
              a__						:     Any			=    4096
              a__						:     str			=    24
              a__						:     Dict			=    16
              a__						:     Optional[int]			=    0.1
       elif "b4" in checkpoint_url:
              a__						:     Tuple			=    4
       elif "l7" in checkpoint_url:
              a__						:     Union[str, Any]			=    7
              a__						:     Union[str, Any]			=    1024
              a__						:     Dict			=    4096
              a__						:     Dict			=    24
              a__						:     str			=    16
              a__						:     Tuple			=    0.1

       a__						:     Dict			=    ViTMSNModel(A__    )

       a__						:     Optional[Any]			=    torch.hub.load_state_dict_from_url(A__		,				map_location='cpu'    )['target_encoder']

       a__						:     str			=    ViTImageProcessor(size=config.image_size    )

       remove_projection_head(A__    )
       a__						:     str			=    create_rename_keys(A__		,				base_model=A__    )

       for src, dest in rename_keys:
              rename_key(A__		,				A__		,				A__    )
       read_in_q_k_v(A__		,				A__		,				base_model=A__    )

       model.load_state_dict(A__    )
       model.eval()

       a__						:     int			=    'http://images.cocodataset.org/val2017/000000039769.jpg'

       a__						:     Tuple			=    Image.open(requests.get(A__		,				stream=A__    ).raw    )
       a__						:     Optional[int]			=    ViTImageProcessor(
           size=config.image_size		,				image_mean=A__		,				image_std=A__    )
       a__						:     Optional[Any]			=    image_processor(images=A__		,				return_tensors='pt'    )

       # forward pass
       torch.manual_seed(2    )
       a__						:     str			=    model(**A__    )
       a__						:     int			=    outputs.last_hidden_state

       # The following Colab Notebook was used to generate these outputs:
       # https://colab.research.google.com/gist/sayakpaul/3672419a04f5997827503fd84079bdd1/scratchpad.ipynb
       if "s16" in checkpoint_url:
              a__						:     List[Any]			=    torch.tensor([[-1.09_15, -1.48_76, -1.18_09]]    )
       elif "b16" in checkpoint_url:
              a__						:     List[Any]			=    torch.tensor([[14.28_89, -18.90_45, 11.72_81]]    )
       elif "l16" in checkpoint_url:
              a__						:     Tuple			=    torch.tensor([[41.50_28, -22.86_81, 45.64_75]]    )
       elif "b4" in checkpoint_url:
              a__						:     Dict			=    torch.tensor([[-4.38_68, 5.29_32, -0.41_37]]    )
       else:
              a__						:     Optional[Any]			=    torch.tensor([[-0.17_92, -0.64_65, 2.42_63]]    )

       # verify logits
       assert torch.allclose(last_hidden_state[:, 0, :3]		,				A__		,				atol=1E-4    )

       print(F'Saving model to {pytorch_dump_folder_path}'    )
       model.save_pretrained(A__    )

       print(F'Saving image processor to {pytorch_dump_folder_path}'    )
       image_processor.save_pretrained(A__    )


if __name__ == "__main__":
    lowercase				:	Any      						=  argparse.ArgumentParser()
    # Required parameters
    parser.add_argument(
        """--checkpoint_url""",
        default="""https://dl.fbaipublicfiles.com/msn/vits16_800ep.pth.tar""",
        type=str,
        help="""URL of the checkpoint you'd like to convert.""",
    )
    parser.add_argument(
        """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
    )

    lowercase				:	str      						=  parser.parse_args()
    convert_vit_msn_checkpoint(args.checkpoint_url, args.pytorch_dump_folder_path)









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


