





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



      def    __a (					self					)      ->   Tuple:



             '''simple docstring'''

             _snake_case      :							List[Any]     				=						self.config_class(**self.inputs_dict					)
             self.parent.assertTrue(hasattr(lowercase_     ,  '''hidden_sizes'''					)					)
             self.parent.assertTrue(hasattr(lowercase_     ,  '''neck_hidden_sizes'''					)					)
             self.parent.assertTrue(hasattr(lowercase_     ,  '''num_attention_heads'''					)					)


class 				A    :



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



             '''simple docstring'''

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



      def    __a (					self					)      ->   List[Any]:



             '''simple docstring'''

             _snake_case      :							Dict     				=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

             _snake_case      :							Any     				=						None
             _snake_case      :							Dict     				=						None
             if self.use_labels:
                    _snake_case      :							Any     				=						ids_tensor([self.batch_size]     ,  self.num_labels					)
                    _snake_case      :							Tuple     				=						ids_tensor([self.batch_size, self.image_size, self.image_size]     ,  self.num_labels					)

             _snake_case      :							Optional[Any]     				=						self.get_config()

             return config, pixel_values, labels, pixel_labels



      def    __a (					self					)      ->   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    __a (					self     ,  lowercase_     ,  lowercase_     ,  lowercase_     ,  lowercase_					)      ->   Union[str, Any]:



             '''simple docstring'''

             _snake_case      :							int     				=						TFMobileViTModel(config=lowercase_					)
             _snake_case      :							List[Any]     				=						model(lowercase_     ,  training=lowercase_					)
             _snake_case      :							Any     				=						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    __a (					self     ,  lowercase_     ,  lowercase_     ,  lowercase_     ,  lowercase_					)      ->   Dict:



             '''simple docstring'''

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



      def    __a (					self     ,  lowercase_     ,  lowercase_     ,  lowercase_     ,  lowercase_					)      ->   Dict:



             '''simple docstring'''

             _snake_case      :							List[str]     				=						self.num_labels
             _snake_case      :							int     				=						TFMobileViTForSemanticSegmentation(lowercase_					)
             _snake_case      :							List[str]     				=						self.image_size // self.output_stride

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

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



      def    __a (					self					)      ->   Tuple:



             '''simple docstring'''

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


@require_tf
class 				A    (__UpperCAmelCase       ,__UpperCAmelCase       ,unittest.TestCase				):
      _SCREAMING_SNAKE_CASE					=							(
          (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
          if is_tf_available()
          else ()
      )
      _SCREAMING_SNAKE_CASE					=							(
          {"""feature-extraction""": TFMobileViTModel, """image-classification""": TFMobileViTForImageClassification}
          if is_tf_available()
          else {}
      )

      _SCREAMING_SNAKE_CASE					=							False
      _SCREAMING_SNAKE_CASE					=							False
      _SCREAMING_SNAKE_CASE					=							False
      _SCREAMING_SNAKE_CASE					=							False
      _SCREAMING_SNAKE_CASE					=							False



      def    __a (					self					)      ->   Optional[int]:



             '''simple docstring'''

             _snake_case      :							Tuple     				=						TFMobileViTModelTester(self					)
             _snake_case      :							Any     				=						TFMobileViTConfigTester(self     ,  config_class=lowercase_     ,  has_text_modality=lowercase_					)



      def    __a (					self					)      ->   Dict:



             '''simple docstring'''

             self.config_tester.run_common_tests()



      @unittest.skip(reason='''MobileViT does not use inputs_embeds'''					)
      def    __a (					self					)      ->   str:



             '''simple docstring'''

             pass



      @unittest.skip(reason='''MobileViT does not support input and output embeddings'''					)
      def    __a (					self					)      ->   Optional[Any]:



             '''simple docstring'''

             pass



      @unittest.skip(reason='''MobileViT does not output attentions'''					)
      def    __a (					self					)      ->   List[str]:



             '''simple docstring'''

             pass



      def    __a (					self					)      ->   int:



             '''simple docstring'''

             _snake_case				,    _snake_case      :							Any     				=						self.model_tester.prepare_config_and_inputs_for_common()

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

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



      def    __a (					self					)      ->   Optional[Any]:



             '''simple docstring'''

             _snake_case      :							Dict     				=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_model(*lowercase_					)



      def    __a (					self					)      ->   Dict:



             '''simple docstring'''

             def check_hidden_states_output(lowercase_     ,  lowercase_     ,  lowercase_					):
                    _snake_case      :							Tuple     				=						model_class(lowercase_					)

                    _snake_case      :							int     				=						model(**self._prepare_for_class(lowercase_     ,  lowercase_					)					)

                    _snake_case      :							Optional[int]     				=						outputs.hidden_states

                    _snake_case      :							int     				=						5
                    self.assertEqual(len(lowercase_					)     ,  lowercase_					)

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

             _snake_case				,    _snake_case      :							Optional[int]     				=						self.model_tester.prepare_config_and_inputs_for_common()

             for model_class in self.all_model_classes:
                    _snake_case      :							List[Any]     				=						True
                    check_hidden_states_output(lowercase_     ,  lowercase_     ,  lowercase_					)

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

                    check_hidden_states_output(lowercase_     ,  lowercase_     ,  lowercase_					)



      def    __a (					self					)      ->   Dict:



             '''simple docstring'''

             _snake_case      :							Any     				=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_image_classification(*lowercase_					)



      def    __a (					self					)      ->   Optional[Any]:



             '''simple docstring'''

             _snake_case      :							Union[str, Any]     				=						self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_for_semantic_segmentation(*lowercase_					)



      @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    __a (					self					)      ->   Tuple:



             '''simple docstring'''

             super().test_dataset_conversion()



      def    __a (					self     ,  lowercase_     ,  lowercase_     ,  lowercase_=2E-1     ,  lowercase_=2E-1					)      ->   Optional[int]:



             '''simple docstring'''

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



      @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    __a (					self					)      ->   Optional[int]:



             '''simple docstring'''

             _snake_case				,    _snake_case      :							int     				=						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":
                           _snake_case      :							Union[str, Any]     				=						model_class(lowercase_					)
                           if getattr(lowercase_     ,  '''hf_compute_loss'''     ,  lowercase_					):
                                  super().test_keras_fit()



      def    __a (					self					)      ->   Any:



             '''simple docstring'''

             _snake_case				,    _snake_case      :							Dict     				=						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":
                           _snake_case      :							str     				=						5

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

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

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

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

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

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

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

                           _snake_case      :							Optional[int]     				=						tuple(lowercase_					)

                           # Send to model
                           _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    __a (					self					)      ->   Tuple:



             '''simple docstring'''

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




def 						A_			(  )			->						Optional[int]:
       _snake_case      :							List[str]     				=						Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''  )
       return image

@require_tf
class 				A    (unittest.TestCase				):



      @slow
      def    __a (					self					)      ->   Optional[int]:



             '''simple docstring'''

             _snake_case      :							Tuple     				=						TFMobileViTForImageClassification.from_pretrained('''apple/mobilevit-xx-small'''					)

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

             # forward pass
             _snake_case      :							List[str]     				=						model(**lowercase_     ,  training=lowercase_					)

             # verify the logits
             _snake_case      :							List[str]     				=						tf.TensorShape((1, 1000)					)
             self.assertEqual(outputs.logits.shape     ,  lowercase_					)

             _snake_case      :							Any     				=						tf.constant([-1.9364, -1.2327, -0.4653]					)

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



      @slow
      def    __a (					self					)      ->   int:



             '''simple docstring'''

             _snake_case      :							Dict     				=						TFMobileViTForSemanticSegmentation.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''					)

             _snake_case      :							Optional[Any]     				=						MobileViTImageProcessor.from_pretrained('''apple/deeplabv3-mobilevit-xx-small'''					)

             _snake_case      :							List[str]     				=						prepare_img()
             _snake_case      :							List[str]     				=						image_processor(images=lowercase_     ,  return_tensors='''tf'''					)

             # forward pass
             _snake_case      :							str     				=						model(inputs.pixel_values     ,  training=lowercase_					)
             _snake_case      :							Tuple     				=						outputs.logits

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

             _snake_case      :							Optional[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]     ,  lowercase_     ,  rtol=1E-4     ,  atol=1E-4					)













from __future__ import annotations

class 				A    :



      def __init__(					self     ,  lowercase_					)      ->   None:



             '''simple docstring'''

             _snake_case      :							Optional[Any]     				=						vertices
             _snake_case      :							int     				=						[[0] * vertices for _ in range(lowercase_					)]



      def    __a (					self     ,  lowercase_					)      ->   None:



             '''simple docstring'''

             print('''Vertex \t Distance from Source'''					)
             for vertex in range(self.vertices					):
                    print(lowercase_     ,  '''\t\t'''     ,  distances_from_source[vertex]					)



      def    __a (					self     ,  lowercase_     ,  lowercase_					)      ->   int:



             '''simple docstring'''

             _snake_case      :							List[Any]     				=						1E7
             _snake_case      :							Tuple     				=						0

             # Search not nearest vertex not in the shortest path tree
             for vertex in range(self.vertices					):
                    if distances_from_source[vertex] < minimum and visited[vertex] is False:
                           _snake_case      :							Dict     				=						distances_from_source[vertex]
                           _snake_case      :							int     				=						vertex
             return min_index



      def    __a (					self     ,  lowercase_					)      ->   None:



             '''simple docstring'''

             _snake_case      :							List[Any]     				=						[int(1E7					)] * self.vertices  # distances from the source
             _snake_case      :							List[Any]     				=						0
             _snake_case      :							List[str]     				=						[False] * self.vertices

             for _ in range(self.vertices					):
                    _snake_case      :							List[Any]     				=						self.minimum_distance(lowercase_     ,  lowercase_					)
                    _snake_case      :							List[str]     				=						True

                    # Update dist value of the adjacent vertices
                    # of the picked vertex only if the current
                    # distance is greater than new distance and
                    # the vertex in not in the shortest path tree
                    for v in range(self.vertices					):
                           if (
                               self.graph[u][v] > 0
                               and visited[v] is False
                               and distances[v] > distances[u] + self.graph[u][v]
                           ):
                                  _snake_case      :							Any     				=						distances[u] + self.graph[u][v]

             self.print_solution(lowercase_					)


if __name__ == "__main__":
   lowerCAmelCase_   =   Graph(9)
   lowerCAmelCase_   =   [
       [0, 4, 0, 0, 0, 0, 0, 8, 0],
       [4, 0, 8, 0, 0, 0, 0, 1_1, 0],
       [0, 8, 0, 7, 0, 4, 0, 0, 2],
       [0, 0, 7, 0, 9, 1_4, 0, 0, 0],
       [0, 0, 0, 9, 0, 1_0, 0, 0, 0],
       [0, 0, 4, 1_4, 1_0, 0, 2, 0, 0],
       [0, 0, 0, 0, 0, 2, 0, 1, 6],
       [8, 1_1, 0, 0, 0, 0, 1, 0, 7],
       [0, 0, 2, 0, 0, 0, 6, 7, 0],
   ]
   graph.dijkstra(0)






