
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						(					lowercase_):

  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					Any          =       self.config_class(**self.inputs_dict   )
        self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE	,   'hidden_sizes'   )   )
        self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE	,   'neck_hidden_sizes'   )   )
        self.parent.assertTrue(hasattr(_SCREAMING_SNAKE_CASE	,   'num_attention_heads'   )   )

class 	_A						:

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





        """simple docstring"""







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

  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					int          =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

        SCREAMING_SNAKE_CASE_			:					Union[str, Any]          =       None
        SCREAMING_SNAKE_CASE_			:					Any          =       None
        if self.use_labels:
              SCREAMING_SNAKE_CASE_			:					Optional[int]          =       ids_tensor([self.batch_size]	,   self.num_labels   )
              SCREAMING_SNAKE_CASE_			:					str          =       ids_tensor([self.batch_size, self.image_size, self.image_size]	,   self.num_labels   )

        SCREAMING_SNAKE_CASE_			:					Union[str, Any]          =       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	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					Optional[int]          =       TFMobileViTModel(config=_SCREAMING_SNAKE_CASE   )
        SCREAMING_SNAKE_CASE_			:					Dict          =       model(_SCREAMING_SNAKE_CASE	,   training=_SCREAMING_SNAKE_CASE   )
        SCREAMING_SNAKE_CASE_			:					Tuple          =       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	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					Union[str, Any]          =       self.num_labels
        SCREAMING_SNAKE_CASE_			:					Any          =       TFMobileViTForImageClassification(_SCREAMING_SNAKE_CASE   )
        SCREAMING_SNAKE_CASE_			:					Optional[Any]          =       model(_SCREAMING_SNAKE_CASE	,   labels=_SCREAMING_SNAKE_CASE	,   training=_SCREAMING_SNAKE_CASE   )
        self.parent.assertEqual(result.logits.shape	,   (self.batch_size, self.num_labels)   )

  def 	UpperCAmelCase      (			self	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					str          =       self.num_labels
        SCREAMING_SNAKE_CASE_			:					Optional[Any]          =       TFMobileViTForSemanticSegmentation(_SCREAMING_SNAKE_CASE   )
        SCREAMING_SNAKE_CASE_			:					Any          =       self.image_size // self.output_stride

        SCREAMING_SNAKE_CASE_			:					Dict          =       model(_SCREAMING_SNAKE_CASE	,   training=_SCREAMING_SNAKE_CASE   )
        self.parent.assertEqual(
            result.logits.shape	,   (self.batch_size, self.num_labels, expected_height, expected_width)   )

        SCREAMING_SNAKE_CASE_			:					Any          =       model(_SCREAMING_SNAKE_CASE	,   labels=_SCREAMING_SNAKE_CASE	,   training=_SCREAMING_SNAKE_CASE   )
        self.parent.assertEqual(
            result.logits.shape	,   (self.batch_size, self.num_labels, expected_height, expected_width)   )



  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					Any          =       self.prepare_config_and_inputs()
        SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_			:					Union[str, Any]          =       config_and_inputs
        SCREAMING_SNAKE_CASE_			:					Union[str, Any]          =       {'pixel_values': pixel_values}
        return config, inputs_dict

@require_tf
class 	_A						(					lowercase_				,       lowercase_				,       unittest.TestCase):
  SCREAMING_SNAKE_CASE      : Any    =					(
      (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
      if is_tf_available()
      else ()
  )
  SCREAMING_SNAKE_CASE      : int    =					(
      {"""feature-extraction""": TFMobileViTModel, """image-classification""": TFMobileViTForImageClassification}
      if is_tf_available()
      else {}
  )

  SCREAMING_SNAKE_CASE      : Dict    =					False
  SCREAMING_SNAKE_CASE      : Dict    =					False
  SCREAMING_SNAKE_CASE      : List[str]    =					False
  SCREAMING_SNAKE_CASE      : Tuple    =					False
  SCREAMING_SNAKE_CASE      : List[Any]    =					False

  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					List[str]          =       TFMobileViTModelTester(self   )
        SCREAMING_SNAKE_CASE_			:					str          =       TFMobileViTConfigTester(self	,   config_class=_SCREAMING_SNAKE_CASE	,   has_text_modality=_SCREAMING_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"""







        SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_			:					Dict          =       self.model_tester.prepare_config_and_inputs_for_common()

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

              SCREAMING_SNAKE_CASE_			:					List[str]          =       ['pixel_values']
              self.assertListEqual(arg_names[:1]	,   _SCREAMING_SNAKE_CASE   )

  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					str          =       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*_SCREAMING_SNAKE_CASE   )

  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        def check_hidden_states_output(_SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE   ):
              SCREAMING_SNAKE_CASE_			:					List[Any]          =       model_class(_SCREAMING_SNAKE_CASE   )

              SCREAMING_SNAKE_CASE_			:					Optional[Any]          =       model(**self._prepare_for_class(_SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE   )   )

              SCREAMING_SNAKE_CASE_			:					List[Any]          =       outputs.hidden_states

              SCREAMING_SNAKE_CASE_			:					int          =       5
              self.assertEqual(len(_SCREAMING_SNAKE_CASE   )	,   _SCREAMING_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.
              SCREAMING_SNAKE_CASE_			:					List[Any]          =       2
              for i in range(len(_SCREAMING_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   )

        SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_			:					Tuple          =       self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
              SCREAMING_SNAKE_CASE_			:					Union[str, Any]          =       True
              check_hidden_states_output(_SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE   )

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

              check_hidden_states_output(_SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE   )

  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					str          =       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*_SCREAMING_SNAKE_CASE   )

  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					Tuple          =       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*_SCREAMING_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	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE=2e-1	,   _SCREAMING_SNAKE_CASE=2e-1   ):





        """simple docstring"""







        self.assertTrue(np.allclose(_SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE	,   atol=_SCREAMING_SNAKE_CASE	,   rtol=_SCREAMING_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"""







        SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_			:					Any          =       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_			:					int          =       model_class(_SCREAMING_SNAKE_CASE   )
                    if getattr(_SCREAMING_SNAKE_CASE	,   'hf_compute_loss'	,   _SCREAMING_SNAKE_CASE   ):
                          super().test_keras_fit()

  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_    ,  SCREAMING_SNAKE_CASE_			:					Any          =       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_			:					Tuple          =       5

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

                    # Test that model correctly compute the loss with kwargs
                    SCREAMING_SNAKE_CASE_			:					str          =       self._prepare_for_class(inputs_dict.copy()	,   _SCREAMING_SNAKE_CASE	,   return_labels=_SCREAMING_SNAKE_CASE   )
                    SCREAMING_SNAKE_CASE_			:					Union[str, Any]          =       {'input_ids', 'pixel_values', 'input_features'}
                    SCREAMING_SNAKE_CASE_			:					Optional[int]          =       possible_input_names.intersection(set(_SCREAMING_SNAKE_CASE   )   ).pop()
                    SCREAMING_SNAKE_CASE_			:					List[str]          =       prepared_for_class.pop(_SCREAMING_SNAKE_CASE   )

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

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

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

                    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[str]          =       prepared_for_class[value]

                    SCREAMING_SNAKE_CASE_			:					Tuple          =       tuple(_SCREAMING_SNAKE_CASE   )

                    # Send to model
                    SCREAMING_SNAKE_CASE_			:					Optional[int]          =       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]:
              SCREAMING_SNAKE_CASE_			:					Dict          =       TFMobileViTModel.from_pretrained(_SCREAMING_SNAKE_CASE   )
              self.assertIsNotNone(_SCREAMING_SNAKE_CASE   )

def 				A_					(							):

      """simple docstring"""



      SCREAMING_SNAKE_CASE_			:					int          =       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'					)
      return image



@require_tf
class 	_A						(					unittest.TestCase):

  @slow
  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					str          =       TFMobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small'   )

        SCREAMING_SNAKE_CASE_			:					int          =       MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small'   )
        SCREAMING_SNAKE_CASE_			:					Union[str, Any]          =       prepare_img()
        SCREAMING_SNAKE_CASE_			:					Tuple          =       image_processor(images=_SCREAMING_SNAKE_CASE	,   return_tensors='tf'   )

        # forward pass
        SCREAMING_SNAKE_CASE_			:					Tuple          =       model(**_SCREAMING_SNAKE_CASE	,   training=_SCREAMING_SNAKE_CASE   )

        # verify the logits
        SCREAMING_SNAKE_CASE_			:					Dict          =       tf.TensorShape((1, 1000)   )
        self.assertEqual(outputs.logits.shape	,   _SCREAMING_SNAKE_CASE   )

        SCREAMING_SNAKE_CASE_			:					str          =       tf.constant([-1.9364, -1.2327, -0.4653]   )

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



  @slow
  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					Any          =       TFMobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'   )

        SCREAMING_SNAKE_CASE_			:					Union[str, Any]          =       MobileViTImageProcessor.from_pretrained('apple/deeplabv3-mobilevit-xx-small'   )

        SCREAMING_SNAKE_CASE_			:					List[str]          =       prepare_img()
        SCREAMING_SNAKE_CASE_			:					List[str]          =       image_processor(images=_SCREAMING_SNAKE_CASE	,   return_tensors='tf'   )

        # forward pass
        SCREAMING_SNAKE_CASE_			:					Any          =       model(inputs.pixel_values	,   training=_SCREAMING_SNAKE_CASE   )
        SCREAMING_SNAKE_CASE_			:					Optional[int]          =       outputs.logits

        # verify the logits
        SCREAMING_SNAKE_CASE_			:					Tuple          =       tf.TensorShape((1, 21, 32, 32)   )
        self.assertEqual(logits.shape	,   _SCREAMING_SNAKE_CASE   )

        SCREAMING_SNAKE_CASE_			:					Any          =       tf.constant(
            [
                [[6.9713, 6.9786, 7.2422], [7.2893, 7.2825, 7.4446], [7.6580, 7.8797, 7.9420]],
                [[-10.6869, -10.3250, -10.3471], [-10.4228, -9.9868, -9.7132], [-11.0405, -11.0221, -10.7318]],
                [[-3.3089, -2.8539, -2.6740], [-3.2706, -2.5621, -2.5108], [-3.2534, -2.6615, -2.6651]],
            ]   )

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









import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils import AddedToken
from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_mpnet import MPNetTokenizer


lowerCAmelCase       :				List[Any]         =					logging.get_logger(__name__)

lowerCAmelCase       :				Any         =					{'vocab_file': 'vocab.txt', 'tokenizer_file': 'tokenizer.json'}

lowerCAmelCase       :				Any         =					{
    'vocab_file': {
        'microsoft/mpnet-base': 'https://huggingface.co/microsoft/mpnet-base/resolve/main/vocab.txt',
    },
    'tokenizer_file': {
        'microsoft/mpnet-base': 'https://huggingface.co/microsoft/mpnet-base/resolve/main/tokenizer.json',
    },
}

lowerCAmelCase       :				str         =					{
    'microsoft/mpnet-base': 5_12,
}

lowerCAmelCase       :				Optional[Any]         =					{
    'microsoft/mpnet-base': {'do_lower_case': True},
}
class 	_A						(					__magic_name__):
  SCREAMING_SNAKE_CASE      : Tuple    =					VOCAB_FILES_NAMES
  SCREAMING_SNAKE_CASE      : List[Any]    =					PRETRAINED_VOCAB_FILES_MAP
  SCREAMING_SNAKE_CASE      : Dict    =					PRETRAINED_INIT_CONFIGURATION
  SCREAMING_SNAKE_CASE      : str    =					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
  SCREAMING_SNAKE_CASE      : Dict    =					MPNetTokenizer
  SCREAMING_SNAKE_CASE      : Any    =					['''input_ids''', '''attention_mask''']

  def __init__(			self	,   _SCREAMING_SNAKE_CASE=None	,   _SCREAMING_SNAKE_CASE=None	,   _SCREAMING_SNAKE_CASE=True	,   _SCREAMING_SNAKE_CASE="<s>"	,   _SCREAMING_SNAKE_CASE="</s>"	,   _SCREAMING_SNAKE_CASE="</s>"	,   _SCREAMING_SNAKE_CASE="<s>"	,   _SCREAMING_SNAKE_CASE="[UNK]"	,   _SCREAMING_SNAKE_CASE="<pad>"	,   _SCREAMING_SNAKE_CASE="<mask>"	,   _SCREAMING_SNAKE_CASE=True	,   _SCREAMING_SNAKE_CASE=None	,   **_SCREAMING_SNAKE_CASE	,   ):





        """simple docstring"""







        super().__init__(
            _SCREAMING_SNAKE_CASE	,   tokenizer_file=_SCREAMING_SNAKE_CASE	,   do_lower_case=_SCREAMING_SNAKE_CASE	,   bos_token=_SCREAMING_SNAKE_CASE	,   eos_token=_SCREAMING_SNAKE_CASE	,   sep_token=_SCREAMING_SNAKE_CASE	,   cls_token=_SCREAMING_SNAKE_CASE	,   unk_token=_SCREAMING_SNAKE_CASE	,   pad_token=_SCREAMING_SNAKE_CASE	,   mask_token=_SCREAMING_SNAKE_CASE	,   tokenize_chinese_chars=_SCREAMING_SNAKE_CASE	,   strip_accents=_SCREAMING_SNAKE_CASE	,   **_SCREAMING_SNAKE_CASE	,   )

        SCREAMING_SNAKE_CASE_			:					Optional[Any]          =       json.loads(self.backend_tokenizer.normalizer.__getstate__()   )
        if (
            pre_tok_state.get('lowercase'	,   _SCREAMING_SNAKE_CASE   ) != do_lower_case
            or pre_tok_state.get('strip_accents'	,   _SCREAMING_SNAKE_CASE   ) != strip_accents
        ):
              SCREAMING_SNAKE_CASE_			:					Any          =       getattr(_SCREAMING_SNAKE_CASE	,   pre_tok_state.pop('type'   )   )
              SCREAMING_SNAKE_CASE_			:					Dict          =       do_lower_case
              SCREAMING_SNAKE_CASE_			:					Union[str, Any]          =       strip_accents
              SCREAMING_SNAKE_CASE_			:					Tuple          =       pre_tok_class(**_SCREAMING_SNAKE_CASE   )

        SCREAMING_SNAKE_CASE_			:					Optional[Any]          =       do_lower_case

  @property
  def 	UpperCAmelCase      (			self   ):





        """simple docstring"""







        if self._mask_token is None:
              if self.verbose:
                    logger.error('Using mask_token, but it is not set yet.'   )
              return None
        return str(self._mask_token   )

  @mask_token.setter
  def 	UpperCAmelCase      (			self	,   _SCREAMING_SNAKE_CASE   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					Optional[Any]          =       AddedToken(_SCREAMING_SNAKE_CASE	,   lstrip=_SCREAMING_SNAKE_CASE	,   rstrip=_SCREAMING_SNAKE_CASE   ) if isinstance(_SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE   ) else value
        SCREAMING_SNAKE_CASE_			:					List[Any]          =       value

  def 	UpperCAmelCase      (			self	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE=None   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					List[str]          =       [self.bos_token_id] + token_ids_a + [self.eos_token_id]
        if token_ids_a is None:
              return output

        return output + [self.eos_token_id] + token_ids_a + [self.eos_token_id]

  def 	UpperCAmelCase      (			self	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE = None   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					str          =       [self.sep_token_id]
        SCREAMING_SNAKE_CASE_			:					int          =       [self.cls_token_id]

        if token_ids_a is None:
              return len(cls + token_ids_a + sep   ) * [0]
        return len(cls + token_ids_a + sep + sep + token_ids_a + sep   ) * [0]



  def 	UpperCAmelCase      (			self	,   _SCREAMING_SNAKE_CASE	,   _SCREAMING_SNAKE_CASE = None   ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_			:					Tuple          =       self._tokenizer.model.save(_SCREAMING_SNAKE_CASE	,   name=_SCREAMING_SNAKE_CASE   )
        return tuple(_SCREAMING_SNAKE_CASE   )






