





import argparse
import json

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

from transformers import ConvNextConfig, SegformerImageProcessor, UperNetConfig, UperNetForSemanticSegmentation



def A_     (		A__    )  ->		str:
       a__						:     Any			=    384
       if "tiny" in model_name:
              a__						:     List[Any]			=    [3, 3, 9, 3]
              a__						:     Optional[Any]			=    [96, 192, 384, 768]
       if "small" in model_name:
              a__						:     Union[str, Any]			=    [3, 3, 27, 3]
              a__						:     List[Any]			=    [96, 192, 384, 768]
       if "base" in model_name:
              a__						:     int			=    [3, 3, 27, 3]
              a__						:     List[str]			=    [128, 256, 512, 1024]
              a__						:     Optional[int]			=    512
       if "large" in model_name:
              a__						:     Optional[int]			=    [3, 3, 27, 3]
              a__						:     Any			=    [192, 384, 768, 1536]
              a__						:     int			=    768
       if "xlarge" in model_name:
              a__						:     str			=    [3, 3, 27, 3]
              a__						:     int			=    [256, 512, 1024, 2048]
              a__						:     List[str]			=    1024

       # set label information
       a__						:     int			=    150
       a__						:     List[Any]			=    'huggingface/label-files'
       a__						:     str			=    'ade20k-id2label.json'
       a__						:     Optional[int]			=    json.load(open(hf_hub_download(A__		,				A__		,				repo_type='dataset'    )		,				'r'    )    )
       a__						:     List[str]			=    {int(A__    ): v for k, v in idalabel.items()}
       a__						:     Union[str, Any]			=    {v: k for k, v in idalabel.items()}

       a__						:     List[Any]			=    ConvNextConfig(
           depths=A__		,				hidden_sizes=A__		,				out_features=['stage1', 'stage2', 'stage3', 'stage4']    )
       a__						:     Optional[int]			=    UperNetConfig(
           backbone_config=A__		,				auxiliary_in_channels=A__		,				num_labels=A__		,				idalabel=A__		,				labelaid=A__		,				)

       return config



def A_     (		A__    )  ->		Tuple:
       a__						:     Optional[int]			=    []

       # fmt: off
       # stem
       rename_keys.append(('backbone.downsample_layers.0.0.weight', 'backbone.embeddings.patch_embeddings.weight')    )
       rename_keys.append(('backbone.downsample_layers.0.0.bias', 'backbone.embeddings.patch_embeddings.bias')    )
       rename_keys.append(('backbone.downsample_layers.0.1.weight', 'backbone.embeddings.layernorm.weight')    )
       rename_keys.append(('backbone.downsample_layers.0.1.bias', 'backbone.embeddings.layernorm.bias')    )
       # stages
       for i in range(len(config.backbone_config.depths    )    ):
              for j in range(config.backbone_config.depths[i]    ):
                     rename_keys.append((F'backbone.stages.{i}.{j}.gamma', F'backbone.encoder.stages.{i}.layers.{j}.layer_scale_parameter')    )
                     rename_keys.append((F'backbone.stages.{i}.{j}.depthwise_conv.weight', F'backbone.encoder.stages.{i}.layers.{j}.dwconv.weight')    )
                     rename_keys.append((F'backbone.stages.{i}.{j}.depthwise_conv.bias', F'backbone.encoder.stages.{i}.layers.{j}.dwconv.bias')    )
                     rename_keys.append((F'backbone.stages.{i}.{j}.norm.weight', F'backbone.encoder.stages.{i}.layers.{j}.layernorm.weight')    )
                     rename_keys.append((F'backbone.stages.{i}.{j}.norm.bias', F'backbone.encoder.stages.{i}.layers.{j}.layernorm.bias')    )
                     rename_keys.append((F'backbone.stages.{i}.{j}.pointwise_conv1.weight', F'backbone.encoder.stages.{i}.layers.{j}.pwconv1.weight')    )
                     rename_keys.append((F'backbone.stages.{i}.{j}.pointwise_conv1.bias', F'backbone.encoder.stages.{i}.layers.{j}.pwconv1.bias')    )
                     rename_keys.append((F'backbone.stages.{i}.{j}.pointwise_conv2.weight', F'backbone.encoder.stages.{i}.layers.{j}.pwconv2.weight')    )
                     rename_keys.append((F'backbone.stages.{i}.{j}.pointwise_conv2.bias', F'backbone.encoder.stages.{i}.layers.{j}.pwconv2.bias')    )
              if i > 0:
                     rename_keys.append((F'backbone.downsample_layers.{i}.0.weight', F'backbone.encoder.stages.{i}.downsampling_layer.0.weight')    )
                     rename_keys.append((F'backbone.downsample_layers.{i}.0.bias', F'backbone.encoder.stages.{i}.downsampling_layer.0.bias')    )
                     rename_keys.append((F'backbone.downsample_layers.{i}.1.weight', F'backbone.encoder.stages.{i}.downsampling_layer.1.weight')    )
                     rename_keys.append((F'backbone.downsample_layers.{i}.1.bias', F'backbone.encoder.stages.{i}.downsampling_layer.1.bias')    )

              rename_keys.append((F'backbone.norm{i}.weight', F'backbone.hidden_states_norms.stage{i+1}.weight')    )
              rename_keys.append((F'backbone.norm{i}.bias', F'backbone.hidden_states_norms.stage{i+1}.bias')    )

       # decode head
       rename_keys.extend(
           [
               ('decode_head.conv_seg.weight', 'decode_head.classifier.weight'),
               ('decode_head.conv_seg.bias', 'decode_head.classifier.bias'),
               ('auxiliary_head.conv_seg.weight', 'auxiliary_head.classifier.weight'),
               ('auxiliary_head.conv_seg.bias', 'auxiliary_head.classifier.bias'),
           ]    )
       # fmt: on

       return rename_keys



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



def A_     (		A__		,				A__		,				A__    )  ->		str:
       a__						:     Tuple			=    {
           'upernet-convnext-tiny': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_tiny_fp16_512x512_160k_ade20k/upernet_convnext_tiny_fp16_512x512_160k_ade20k_20220227_124553-cad485de.pth',
           'upernet-convnext-small': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_small_fp16_512x512_160k_ade20k/upernet_convnext_small_fp16_512x512_160k_ade20k_20220227_131208-1b1e394f.pth',
           'upernet-convnext-base': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_base_fp16_512x512_160k_ade20k/upernet_convnext_base_fp16_512x512_160k_ade20k_20220227_181227-02a24fc6.pth',
           'upernet-convnext-large': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_large_fp16_640x640_160k_ade20k/upernet_convnext_large_fp16_640x640_160k_ade20k_20220226_040532-e57aa54d.pth',
           'upernet-convnext-xlarge': 'https://download.openmmlab.com/mmsegmentation/v0.5/convnext/upernet_convnext_xlarge_fp16_640x640_160k_ade20k/upernet_convnext_xlarge_fp16_640x640_160k_ade20k_20220226_080344-95fc38c2.pth',
       }
       a__						:     Dict			=    model_name_to_url[model_name]
       a__						:     Optional[int]			=    torch.hub.load_state_dict_from_url(A__		,				map_location='cpu'    )['state_dict']

       a__						:     List[Any]			=    get_upernet_config(A__    )
       a__						:     Dict			=    UperNetForSemanticSegmentation(A__    )
       model.eval()

       # replace "bn" => "batch_norm"
       for key in state_dict.copy().keys():
              a__						:     Dict			=    state_dict.pop(A__    )
              if "bn" in key:
                     a__						:     Optional[int]			=    key.replace('bn'		,				'batch_norm'    )
              a__						:     List[Any]			=    val

       # rename keys
       a__						:     Union[str, Any]			=    create_rename_keys(A__    )
       for src, dest in rename_keys:
              rename_key(A__		,				A__		,				A__    )

       model.load_state_dict(A__    )

       # verify on image
       a__						:     str			=    'https://huggingface.co/datasets/hf-internal-testing/fixtures_ade20k/resolve/main/ADE_val_00000001.jpg'
       a__						:     int			=    Image.open(requests.get(A__		,				stream=A__    ).raw    ).convert('RGB'    )

       a__						:     Union[str, Any]			=    SegformerImageProcessor()
       a__						:     Union[str, Any]			=    processor(A__		,				return_tensors='pt'    ).pixel_values

       with torch.no_grad():
              a__						:     Optional[Any]			=    model(A__    )

       if model_name == "upernet-convnext-tiny":
              a__						:     Union[str, Any]			=    torch.tensor(
                  [[-8.81_10, -8.81_10, -8.65_21], [-8.81_10, -8.81_10, -8.65_21], [-8.77_46, -8.77_46, -8.61_30]]    )
       elif model_name == "upernet-convnext-small":
              a__						:     int			=    torch.tensor(
                  [[-8.82_36, -8.82_36, -8.67_71], [-8.82_36, -8.82_36, -8.67_71], [-8.76_38, -8.76_38, -8.62_40]]    )
       elif model_name == "upernet-convnext-base":
              a__						:     int			=    torch.tensor(
                  [[-8.85_58, -8.85_58, -8.69_05], [-8.85_58, -8.85_58, -8.69_05], [-8.76_69, -8.76_69, -8.60_21]]    )
       elif model_name == "upernet-convnext-large":
              a__						:     Optional[Any]			=    torch.tensor(
                  [[-8.66_60, -8.66_60, -8.62_10], [-8.66_60, -8.66_60, -8.62_10], [-8.63_10, -8.63_10, -8.59_64]]    )
       elif model_name == "upernet-convnext-xlarge":
              a__						:     Optional[int]			=    torch.tensor(
                  [[-8.49_80, -8.49_80, -8.39_77], [-8.49_80, -8.49_80, -8.39_77], [-8.43_79, -8.43_79, -8.34_12]]    )
       print('Logits:'		,				outputs.logits[0, 0, :3, :3]    )
       assert torch.allclose(outputs.logits[0, 0, :3, :3]		,				A__		,				atol=1E-4    )
       print('Looks ok!'    )

       if pytorch_dump_folder_path is not None:
              print(F'Saving model {model_name} to {pytorch_dump_folder_path}'    )
              model.save_pretrained(A__    )
              print(F'Saving processor to {pytorch_dump_folder_path}'    )
              processor.save_pretrained(A__    )

       if push_to_hub:
              print(F'Pushing model and processor for {model_name} to hub'    )
              model.push_to_hub(F'openmmlab/{model_name}'    )
              processor.push_to_hub(F'openmmlab/{model_name}'    )


if __name__ == "__main__":
    lowercase				:	Optional[Any]      						=  argparse.ArgumentParser()
    # Required parameters
    parser.add_argument(
        """--model_name""",
        default="""upernet-convnext-tiny""",
        type=str,
        choices=[F"""upernet-convnext-{size}""" for size in ["""tiny""", """small""", """base""", """large""", """xlarge"""]],
        help="""Name of the ConvNext UperNet model you'd like to convert.""",
    )
    parser.add_argument(
        """--pytorch_dump_folder_path""", default=None, type=str, help="""Path to the output PyTorch model directory."""
    )
    parser.add_argument(
        """--push_to_hub""", action="""store_true""", help="""Whether or not to push the converted model to the 🤗 hub."""
    )

    lowercase				:	str      						=  parser.parse_args()
    convert_upernet_checkpoint(args.model_name, args.pytorch_dump_folder_path, args.push_to_hub)









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


