

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__							( UpperCAmelCase							):







  """simple docstring"""




  def 			_lowercase   (      self     :			Dict		)       ->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE			:   Dict	  = self.config_class(**self.inputs_dict		)
        self.parent.assertTrue(hasattr(UpperCAmelCase__					,					"""hidden_sizes"""		)		)
        self.parent.assertTrue(hasattr(UpperCAmelCase__					,					"""neck_hidden_sizes"""		)		)
        self.parent.assertTrue(hasattr(UpperCAmelCase__					,					"""num_attention_heads"""		)		)







class 							a__							:







  """simple docstring"""




  def __init__(      self     :			int					,					UpperCAmelCase__     :			int					,					UpperCAmelCase__     :			str=1_3					,					UpperCAmelCase__     :			Optional[Any]=3_2					,					UpperCAmelCase__     :			int=2					,					UpperCAmelCase__     :			List[str]=3					,					UpperCAmelCase__     :			List[Any]=6_4_0					,					UpperCAmelCase__     :			Tuple=4					,					UpperCAmelCase__     :			int="silu"					,					UpperCAmelCase__     :			Optional[int]=3					,					UpperCAmelCase__     :			Tuple=3_2					,					UpperCAmelCase__     :			Union[str, Any]=0.1					,					UpperCAmelCase__     :			Tuple=0.1					,					UpperCAmelCase__     :			Optional[Any]=0.1					,					UpperCAmelCase__     :			Dict=0.02					,					UpperCAmelCase__     :			str=True					,					UpperCAmelCase__     :			Union[str, Any]=True					,					UpperCAmelCase__     :			Tuple=1_0					,					UpperCAmelCase__     :			Tuple=None					,					)       ->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE			:   List[Any]	  = parent
        SCREAMING_SNAKE_CASE			:   Union[str, Any]	  = batch_size
        SCREAMING_SNAKE_CASE			:   List[Any]	  = image_size
        SCREAMING_SNAKE_CASE			:   Tuple	  = patch_size
        SCREAMING_SNAKE_CASE			:   Optional[Any]	  = num_channels
        SCREAMING_SNAKE_CASE			:   Tuple	  = last_hidden_size
        SCREAMING_SNAKE_CASE			:   Optional[int]	  = num_attention_heads
        SCREAMING_SNAKE_CASE			:   Tuple	  = hidden_act
        SCREAMING_SNAKE_CASE			:   int	  = conv_kernel_size
        SCREAMING_SNAKE_CASE			:   Optional[Any]	  = output_stride
        SCREAMING_SNAKE_CASE			:   Any	  = hidden_dropout_prob
        SCREAMING_SNAKE_CASE			:   int	  = attention_probs_dropout_prob
        SCREAMING_SNAKE_CASE			:   Union[str, Any]	  = classifier_dropout_prob
        SCREAMING_SNAKE_CASE			:   Optional[Any]	  = use_labels
        SCREAMING_SNAKE_CASE			:   Tuple	  = is_training
        SCREAMING_SNAKE_CASE			:   int	  = num_labels
        SCREAMING_SNAKE_CASE			:   Tuple	  = initializer_range
        SCREAMING_SNAKE_CASE			:   Union[str, Any]	  = scope


  def 			_lowercase   (      self     :			Optional[Any]		)       ->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE			:   Union[str, Any]	  = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

        SCREAMING_SNAKE_CASE			:   List[Any]	  = None
        SCREAMING_SNAKE_CASE			:   Optional[Any]	  = None
        if self.use_labels:
              SCREAMING_SNAKE_CASE			:   Optional[Any]	  = ids_tensor([self.batch_size]					,					self.num_labels		)
              SCREAMING_SNAKE_CASE			:   List[Any]	  = ids_tensor([self.batch_size, self.image_size, self.image_size]					,					self.num_labels		)

        SCREAMING_SNAKE_CASE			:   Optional[int]	  = self.get_config()

        return config, pixel_values, labels, pixel_labels


  def 			_lowercase   (      self     :			str		)       ->Union[str, Any]:
        """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 			_lowercase   (      self     :			List[str]					,					UpperCAmelCase__     :			Dict					,					UpperCAmelCase__     :			Optional[Any]					,					UpperCAmelCase__     :			Optional[Any]					,					UpperCAmelCase__     :			Dict		)       ->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE			:   Optional[int]	  = TFMobileViTModel(config=UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE			:   Union[str, Any]	  = model(UpperCAmelCase__					,					training=UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE			:   Dict	  = 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 			_lowercase   (      self     :			str					,					UpperCAmelCase__     :			str					,					UpperCAmelCase__     :			Dict					,					UpperCAmelCase__     :			Union[str, Any]					,					UpperCAmelCase__     :			Tuple		)       ->List[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE			:   Tuple	  = self.num_labels
        SCREAMING_SNAKE_CASE			:   Any	  = TFMobileViTForImageClassification(UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE			:   Any	  = model(UpperCAmelCase__					,					labels=UpperCAmelCase__					,					training=UpperCAmelCase__		)
        self.parent.assertEqual(result.logits.shape					,					(self.batch_size, self.num_labels)		)


  def 			_lowercase   (      self     :			int					,					UpperCAmelCase__     :			str					,					UpperCAmelCase__     :			Optional[Any]					,					UpperCAmelCase__     :			str					,					UpperCAmelCase__     :			Tuple		)       ->int:
        """simple docstring"""







        SCREAMING_SNAKE_CASE			:   Optional[int]	  = self.num_labels
        SCREAMING_SNAKE_CASE			:   Dict	  = TFMobileViTForSemanticSegmentation(UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE			:   Dict	  = self.image_size // self.output_stride

        SCREAMING_SNAKE_CASE			:   int	  = model(UpperCAmelCase__					,					training=UpperCAmelCase__		)
        self.parent.assertEqual(
            result.logits.shape					,					(self.batch_size, self.num_labels, expected_height, expected_width)		)

        SCREAMING_SNAKE_CASE			:   List[str]	  = model(UpperCAmelCase__					,					labels=UpperCAmelCase__					,					training=UpperCAmelCase__		)
        self.parent.assertEqual(
            result.logits.shape					,					(self.batch_size, self.num_labels, expected_height, expected_width)		)




  def 			_lowercase   (      self     :			Dict		)       ->Optional[Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE			:   List[str]	  = self.prepare_config_and_inputs()
        SCREAMING_SNAKE_CASE  ,						SCREAMING_SNAKE_CASE  ,						SCREAMING_SNAKE_CASE  ,						SCREAMING_SNAKE_CASE			:   Optional[Any]	  = config_and_inputs
        SCREAMING_SNAKE_CASE			:   List[str]	  = {"""pixel_values""": pixel_values}
        return config, inputs_dict







@require_tf
class 							a__							( UpperCAmelCase						,      UpperCAmelCase						,      unittest.TestCase							):







  """simple docstring"""




  UpperCAmelCase__   :			List[Any]      							=(
      (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
      if is_tf_available()
      else ()
  )
  UpperCAmelCase__   :			str      							=(
      {"""feature-extraction""": TFMobileViTModel, """image-classification""": TFMobileViTForImageClassification}
      if is_tf_available()
      else {}
  )

  UpperCAmelCase__   :			Dict      							=False
  UpperCAmelCase__   :			Optional[int]      							=False
  UpperCAmelCase__   :			str      							=False
  UpperCAmelCase__   :			int      							=False
  UpperCAmelCase__   :			Tuple      							=False


  def 			_lowercase   (      self     :			Dict		)       ->Union[str, Any]:
        """simple docstring"""







        SCREAMING_SNAKE_CASE			:   str	  = TFMobileViTModelTester(self		)
        SCREAMING_SNAKE_CASE			:   List[str]	  = TFMobileViTConfigTester(self					,					config_class=UpperCAmelCase__					,					has_text_modality=UpperCAmelCase__		)


  def 			_lowercase   (      self     :			Optional[int]		)       ->Optional[Any]:
        """simple docstring"""







        self.config_tester.run_common_tests()


  @unittest.skip(reason="""MobileViT does not use inputs_embeds"""		)
  def 			_lowercase   (      self     :			Union[str, Any]		)       ->List[Any]:
        """simple docstring"""







        pass


  @unittest.skip(reason="""MobileViT does not support input and output embeddings"""		)
  def 			_lowercase   (      self     :			Dict		)       ->str:
        """simple docstring"""







        pass


  @unittest.skip(reason="""MobileViT does not output attentions"""		)
  def 			_lowercase   (      self     :			Optional[Any]		)       ->Optional[Any]:
        """simple docstring"""







        pass


  def 			_lowercase   (      self     :			Union[str, Any]		)       ->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE  ,						SCREAMING_SNAKE_CASE			:   Union[str, Any]	  = self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE			:   str	  = model_class(UpperCAmelCase__		)
              SCREAMING_SNAKE_CASE			:   Optional[int]	  = inspect.signature(model.call		)
              # signature.parameters is an OrderedDict => so arg_names order is deterministic
              SCREAMING_SNAKE_CASE			:   Any	  = [*signature.parameters.keys()]

              SCREAMING_SNAKE_CASE			:   Any	  = ["""pixel_values"""]
              self.assertListEqual(arg_names[:1]					,					UpperCAmelCase__		)


  def 			_lowercase   (      self     :			List[str]		)       ->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE			:   Tuple	  = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*UpperCAmelCase__		)


  def 			_lowercase   (      self     :			Tuple		)       ->Tuple:
        """simple docstring"""







        def check_hidden_states_output(UpperCAmelCase__     :			Tuple					,					UpperCAmelCase__     :			str					,					UpperCAmelCase__     :			Optional[int]		):
              SCREAMING_SNAKE_CASE			:   str	  = model_class(UpperCAmelCase__		)

              SCREAMING_SNAKE_CASE			:   Any	  = model(**self._prepare_for_class(UpperCAmelCase__					,					UpperCAmelCase__		)		)

              SCREAMING_SNAKE_CASE			:   List[str]	  = outputs.hidden_states

              SCREAMING_SNAKE_CASE			:   List[Any]	  = 5
              self.assertEqual(len(UpperCAmelCase__		)					,					UpperCAmelCase__		)

              # MobileViT's feature maps are of shape (batch_size, num_channels, height, width)
              # with the width and height being successively divided by 2.
              SCREAMING_SNAKE_CASE			:   str	  = 2
              for i in range(len(UpperCAmelCase__		)		):
                    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		)

        SCREAMING_SNAKE_CASE  ,						SCREAMING_SNAKE_CASE			:   Optional[Any]	  = self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE			:   Any	  = True
              check_hidden_states_output(UpperCAmelCase__					,					UpperCAmelCase__					,					UpperCAmelCase__		)

              # check that output_hidden_states also work using config
              del inputs_dict["output_hidden_states"]
              SCREAMING_SNAKE_CASE			:   int	  = True

              check_hidden_states_output(UpperCAmelCase__					,					UpperCAmelCase__					,					UpperCAmelCase__		)


  def 			_lowercase   (      self     :			Dict		)       ->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE			:   Union[str, Any]	  = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__		)


  def 			_lowercase   (      self     :			Union[str, Any]		)       ->Dict:
        """simple docstring"""







        SCREAMING_SNAKE_CASE			:   int	  = self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*UpperCAmelCase__		)


  @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 			_lowercase   (      self     :			Union[str, Any]		)       ->str:
        """simple docstring"""







        super().test_dataset_conversion()


  def 			_lowercase   (      self     :			Tuple					,					UpperCAmelCase__     :			Optional[int]					,					UpperCAmelCase__     :			Optional[int]					,					UpperCAmelCase__     :			Optional[int]=2e-1					,					UpperCAmelCase__     :			List[str]=2e-1		)       ->Optional[int]:
        """simple docstring"""







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


  @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 			_lowercase   (      self     :			Union[str, Any]		)       ->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE  ,						SCREAMING_SNAKE_CASE			:   List[str]	  = 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":
                    SCREAMING_SNAKE_CASE			:   Dict	  = model_class(UpperCAmelCase__		)
                    if getattr(UpperCAmelCase__					,					"""hf_compute_loss"""					,					UpperCAmelCase__		):
                          super().test_keras_fit()


  def 			_lowercase   (      self     :			int		)       ->int:
        """simple docstring"""







        SCREAMING_SNAKE_CASE  ,						SCREAMING_SNAKE_CASE			:   List[str]	  = 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":
                    SCREAMING_SNAKE_CASE			:   str	  = 5

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

                    # Test that model correctly compute the loss with kwargs
                    SCREAMING_SNAKE_CASE			:   List[str]	  = self._prepare_for_class(inputs_dict.copy()					,					UpperCAmelCase__					,					return_labels=UpperCAmelCase__		)
                    SCREAMING_SNAKE_CASE			:   Dict	  = {"""input_ids""", """pixel_values""", """input_features"""}
                    SCREAMING_SNAKE_CASE			:   int	  = possible_input_names.intersection(set(UpperCAmelCase__		)		).pop()
                    SCREAMING_SNAKE_CASE			:   str	  = prepared_for_class.pop(UpperCAmelCase__		)

                    SCREAMING_SNAKE_CASE			:   Optional[int]	  = model(UpperCAmelCase__					,					**UpperCAmelCase__		)[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
                    SCREAMING_SNAKE_CASE			:   str	  = self._prepare_for_class(inputs_dict.copy()					,					UpperCAmelCase__					,					return_labels=UpperCAmelCase__		)
                    SCREAMING_SNAKE_CASE			:   str	  = {"""input_ids""", """pixel_values""", """input_features"""}
                    SCREAMING_SNAKE_CASE			:   int	  = possible_input_names.intersection(set(UpperCAmelCase__		)		).pop()
                    SCREAMING_SNAKE_CASE			:   Union[str, Any]	  = prepared_for_class.pop(UpperCAmelCase__		)
                    if "labels" in prepared_for_class:
                          SCREAMING_SNAKE_CASE			:   List[str]	  = prepared_for_class["""labels"""].numpy()
                          if len(labels.shape		) > 1 and labels.shape[1] != 1:
                                # labels[0] = -100
                                SCREAMING_SNAKE_CASE			:   List[Any]	  = tf.convert_to_tensor(UpperCAmelCase__		)
                                SCREAMING_SNAKE_CASE			:   Union[str, Any]	  = model(UpperCAmelCase__					,					**UpperCAmelCase__		)[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
                    SCREAMING_SNAKE_CASE			:   Optional[Any]	  = self._prepare_for_class(inputs_dict.copy()					,					UpperCAmelCase__					,					return_labels=UpperCAmelCase__		)
                    SCREAMING_SNAKE_CASE			:   Union[str, Any]	  = model(UpperCAmelCase__		)[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
                    SCREAMING_SNAKE_CASE			:   Dict	  = self._prepare_for_class(inputs_dict.copy()					,					UpperCAmelCase__					,					return_labels=UpperCAmelCase__		)

                    # Get keys that were added with the _prepare_for_class function
                    SCREAMING_SNAKE_CASE			:   Union[str, Any]	  = prepared_for_class.keys() - inputs_dict.keys()
                    SCREAMING_SNAKE_CASE			:   Optional[Any]	  = inspect.signature(model.call		).parameters
                    SCREAMING_SNAKE_CASE			:   Optional[Any]	  = list(signature.keys()		)

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

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

                    for index, value in sorted_tuple_index_mapping:
                          SCREAMING_SNAKE_CASE			:   List[Any]	  = prepared_for_class[value]

                    SCREAMING_SNAKE_CASE			:   Optional[Any]	  = tuple(UpperCAmelCase__		)

                    # Send to model
                    SCREAMING_SNAKE_CASE			:   List[Any]	  = model(tuple_input[:-1]		)[0]

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




  @slow
  def 			_lowercase   (      self     :			Any		)       ->Optional[int]:
        """simple docstring"""







        for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
              SCREAMING_SNAKE_CASE			:   Tuple	  = TFMobileViTModel.from_pretrained(UpperCAmelCase__		)
              self.assertIsNotNone(UpperCAmelCase__		)






def        __lowercase   (  )  ->    int:
      SCREAMING_SNAKE_CASE			:   List[Any]	  = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      )
      return image







@require_tf
class 							a__							( unittest.TestCase							):







  """simple docstring"""




  @slow
  def 			_lowercase   (      self     :			Optional[int]		)       ->Any:
        """simple docstring"""







        SCREAMING_SNAKE_CASE			:   List[str]	  = TFMobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small"""		)

        SCREAMING_SNAKE_CASE			:   str	  = MobileViTImageProcessor.from_pretrained("""apple/mobilevit-xx-small"""		)
        SCREAMING_SNAKE_CASE			:   Tuple	  = prepare_img()
        SCREAMING_SNAKE_CASE			:   str	  = image_processor(images=UpperCAmelCase__					,					return_tensors="""tf"""		)

        # forward pass
        SCREAMING_SNAKE_CASE			:   Tuple	  = model(**UpperCAmelCase__					,					training=UpperCAmelCase__		)

        # verify the logits
        SCREAMING_SNAKE_CASE			:   List[Any]	  = tf.TensorShape((1, 1_0_0_0)		)
        self.assertEqual(outputs.logits.shape					,					UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE			:   Optional[int]	  = tf.constant([-1.93_64, -1.23_27, -0.46_53]		)

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




  @slow
  def 			_lowercase   (      self     :			List[str]		)       ->Tuple:
        """simple docstring"""







        SCREAMING_SNAKE_CASE			:   Union[str, Any]	  = TFMobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""		)

        SCREAMING_SNAKE_CASE			:   Tuple	  = MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""		)

        SCREAMING_SNAKE_CASE			:   Union[str, Any]	  = prepare_img()
        SCREAMING_SNAKE_CASE			:   Dict	  = image_processor(images=UpperCAmelCase__					,					return_tensors="""tf"""		)

        # forward pass
        SCREAMING_SNAKE_CASE			:   List[str]	  = model(inputs.pixel_values					,					training=UpperCAmelCase__		)
        SCREAMING_SNAKE_CASE			:   Any	  = outputs.logits

        # verify the logits
        SCREAMING_SNAKE_CASE			:   Tuple	  = tf.TensorShape((1, 2_1, 3_2, 3_2)		)
        self.assertEqual(logits.shape					,					UpperCAmelCase__		)

        SCREAMING_SNAKE_CASE			:   List[str]	  = tf.constant(
            [
                [[6.97_13, 6.97_86, 7.24_22], [7.28_93, 7.28_25, 7.44_46], [7.65_80, 7.87_97, 7.94_20]],
                [[-10.68_69, -10.32_50, -10.34_71], [-10.42_28, -9.98_68, -9.71_32], [-11.04_05, -11.02_21, -10.73_18]],
                [[-3.30_89, -2.85_39, -2.67_40], [-3.27_06, -2.56_21, -2.51_08], [-3.25_34, -2.66_15, -2.66_51]],
            ]		)

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







from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_sentencepiece_available,
    is_speech_available,
    is_torch_available,
)


UpperCAmelCase__			:  Tuple					     =     {
    """configuration_speech_to_text_2""": ["""SPEECH_TO_TEXT_2_PRETRAINED_CONFIG_ARCHIVE_MAP""", """Speech2Text2Config"""],
    """processing_speech_to_text_2""": ["""Speech2Text2Processor"""],
    """tokenization_speech_to_text_2""": ["""Speech2Text2Tokenizer"""],
}


try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  UpperCAmelCase__			:  Tuple					     =     [
      """SPEECH_TO_TEXT_2_PRETRAINED_MODEL_ARCHIVE_LIST""",
      """Speech2Text2ForCausalLM""",
      """Speech2Text2PreTrainedModel""",
  ]


if TYPE_CHECKING:
  from .configuration_speech_to_text_a import SPEECH_TO_TEXT_2_PRETRAINED_CONFIG_ARCHIVE_MAP, SpeechaTextaConfig
  from .processing_speech_to_text_a import SpeechaTextaProcessor
  from .tokenization_speech_to_text_a import SpeechaTextaTokenizer

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .modeling_speech_to_text_a import (
        SPEECH_TO_TEXT_2_PRETRAINED_MODEL_ARCHIVE_LIST,
        SpeechaTextaForCausalLM,
        SpeechaTextaPreTrainedModel,
    )

else:
  import sys

  UpperCAmelCase__			:  Optional[int]					     =     _LazyModule(__name__, globals()["""__file__"""], _import_structure, module_spec=__spec__)




