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

from collections import deque
from queue import Queue
from timeit import timeit

_a   :      List[Any]       =				{
    """A""": ["""B""", """C"""],
    """B""": ["""A""", """D""", """E"""],
    """C""": ["""A""", """F"""],
    """D""": ["""B"""],
    """E""": ["""B""", """F"""],
    """F""": ["""C""", """E"""],
}
def 					a__ ( a :					dict							,  a :					str		):

  """simple docstring"""







  _snake_case  :    List[str]            = {start}
  _snake_case  :    Tuple            = [start]
  _snake_case  :    Queue            = Queue()
  queue.put(a		)
  while not queue.empty():
    _snake_case  :    str            = queue.get()
    for w in graph[v]:
      if w not in explored:
        explored.add(a		)
        result.append(a		)
        queue.put(a		)
  return result
def 					a__ ( a :					dict							,  a :					str		):

  """simple docstring"""







  _snake_case  :    List[str]            = {start}
  _snake_case  :    Union[str, Any]            = [start]
  _snake_case  :    List[Any]            = deque([start]		)
  while queue:
    _snake_case  :    Dict            = queue.popleft()
    for child in graph[v]:
      if child not in visited:
        visited.add(a		)
        result.append(a		)
        queue.append(a		)
  return result
def 					a__ ( a :					str		):

  """simple docstring"""







  _snake_case  :    int            = f'from __main__ import G, {name}'
  _snake_case  :    str            = 10_000
  _snake_case  :    Any            = timeit(f'{name}(G, \'A\')'							,  setup=a							,  number=a		)
  print(f'{name:<35} finished {number} runs in {res:.5f} seconds'		)


if __name__ == "__main__":
    import doctest

    doctest.testmod()

    benchmark_function("""breadth_first_search""")
    benchmark_function("""breadth_first_search_with_deque""")
    # breadth_first_search                finished 10000 runs in 0.20999 seconds
    # breadth_first_search_with_deque     finished 10000 runs in 0.01421 seconds



"""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   _UpperCAmelCase					(       _snake_case):
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    List[str]            = 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   _UpperCAmelCase					:
    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    ,     ):
      _snake_case  :    List[Any]            = parent
      _snake_case  :    Union[str, Any]            = batch_size
      _snake_case  :    List[Any]            = image_size
      _snake_case  :    List[Any]            = patch_size
      _snake_case  :    Optional[Any]            = num_channels
      _snake_case  :    List[Any]            = last_hidden_size
      _snake_case  :    Tuple            = num_attention_heads
      _snake_case  :    Any            = hidden_act
      _snake_case  :    List[Any]            = conv_kernel_size
      _snake_case  :    int            = output_stride
      _snake_case  :    Dict            = hidden_dropout_prob
      _snake_case  :    Optional[int]            = attention_probs_dropout_prob
      _snake_case  :    List[Any]            = classifier_dropout_prob
      _snake_case  :    List[str]            = use_labels
      _snake_case  :    Dict            = is_training
      _snake_case  :    List[str]            = num_labels
      _snake_case  :    Optional[Any]            = initializer_range
      _snake_case  :    Dict            = scope
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Optional[int]            = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

      _snake_case  :    List[str]            = None
      _snake_case  :    int            = None
      if self.use_labels:
        _snake_case  :    Any            = ids_tensor([self.batch_size]    ,     self.num_labels  )
        _snake_case  :    Dict            = 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        lowerCamelCase__						(     self  ):
      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        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_  ):
      _snake_case  :    str            = TFMobileViTModel(config=snake_case_  )
      _snake_case  :    Optional[int]            = model(snake_case_    ,     training=snake_case_  )
      _snake_case  :    List[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        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_  ):
      _snake_case  :    int            = self.num_labels
      _snake_case  :    Optional[Any]            = TFMobileViTForImageClassification(snake_case_  )
      _snake_case  :    str            = model(snake_case_    ,     labels=snake_case_    ,     training=snake_case_  )
      self.parent.assertEqual(result.logits.shape    ,     (self.batch_size, self.num_labels)  )
    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_    ,     snake_case_    ,     snake_case_  ):
      _snake_case  :    List[str]            = self.num_labels
      _snake_case  :    Any            = TFMobileViTForSemanticSegmentation(snake_case_  )
      _snake_case  :    Optional[Any]            = self.image_size // self.output_stride

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

      _snake_case  :    List[Any]            = 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        lowerCamelCase__						(     self  ):
      _snake_case  :    Union[str, Any]            = self.prepare_config_and_inputs()
      _snake_case      ,       _snake_case      ,       _snake_case      ,       _snake_case  :    str            = config_and_inputs
      _snake_case  :    Optional[int]            = {"pixel_values": pixel_values}
      return config, inputs_dict






@require_tf
class   _UpperCAmelCase					(       _snake_case		,       _snake_case		,       unittest.TestCase):
    __lowercase				:			Tuple	=       (
        (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
        if is_tf_available()
        else ()
    )
    __lowercase				:			int	=       (
        {"""feature-extraction""": TFMobileViTModel, """image-classification""": TFMobileViTForImageClassification}
        if is_tf_available()
        else {}
    )

    __lowercase				:			Optional[int]	=       False
    __lowercase				:			Optional[int]	=       False
    __lowercase				:			List[Any]	=       False
    __lowercase				:			int	=       False
    __lowercase				:			Union[str, Any]	=       False
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Tuple            = TFMobileViTModelTester(self  )
      _snake_case  :    Dict            = TFMobileViTConfigTester(self    ,     config_class=snake_case_    ,     has_text_modality=snake_case_  )
    def        lowerCamelCase__						(     self  ):
      self.config_tester.run_common_tests()
    @unittest.skip(reason="MobileViT does not use inputs_embeds"  )
    def        lowerCamelCase__						(     self  ):
      pass
    @unittest.skip(reason="MobileViT does not support input and output embeddings"  )
    def        lowerCamelCase__						(     self  ):
      pass
    @unittest.skip(reason="MobileViT does not output attentions"  )
    def        lowerCamelCase__						(     self  ):
      pass
    def        lowerCamelCase__						(     self  ):
      _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]            = model_class(snake_case_  )
        _snake_case  :    Any            = inspect.signature(model.call  )
        # signature.parameters is an OrderedDict => so arg_names order is deterministic
        _snake_case  :    int            = [*signature.parameters.keys()]

        _snake_case  :    List[str]            = ["pixel_values"]
        self.assertListEqual(arg_names[:1]    ,     snake_case_  )
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    List[Any]            = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*snake_case_  )
    def        lowerCamelCase__						(     self  ):
      def check_hidden_states_output(snake_case_    ,     snake_case_    ,     snake_case_  ):
        _snake_case  :    Optional[int]            = model_class(snake_case_  )

        _snake_case  :    Dict            = model(**self._prepare_for_class(snake_case_    ,     snake_case_  )  )

        _snake_case  :    Optional[Any]            = outputs.hidden_states

        _snake_case  :    Any            = 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.
        _snake_case  :    Dict            = 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  )

      _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  :    Union[str, Any]            = 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"]
        _snake_case  :    Optional[Any]            = True

        check_hidden_states_output(snake_case_    ,     snake_case_    ,     snake_case_  )
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    List[str]            = self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*snake_case_  )
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Tuple            = 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        lowerCamelCase__						(     self  ):
      super().test_dataset_conversion()
    def        lowerCamelCase__						(     self    ,     snake_case_    ,     snake_case_    ,     snake_case_=2E-1    ,     snake_case_=2E-1  ):
      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        lowerCamelCase__						(     self  ):
      _snake_case      ,       _snake_case  :    Optional[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  :    List[str]            = model_class(snake_case_  )
          if getattr(snake_case_    ,     "hf_compute_loss"    ,     snake_case_  ):
            super().test_keras_fit()
    def        lowerCamelCase__						(     self  ):
      _snake_case      ,       _snake_case  :    Optional[int]            = 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  :    Optional[Any]            = 5

        _snake_case  :    Optional[Any]            = 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
          _snake_case  :    Optional[Any]            = self._prepare_for_class(inputs_dict.copy()    ,     snake_case_    ,     return_labels=snake_case_  )
          _snake_case  :    int            = prepared_for_class[
              sorted(prepared_for_class.keys() - inputs_dict.keys()    ,     reverse=snake_case_  )[0]
          ]
          _snake_case  :    Optional[Any]            = added_label.shape.as_list()[:1]

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

          _snake_case  :    Union[str, Any]            = 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
          _snake_case  :    Optional[Any]            = self._prepare_for_class(inputs_dict.copy()    ,     snake_case_    ,     return_labels=snake_case_  )
          _snake_case  :    Any            = {"input_ids", "pixel_values", "input_features"}
          _snake_case  :    Optional[int]            = possible_input_names.intersection(set(snake_case_  )  ).pop()
          _snake_case  :    List[str]            = prepared_for_class.pop(snake_case_  )
          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  :    Optional[int]            = tf.convert_to_tensor(snake_case_  )
              _snake_case  :    Union[str, Any]            = 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
          _snake_case  :    Tuple            = self._prepare_for_class(inputs_dict.copy()    ,     snake_case_    ,     return_labels=snake_case_  )
          _snake_case  :    Tuple            = 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
          _snake_case  :    Dict            = self._prepare_for_class(inputs_dict.copy()    ,     snake_case_    ,     return_labels=snake_case_  )

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

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

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

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

          _snake_case  :    str            = tuple(snake_case_  )

          # Send to model
          _snake_case  :    Union[str, Any]            = model(tuple_input[:-1]  )[0]

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


    @slow
    def        lowerCamelCase__						(     self  ):
      for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        _snake_case  :    Optional[int]            = TFMobileViTModel.from_pretrained(snake_case_  )
        self.assertIsNotNone(snake_case_  )


def 					a__ ( ):

  """simple docstring"""







  _snake_case  :    Union[str, Any]            = Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"		)
  return image






@require_tf
class   _UpperCAmelCase					(       unittest.TestCase):
    @slow
    def        lowerCamelCase__						(     self  ):
      _snake_case  :    Optional[Any]            = TFMobileViTForImageClassification.from_pretrained("apple/mobilevit-xx-small"  )

      _snake_case  :    List[Any]            = MobileViTImageProcessor.from_pretrained("apple/mobilevit-xx-small"  )
      _snake_case  :    List[Any]            = prepare_img()
      _snake_case  :    List[str]            = image_processor(images=snake_case_    ,     return_tensors="tf"  )

      # forward pass
      _snake_case  :    Union[str, Any]            = model(**snake_case_    ,     training=snake_case_  )

      # verify the logits
      _snake_case  :    Optional[Any]            = tf.TensorShape((1, 10_00)  )
      self.assertEqual(outputs.logits.shape    ,     snake_case_  )

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

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


    @slow
    def        lowerCamelCase__						(     self  ):
      # `from_pt` will be removed
      _snake_case  :    List[str]            = TFMobileViTForSemanticSegmentation.from_pretrained("apple/deeplabv3-mobilevit-xx-small"  )

      _snake_case  :    int            = MobileViTImageProcessor.from_pretrained("apple/deeplabv3-mobilevit-xx-small"  )

      _snake_case  :    List[Any]            = prepare_img()
      _snake_case  :    str            = image_processor(images=snake_case_    ,     return_tensors="tf"  )

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

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

      _snake_case  :    str            = 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]    ,     snake_case_    ,     rtol=1E-4    ,     atol=1E-4  )

