





"""simple docstring"""
from __future__ import annotations

import inspect
import unittest

from transformers import MobileViTConfig
from transformers.file_utils import is_tf_available, is_vision_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
       import numpy as np
       import tensorflow as tf

       from transformers import TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation, TFMobileViTModel
       from transformers.models.mobilevit.modeling_tf_mobilevit import TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
       from PIL import Image

       from transformers import MobileViTImageProcessor







class 	a				(					a__   ):



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.config_class(**self.inputs_dict			)
  self.parent.assertTrue(hasattr(_snake_case							,    'hidden_sizes'			)			)
  self.parent.assertTrue(hasattr(_snake_case							,    'neck_hidden_sizes'			)			)
  self.parent.assertTrue(hasattr(_snake_case							,    'num_attention_heads'			)			)







class 	a				:



 def __init__(			self							,    _snake_case							,    _snake_case=13							,    _snake_case=32							,    _snake_case=2							,    _snake_case=3							,    _snake_case=6_40							,    _snake_case=4							,    _snake_case="silu"							,    _snake_case=3							,    _snake_case=32							,    _snake_case=0.1							,    _snake_case=0.1							,    _snake_case=0.1							,    _snake_case=0.02							,    _snake_case=True							,    _snake_case=True							,    _snake_case=10							,    _snake_case=None							,    ):







  """simple docstring"""






  lowerCAmelCase  							=      parent
  lowerCAmelCase  							=      batch_size
  lowerCAmelCase  							=      image_size
  lowerCAmelCase  							=      patch_size
  lowerCAmelCase  							=      num_channels
  lowerCAmelCase  							=      last_hidden_size
  lowerCAmelCase  							=      num_attention_heads
  lowerCAmelCase  							=      hidden_act
  lowerCAmelCase  							=      conv_kernel_size
  lowerCAmelCase  							=      output_stride
  lowerCAmelCase  							=      hidden_dropout_prob
  lowerCAmelCase  							=      attention_probs_dropout_prob
  lowerCAmelCase  							=      classifier_dropout_prob
  lowerCAmelCase  							=      use_labels
  lowerCAmelCase  							=      is_training
  lowerCAmelCase  							=      num_labels
  lowerCAmelCase  							=      initializer_range
  lowerCAmelCase  							=      scope



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

  lowerCAmelCase  							=      None
  lowerCAmelCase  							=      None
  if self.use_labels:
   lowerCAmelCase  							=      ids_tensor([self.batch_size]							,    self.num_labels			)
   lowerCAmelCase  							=      ids_tensor([self.batch_size, self.image_size, self.image_size]							,    self.num_labels			)

  lowerCAmelCase  							=      self.get_config()

  return config, pixel_values, labels, pixel_labels



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  return MobileViTConfig(
      image_size=self.image_size							,    patch_size=self.patch_size							,    num_channels=self.num_channels							,    num_attention_heads=self.num_attention_heads							,    hidden_act=self.hidden_act							,    conv_kernel_size=self.conv_kernel_size							,    output_stride=self.output_stride							,    hidden_dropout_prob=self.hidden_dropout_prob							,    attention_probs_dropout_prob=self.attention_probs_dropout_prob							,    classifier_dropout_prob=self.classifier_dropout_prob							,    initializer_range=self.initializer_range							,    )



 def 					UpperCamelCase__   (			self							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case			):







  """simple docstring"""






  lowerCAmelCase  							=      TFMobileViTModel(config=_snake_case			)
  lowerCAmelCase  							=      model(_snake_case							,    training=_snake_case			)
  lowerCAmelCase  							=      lowerCAmelCase  							=      self.image_size // self.output_stride
  self.parent.assertEqual(
      result.last_hidden_state.shape							,    (self.batch_size, self.last_hidden_size, expected_height, expected_width)			)



 def 					UpperCamelCase__   (			self							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case			):







  """simple docstring"""






  lowerCAmelCase  							=      self.num_labels
  lowerCAmelCase  							=      TFMobileViTForImageClassification(_snake_case			)
  lowerCAmelCase  							=      model(_snake_case							,    labels=_snake_case							,    training=_snake_case			)
  self.parent.assertEqual(result.logits.shape							,    (self.batch_size, self.num_labels)			)



 def 					UpperCamelCase__   (			self							,    _snake_case							,    _snake_case							,    _snake_case							,    _snake_case			):







  """simple docstring"""






  lowerCAmelCase  							=      self.num_labels
  lowerCAmelCase  							=      TFMobileViTForSemanticSegmentation(_snake_case			)
  lowerCAmelCase  							=      lowerCAmelCase  							=      self.image_size // self.output_stride

  lowerCAmelCase  							=      model(_snake_case							,    training=_snake_case			)
  self.parent.assertEqual(
      result.logits.shape							,    (self.batch_size, self.num_labels, expected_height, expected_width)			)

  lowerCAmelCase  							=      model(_snake_case							,    labels=_snake_case							,    training=_snake_case			)
  self.parent.assertEqual(
      result.logits.shape							,    (self.batch_size, self.num_labels, expected_height, expected_width)			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.prepare_config_and_inputs()
  lowerCAmelCase							,lowerCAmelCase							,lowerCAmelCase							,lowerCAmelCase  							=      config_and_inputs
  lowerCAmelCase  							=      {'pixel_values': pixel_values}
  return config, inputs_dict







@require_tf
class 	a				(					a__					,      a__					,      unittest.TestCase   ):
 snake_case__    	=    (
     (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
     if is_tf_available()
     else ()
 )
 snake_case__    	=    (
     {'''feature-extraction''': TFMobileViTModel, '''image-classification''': TFMobileViTForImageClassification}
     if is_tf_available()
     else {}
 )

 snake_case__    	=    False
 snake_case__    	=    False
 snake_case__    	=    False
 snake_case__    	=    False
 snake_case__    	=    False



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      TFMobileViTModelTester(self			)
  lowerCAmelCase  							=      TFMobileViTConfigTester(self							,    config_class=_snake_case							,    has_text_modality=_snake_case			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  self.config_tester.run_common_tests()



 @unittest.skip(reason='MobileViT does not use inputs_embeds'			)
 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  pass



 @unittest.skip(reason='MobileViT does not support input and output embeddings'			)
 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  pass



 @unittest.skip(reason='MobileViT does not output attentions'			)
 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  pass



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase							,lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs_for_common()

  for model_class in self.all_model_classes:
   lowerCAmelCase  							=      model_class(_snake_case			)
   lowerCAmelCase  							=      inspect.signature(model.call			)
   # signature.parameters is an OrderedDict => so arg_names order is deterministic
   lowerCAmelCase  							=      [*signature.parameters.keys()]

   lowerCAmelCase  							=      ['pixel_values']
   self.assertListEqual(arg_names[:1]							,    _snake_case			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_model(*_snake_case			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  def check_hidden_states_output(_snake_case							,    _snake_case							,    _snake_case			):
   lowerCAmelCase  							=      model_class(_snake_case			)

   lowerCAmelCase  							=      model(**self._prepare_for_class(_snake_case							,    _snake_case			)			)

   lowerCAmelCase  							=      outputs.hidden_states

   lowerCAmelCase  							=      5
   self.assertEqual(len(_snake_case			)							,    _snake_case			)

   # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
   # with the width and height being successively divided by 2.
   lowerCAmelCase  							=      2
   for i in range(len(_snake_case			)			):
    self.assertListEqual(
        list(hidden_states[i].shape[-2:]			)							,    [self.model_tester.image_size // divisor, self.model_tester.image_size // divisor]							,    )
    divisor *= 2

   self.assertEqual(self.model_tester.output_stride							,    divisor // 2			)

  lowerCAmelCase							,lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs_for_common()

  for model_class in self.all_model_classes:
   lowerCAmelCase  							=      True
   check_hidden_states_output(_snake_case							,    _snake_case							,    _snake_case			)

   # check that output_hidden_states also work using config
   del inputs_dict["output_hidden_states"]
   lowerCAmelCase  							=      True

   check_hidden_states_output(_snake_case							,    _snake_case							,    _snake_case			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_for_image_classification(*_snake_case			)



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_for_semantic_segmentation(*_snake_case			)



 @unittest.skipIf(
     not is_tf_available() or len(tf.config.list_physical_devices('GPU'			)			) == 0							,    reason='TF does not support backprop for grouped convolutions on CPU.'							,    )
 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  super().test_dataset_conversion()



 def 					UpperCamelCase__   (			self							,    _snake_case							,    _snake_case							,    _snake_case=2E-1							,    _snake_case=2E-1			):







  """simple docstring"""






  self.assertTrue(np.allclose(_snake_case							,    _snake_case							,    atol=_snake_case							,    rtol=_snake_case			)			)



 @unittest.skipIf(
     not is_tf_available() or len(tf.config.list_physical_devices('GPU'			)			) == 0							,    reason='TF does not support backprop for grouped convolutions on CPU.'							,    )
 @slow
 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase							,lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs_for_common()

  for model_class in self.all_model_classes:
   # Since `TFMobileViTModel` cannot operate with the default `fit()` method.
   if model_class.__name__ != "TFMobileViTModel":
    lowerCAmelCase  							=      model_class(_snake_case			)
    if getattr(_snake_case							,    'hf_compute_loss'							,    _snake_case			):
     super().test_keras_fit()



 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase							,lowerCAmelCase  							=      self.model_tester.prepare_config_and_inputs_for_common()
  for model_class in self.all_model_classes:
   # set an ignore index to correctly test the masked loss used in
   # `TFMobileViTForSemanticSegmentation`.
   if model_class.__name__ != "TFMobileViTForSemanticSegmentation":
    lowerCAmelCase  							=      5

   lowerCAmelCase  							=      model_class(_snake_case			)
   if getattr(_snake_case							,    'hf_compute_loss'							,    _snake_case			):
    # The number of elements in the loss should be the same as the number of elements in the label
    lowerCAmelCase  							=      self._prepare_for_class(inputs_dict.copy()							,    _snake_case							,    return_labels=_snake_case			)
    lowerCAmelCase  							=      prepared_for_class[
        sorted(prepared_for_class.keys() - inputs_dict.keys()							,    reverse=_snake_case			)[0]
    ]
    lowerCAmelCase  							=      added_label.shape.as_list()[:1]

    # Test that model correctly compute the loss with kwargs
    lowerCAmelCase  							=      self._prepare_for_class(inputs_dict.copy()							,    _snake_case							,    return_labels=_snake_case			)
    lowerCAmelCase  							=      {'input_ids', 'pixel_values', 'input_features'}
    lowerCAmelCase  							=      possible_input_names.intersection(set(_snake_case			)			).pop()
    lowerCAmelCase  							=      prepared_for_class.pop(_snake_case			)

    lowerCAmelCase  							=      model(_snake_case							,    **_snake_case			)[0]
    self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]			)

    # Test that model correctly compute the loss when we mask some positions
    lowerCAmelCase  							=      self._prepare_for_class(inputs_dict.copy()							,    _snake_case							,    return_labels=_snake_case			)
    lowerCAmelCase  							=      {'input_ids', 'pixel_values', 'input_features'}
    lowerCAmelCase  							=      possible_input_names.intersection(set(_snake_case			)			).pop()
    lowerCAmelCase  							=      prepared_for_class.pop(_snake_case			)
    if "labels" in prepared_for_class:
     lowerCAmelCase  							=      prepared_for_class['labels'].numpy()
     if len(labels.shape			) > 1 and labels.shape[1] != 1:
      # labels[0] = -100
      lowerCAmelCase  							=      tf.convert_to_tensor(_snake_case			)
      lowerCAmelCase  							=      model(_snake_case							,    **_snake_case			)[0]
      self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]			)
      self.assertTrue(not np.any(np.isnan(loss.numpy()			)			)			)

                # Test that model correctly compute the loss with a dict
    lowerCAmelCase  							=      self._prepare_for_class(inputs_dict.copy()							,    _snake_case							,    return_labels=_snake_case			)
    lowerCAmelCase  							=      model(_snake_case			)[0]
    self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]			)

    # Test that model correctly compute the loss with a tuple
    lowerCAmelCase  							=      self._prepare_for_class(inputs_dict.copy()							,    _snake_case							,    return_labels=_snake_case			)

    # Get keys that were added with the _prepare_for_class function
    lowerCAmelCase  							=      prepared_for_class.keys() - inputs_dict.keys()
    lowerCAmelCase  							=      inspect.signature(model.call			).parameters
    lowerCAmelCase  							=      list(signature.keys()			)

    # Create a dictionary holding the location of the tensors in the tuple
    lowerCAmelCase  							=      {0: input_name}
    for label_key in label_keys:
     lowerCAmelCase  							=      signature_names.index(_snake_case			)
     lowerCAmelCase  							=      label_key
    lowerCAmelCase  							=      sorted(tuple_index_mapping.items()			)
    # Initialize a list with their default values, update the values and convert to a tuple
    lowerCAmelCase  							=      []

    for name in signature_names:
     if name != "kwargs":
      list_input.append(signature[name].default			)

    for index, value in sorted_tuple_index_mapping:
     lowerCAmelCase  							=      prepared_for_class[value]

    lowerCAmelCase  							=      tuple(_snake_case			)

    # Send to model
    lowerCAmelCase  							=      model(tuple_input[:-1]			)[0]

    self.assertTrue(loss.shape.as_list() == expected_loss_size or loss.shape.as_list() == [1]			)



 @slow
 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
   lowerCAmelCase  							=      TFMobileViTModel.from_pretrained(_snake_case			)
   self.assertIsNotNone(_snake_case			)


def 						_SCREAMING_SNAKE_CASE       ():
 lowerCAmelCase  							=      Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'       )
 return image







@require_tf
class 	a				(					unittest.TestCase   ):



 @slow
 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      TFMobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small'			)

  lowerCAmelCase  							=      MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small'			)
  lowerCAmelCase  							=      prepare_img()
  lowerCAmelCase  							=      image_processor(images=_snake_case							,    return_tensors='tf'			)

  # forward pass
  lowerCAmelCase  							=      model(**_snake_case							,    training=_snake_case			)

  # verify the logits
  lowerCAmelCase  							=      tf.TensorShape((1, 10_00)			)
  self.assertEqual(outputs.logits.shape							,    _snake_case			)

  lowerCAmelCase  							=      tf.constant([-1.9_364, -1.2_327, -0.4_653]			)

  tf.debugging.assert_near(outputs.logits[0, :3]							,    _snake_case							,    atol=1E-4							,    rtol=1E-04			)



 @slow
 def 					UpperCamelCase__   (			self			):







  """simple docstring"""






  lowerCAmelCase  							=      TFMobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'			)

  lowerCAmelCase  							=      MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small'			)

  lowerCAmelCase  							=      prepare_img()
  lowerCAmelCase  							=      image_processor(images=_snake_case							,    return_tensors='tf'			)

  # forward pass
  lowerCAmelCase  							=      model(inputs.pixel_values							,    training=_snake_case			)
  lowerCAmelCase  							=      outputs.logits

  # verify the logits
  lowerCAmelCase  							=      tf.TensorShape((1, 21, 32, 32)			)
  self.assertEqual(logits.shape							,    _snake_case			)

  lowerCAmelCase  							=      tf.constant(
      [
          [[6.9_713, 6.9_786, 7.2_422], [7.2_893, 7.2_825, 7.4_446], [7.6_580, 7.8_797, 7.9_420]],
          [[-10.6_869, -10.3_250, -10.3_471], [-10.4_228, -9.9_868, -9.7_132], [-11.0_405, -11.0_221, -10.7_318]],
          [[-3.3_089, -2.8_539, -2.6_740], [-3.2_706, -2.5_621, -2.5_108], [-3.2_534, -2.6_615, -2.6_651]],
      ]			)

  tf.debugging.assert_near(logits[0, :3, :3, :3]							,    _snake_case							,    rtol=1E-4							,    atol=1E-4			)












"""simple docstring"""
import argparse
import os

import align
import numpy as np
import requests
import tensorflow as tf
import torch
from PIL import Image
from tokenizer import Tokenizer

from transformers import (
    AlignConfig,
    AlignModel,
    AlignProcessor,
    BertConfig,
    BertTokenizer,
    EfficientNetConfig,
    EfficientNetImageProcessor,
)
from transformers.utils import logging


logging.set_verbosity_info()
__UpperCamelCase			:		Union[str, Any]		    =   logging.get_logger(__name__)

def 						_SCREAMING_SNAKE_CASE       (_UpperCAmelCase :  Optional[int]       ):
 lowerCAmelCase  							=      tf.image.resize(_UpperCAmelCase   ,			(346, 346)       )
 lowerCAmelCase  							=      tf.image.crop_to_bounding_box(_UpperCAmelCase   ,			(346 - 289) // 2   ,			(346 - 289) // 2   ,			289   ,			289       )
 return image

def 						_SCREAMING_SNAKE_CASE       ():
 lowerCAmelCase  							=      EfficientNetConfig.from_pretrained('google/efficientnet-b7'       )
 lowerCAmelCase  							=      289
 lowerCAmelCase  							=      640
 lowerCAmelCase  							=      {'0': 'LABEL_0', '1': 'LABEL_1'}
 lowerCAmelCase  							=      {'LABEL_0': 0, 'LABEL_1': 1}
 lowerCAmelCase  							=      []

 lowerCAmelCase  							=      BertConfig()
 lowerCAmelCase  							=      AlignConfig.from_text_vision_configs(
     text_config=_UpperCAmelCase   ,			vision_config=_UpperCAmelCase   ,			projection_dim=640       )
 return config

def 						_SCREAMING_SNAKE_CASE       ():
 lowerCAmelCase  							=      'http://images.cocodataset.org/val2017/000000039769.jpg'
 lowerCAmelCase  							=      Image.open(requests.get(_UpperCAmelCase   ,			stream=_UpperCAmelCase       ).raw       )
 return im

def 						_SCREAMING_SNAKE_CASE       ():
 lowerCAmelCase  							=      EfficientNetImageProcessor(
     do_center_crop=_UpperCAmelCase   ,			rescale_factor=1 / 127.5   ,			rescale_offset=_UpperCAmelCase   ,			do_normalize=_UpperCAmelCase   ,			include_top=_UpperCAmelCase   ,			resample=Image.BILINEAR   ,			)
 lowerCAmelCase  							=      BertTokenizer.from_pretrained('bert-base-uncased'       )
 lowerCAmelCase  							=      64
 lowerCAmelCase  							=      AlignProcessor(image_processor=_UpperCAmelCase   ,			tokenizer=_UpperCAmelCase       )
 return processor

def 						_SCREAMING_SNAKE_CASE       (_UpperCAmelCase :  List[str]       ):
 # EfficientNet image encoder
 lowerCAmelCase  							=      [v.split('_'       )[0].split('block'       )[1] for v in original_param_names if v.startswith('block'       )]
 lowerCAmelCase  							=      list(set(_UpperCAmelCase       )       )
 lowerCAmelCase  							=      sorted(_UpperCAmelCase       )
 lowerCAmelCase  							=      len(_UpperCAmelCase       )
 lowerCAmelCase  							=      {b: str(_UpperCAmelCase       ) for b, i in zip(_UpperCAmelCase   ,			range(_UpperCAmelCase       )       )}

 lowerCAmelCase  							=      []
 rename_keys.append(('stem_conv/kernel:0', 'embeddings.convolution.weight')       )
 rename_keys.append(('stem_bn/gamma:0', 'embeddings.batchnorm.weight')       )
 rename_keys.append(('stem_bn/beta:0', 'embeddings.batchnorm.bias')       )
 rename_keys.append(('stem_bn/moving_mean:0', 'embeddings.batchnorm.running_mean')       )
 rename_keys.append(('stem_bn/moving_variance:0', 'embeddings.batchnorm.running_var')       )

 for b in block_names:
  lowerCAmelCase  							=      block_name_mapping[b]
  rename_keys.append((F'block{b}_expand_conv/kernel:0', F'encoder.blocks.{hf_b}.expansion.expand_conv.weight')       )
  rename_keys.append((F'block{b}_expand_bn/gamma:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.weight')       )
  rename_keys.append((F'block{b}_expand_bn/beta:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.bias')       )
  rename_keys.append(
      (F'block{b}_expand_bn/moving_mean:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.running_mean')       )
  rename_keys.append(
      (F'block{b}_expand_bn/moving_variance:0', F'encoder.blocks.{hf_b}.expansion.expand_bn.running_var')       )
  rename_keys.append(
      (F'block{b}_dwconv/depthwise_kernel:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_conv.weight')       )
  rename_keys.append((F'block{b}_bn/gamma:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.weight')       )
  rename_keys.append((F'block{b}_bn/beta:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.bias')       )
  rename_keys.append(
      (F'block{b}_bn/moving_mean:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_mean')       )
  rename_keys.append(
      (F'block{b}_bn/moving_variance:0', F'encoder.blocks.{hf_b}.depthwise_conv.depthwise_norm.running_var')       )

  rename_keys.append((F'block{b}_se_reduce/kernel:0', F'encoder.blocks.{hf_b}.squeeze_excite.reduce.weight')       )
  rename_keys.append((F'block{b}_se_reduce/bias:0', F'encoder.blocks.{hf_b}.squeeze_excite.reduce.bias')       )
  rename_keys.append((F'block{b}_se_expand/kernel:0', F'encoder.blocks.{hf_b}.squeeze_excite.expand.weight')       )
  rename_keys.append((F'block{b}_se_expand/bias:0', F'encoder.blocks.{hf_b}.squeeze_excite.expand.bias')       )
  rename_keys.append(
      (F'block{b}_project_conv/kernel:0', F'encoder.blocks.{hf_b}.projection.project_conv.weight')       )
  rename_keys.append((F'block{b}_project_bn/gamma:0', F'encoder.blocks.{hf_b}.projection.project_bn.weight')       )
  rename_keys.append((F'block{b}_project_bn/beta:0', F'encoder.blocks.{hf_b}.projection.project_bn.bias')       )
  rename_keys.append(
      (F'block{b}_project_bn/moving_mean:0', F'encoder.blocks.{hf_b}.projection.project_bn.running_mean')       )
  rename_keys.append(
      (F'block{b}_project_bn/moving_variance:0', F'encoder.blocks.{hf_b}.projection.project_bn.running_var')       )

 lowerCAmelCase  							=      {}
 for item in rename_keys:
  if item[0] in original_param_names:
   lowerCAmelCase  							=      'vision_model.' + item[1]

    # BERT text encoder
 lowerCAmelCase  							=      []
 lowerCAmelCase  							=      'tf_bert_model/bert'
 lowerCAmelCase  							=      'text_model'
 for i in range(12       ):
  rename_keys.append(
      (
          F'{old}/encoder/layer_._{i}/attention/self/query/kernel:0',
          F'{new}.encoder.layer.{i}.attention.self.query.weight',
      )       )
  rename_keys.append(
      (
          F'{old}/encoder/layer_._{i}/attention/self/query/bias:0',
          F'{new}.encoder.layer.{i}.attention.self.query.bias',
      )       )
  rename_keys.append(
      (
          F'{old}/encoder/layer_._{i}/attention/self/key/kernel:0',
          F'{new}.encoder.layer.{i}.attention.self.key.weight',
      )       )
  rename_keys.append(
      (
          F'{old}/encoder/layer_._{i}/attention/self/key/bias:0',
          F'{new}.encoder.layer.{i}.attention.self.key.bias',
      )       )
  rename_keys.append(
      (
          F'{old}/encoder/layer_._{i}/attention/self/value/kernel:0',
          F'{new}.encoder.layer.{i}.attention.self.value.weight',
      )       )
  rename_keys.append(
      (
          F'{old}/encoder/layer_._{i}/attention/self/value/bias:0',
          F'{new}.encoder.layer.{i}.attention.self.value.bias',
      )       )
  rename_keys.append(
      (
          F'{old}/encoder/layer_._{i}/attention/output/dense/kernel:0',
          F'{new}.encoder.layer.{i}.attention.output.dense.weight',
      )       )
  rename_keys.append(
      (
          F'{old}/encoder/layer_._{i}/attention/output/dense/bias:0',
          F'{new}.encoder.layer.{i}.attention.output.dense.bias',
      )       )
  rename_keys.append(
      (
          F'{old}/encoder/layer_._{i}/attention/output/LayerNorm/gamma:0',
          F'{new}.encoder.layer.{i}.attention.output.LayerNorm.weight',
      )       )
  rename_keys.append(
      (
          F'{old}/encoder/layer_._{i}/attention/output/LayerNorm/beta:0',
          F'{new}.encoder.layer.{i}.attention.output.LayerNorm.bias',
      )       )
  rename_keys.append(
      (
          F'{old}/encoder/layer_._{i}/intermediate/dense/kernel:0',
          F'{new}.encoder.layer.{i}.intermediate.dense.weight',
      )       )
  rename_keys.append(
      (
          F'{old}/encoder/layer_._{i}/intermediate/dense/bias:0',
          F'{new}.encoder.layer.{i}.intermediate.dense.bias',
      )       )
  rename_keys.append(
      (F'{old}/encoder/layer_._{i}/output/dense/kernel:0', F'{new}.encoder.layer.{i}.output.dense.weight')       )
  rename_keys.append(
      (F'{old}/encoder/layer_._{i}/output/dense/bias:0', F'{new}.encoder.layer.{i}.output.dense.bias')       )
  rename_keys.append(
      (F'{old}/encoder/layer_._{i}/output/LayerNorm/gamma:0', F'{new}.encoder.layer.{i}.output.LayerNorm.weight')       )
  rename_keys.append(
      (F'{old}/encoder/layer_._{i}/output/LayerNorm/beta:0', F'{new}.encoder.layer.{i}.output.LayerNorm.bias')       )

 rename_keys.append((F'{old}/embeddings/word_embeddings/weight:0', F'{new}.embeddings.word_embeddings.weight')       )
 rename_keys.append(
     (F'{old}/embeddings/position_embeddings/embeddings:0', F'{new}.embeddings.position_embeddings.weight')       )
 rename_keys.append(
     (F'{old}/embeddings/token_type_embeddings/embeddings:0', F'{new}.embeddings.token_type_embeddings.weight')       )
 rename_keys.append((F'{old}/embeddings/LayerNorm/gamma:0', F'{new}.embeddings.LayerNorm.weight')       )
 rename_keys.append((F'{old}/embeddings/LayerNorm/beta:0', F'{new}.embeddings.LayerNorm.bias')       )

 rename_keys.append((F'{old}/pooler/dense/kernel:0', F'{new}.pooler.dense.weight')       )
 rename_keys.append((F'{old}/pooler/dense/bias:0', F'{new}.pooler.dense.bias')       )
 rename_keys.append(('dense/kernel:0', 'text_projection.weight')       )
 rename_keys.append(('dense/bias:0', 'text_projection.bias')       )
 rename_keys.append(('dense/bias:0', 'text_projection.bias')       )
 rename_keys.append(('temperature:0', 'temperature')       )

 for item in rename_keys:
  if item[0] in original_param_names:
   lowerCAmelCase  							=      item[1]
 return key_mapping

def 						_SCREAMING_SNAKE_CASE       (_UpperCAmelCase :  List[Any]   ,			_UpperCAmelCase :  List[str]   ,			_UpperCAmelCase :  Any       ):
 list(hf_params.keys()       )

 for key, value in tf_params.items():
  if key not in key_mapping:
   continue

  lowerCAmelCase  							=      key_mapping[key]
  if "_conv" in key and "kernel" in key:
   lowerCAmelCase  							=      torch.from_numpy(_UpperCAmelCase       ).permute(3   ,			2   ,			0   ,			1       )
  elif "embeddings" in key:
   lowerCAmelCase  							=      torch.from_numpy(_UpperCAmelCase       )
  elif "depthwise_kernel" in key:
   lowerCAmelCase  							=      torch.from_numpy(_UpperCAmelCase       ).permute(2   ,			3   ,			0   ,			1       )
  elif "kernel" in key:
   lowerCAmelCase  							=      torch.from_numpy(np.transpose(_UpperCAmelCase       )       )
  elif "temperature" in key:
   lowerCAmelCase  							=      value
  elif "bn/gamma" or "bn/beta" in key:
   lowerCAmelCase  							=      torch.from_numpy(np.transpose(_UpperCAmelCase       )       ).squeeze()
  else:
   lowerCAmelCase  							=      torch.from_numpy(_UpperCAmelCase       )

  # Replace HF parameters with original TF model parameters
  hf_params[hf_key].copy_(_UpperCAmelCase       )

@torch.no_grad()
def 						_SCREAMING_SNAKE_CASE       (_UpperCAmelCase :  str   ,			_UpperCAmelCase :  Tuple   ,			_UpperCAmelCase :  Any   ,			_UpperCAmelCase :  Any       ):
 lowerCAmelCase  							=      64
 lowerCAmelCase  							=      Tokenizer(_UpperCAmelCase       )
 lowerCAmelCase  							=      align.Align('efficientnet-b7'   ,			'bert-base'   ,			640   ,			_UpperCAmelCase   ,			tok.get_vocab_size()       )
 original_model.compile()
 original_model.load_weights(_UpperCAmelCase       )

 lowerCAmelCase  							=      original_model.trainable_variables
 lowerCAmelCase  							=      original_model.non_trainable_variables
 lowerCAmelCase  							=      {param.name: param.numpy() for param in tf_params}
 for param in tf_non_train_params:
  lowerCAmelCase  							=      param.numpy()
 lowerCAmelCase  							=      list(tf_params.keys()       )

 # Load HuggingFace model
 lowerCAmelCase  							=      get_align_config()
 lowerCAmelCase  							=      AlignModel(_UpperCAmelCase       ).eval()
 lowerCAmelCase  							=      hf_model.state_dict()

 # Create src-to-dst parameter name mapping dictionary
 print('Converting parameters...'       )
 lowerCAmelCase  							=      rename_keys(_UpperCAmelCase       )
 replace_params(_UpperCAmelCase   ,			_UpperCAmelCase   ,			_UpperCAmelCase       )

 # Initialize processor
 lowerCAmelCase  							=      get_processor()
 lowerCAmelCase  							=      processor(
     images=prepare_img()   ,			text='A picture of a cat'   ,			padding='max_length'   ,			max_length=64   ,			return_tensors='pt'       )

 # HF model inference
 hf_model.eval()
 with torch.no_grad():
  lowerCAmelCase  							=      hf_model(**_UpperCAmelCase       )

 lowerCAmelCase  							=      outputs.image_embeds.detach().numpy()
 lowerCAmelCase  							=      outputs.text_embeds.detach().numpy()

 # Original model inference
 lowerCAmelCase  							=      False
 lowerCAmelCase  							=      EfficientNetImageProcessor(
     do_center_crop=_UpperCAmelCase   ,			do_rescale=_UpperCAmelCase   ,			do_normalize=_UpperCAmelCase   ,			include_top=_UpperCAmelCase   ,			resample=Image.BILINEAR   ,			)
 lowerCAmelCase  							=      tf_image_processor(images=prepare_img()   ,			return_tensors='tf'   ,			data_format='channels_last'       )['pixel_values']
 lowerCAmelCase  							=      tok(tf.constant(['A picture of a cat']       )       )

 lowerCAmelCase  							=      original_model.image_encoder(_UpperCAmelCase   ,			training=_UpperCAmelCase       )
 lowerCAmelCase  							=      original_model.text_encoder(_UpperCAmelCase   ,			training=_UpperCAmelCase       )

 lowerCAmelCase  							=      tf.nn.la_normalize(_UpperCAmelCase   ,			axis=-1       )
 lowerCAmelCase  							=      tf.nn.la_normalize(_UpperCAmelCase   ,			axis=-1       )

 # Check whether original and HF model outputs match  -> np.allclose
 if not np.allclose(_UpperCAmelCase   ,			_UpperCAmelCase   ,			atol=1e-3       ):
  raise ValueError('The predicted image features are not the same.'       )
 if not np.allclose(_UpperCAmelCase   ,			_UpperCAmelCase   ,			atol=1e-3       ):
  raise ValueError('The predicted text features are not the same.'       )
 print('Model outputs match!'       )

 if save_model:
  # Create folder to save model
  if not os.path.isdir(_UpperCAmelCase       ):
   os.mkdir(_UpperCAmelCase       )
  # Save converted model and image processor
  hf_model.save_pretrained(_UpperCAmelCase       )
  processor.save_pretrained(_UpperCAmelCase       )

 if push_to_hub:
  # Push model and image processor to hub
  print('Pushing converted ALIGN to the hub...'       )
  processor.push_to_hub('align-base'       )
  hf_model.push_to_hub('align-base'       )


if __name__ == "__main__":
       __UpperCamelCase			:		str		    =   argparse.ArgumentParser()
       # Required parameters
       parser.add_argument(
           '''--checkpoint_path''',
           default='''./weights/model-weights''',
           type=str,
           help='''Path to the pretrained TF ALIGN checkpoint.''',
       )
       parser.add_argument(
           '''--pytorch_dump_folder_path''',
           default='''hf_model''',
           type=str,
           help='''Path to the output PyTorch model directory.''',
       )
       parser.add_argument('''--save_model''', action='''store_true''', help='''Save model to local''')
       parser.add_argument('''--push_to_hub''', action='''store_true''', help='''Push model and image processor to the hub''')

       __UpperCamelCase			:		int		    =   parser.parse_args()
       convert_align_checkpoint(args.checkpoint_path, args.pytorch_dump_folder_path, args.save_model, args.push_to_hub)





