"""simple docstring"""


import inspect
import unittest

from transformers import MobileViTConfig
from transformers.testing_utils import require_torch, require_vision, slow, torch_device
from transformers.utils import cached_property, is_torch_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
    import torch

    from transformers import MobileViTForImageClassification, MobileViTForSemanticSegmentation, MobileViTModel
    from transformers.models.mobilevit.modeling_mobilevit import MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
    from PIL import Image

    from transformers import MobileViTImageProcessor


class        a				(		lowerCAmelCase_   ):


    def      lowerCAmelCase_  (					self	:  Optional[Any]					):
      _UpperCAmelCase						 =      self.config_class(**self.inputs_dict					)
      self.parent.assertTrue(hasattr(__lowerCAmelCase   ,				"""hidden_sizes"""					)					)
      self.parent.assertTrue(hasattr(__lowerCAmelCase   ,				"""neck_hidden_sizes"""					)					)
      self.parent.assertTrue(hasattr(__lowerCAmelCase   ,				"""num_attention_heads"""					)					)



class        a				:


    def __init__(					self	:  Any   ,				__lowerCAmelCase	:  Optional[int]   ,				__lowerCAmelCase	:  Optional[int]=13   ,				__lowerCAmelCase	:  Any=32   ,				__lowerCAmelCase	:  int=2   ,				__lowerCAmelCase	:  Optional[Any]=3   ,				__lowerCAmelCase	:  int=640   ,				__lowerCAmelCase	:  List[str]=4   ,				__lowerCAmelCase	:  str="silu"   ,				__lowerCAmelCase	:  List[str]=3   ,				__lowerCAmelCase	:  Any=32   ,				__lowerCAmelCase	:  Tuple=0.1   ,				__lowerCAmelCase	:  str=0.1   ,				__lowerCAmelCase	:  Optional[int]=0.1   ,				__lowerCAmelCase	:  Tuple=0.02   ,				__lowerCAmelCase	:  List[Any]=True   ,				__lowerCAmelCase	:  int=True   ,				__lowerCAmelCase	:  Tuple=10   ,				__lowerCAmelCase	:  int=None   ,				):
      _UpperCAmelCase						 =      parent
      _UpperCAmelCase						 =      batch_size
      _UpperCAmelCase						 =      image_size
      _UpperCAmelCase						 =      patch_size
      _UpperCAmelCase						 =      num_channels
      _UpperCAmelCase						 =      last_hidden_size
      _UpperCAmelCase						 =      num_attention_heads
      _UpperCAmelCase						 =      hidden_act
      _UpperCAmelCase						 =      conv_kernel_size
      _UpperCAmelCase						 =      output_stride
      _UpperCAmelCase						 =      hidden_dropout_prob
      _UpperCAmelCase						 =      attention_probs_dropout_prob
      _UpperCAmelCase						 =      classifier_dropout_prob
      _UpperCAmelCase						 =      use_labels
      _UpperCAmelCase						 =      is_training
      _UpperCAmelCase						 =      num_labels
      _UpperCAmelCase						 =      initializer_range
      _UpperCAmelCase						 =      scope


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

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

      _UpperCAmelCase						 =      self.get_config()

      return config, pixel_values, labels, pixel_labels


    def      lowerCAmelCase_  (					self	:  List[Any]					):
      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	:  List[Any]   ,				__lowerCAmelCase	:  Union[str, Any]   ,				__lowerCAmelCase	:  Optional[Any]   ,				__lowerCAmelCase	:  List[Any]   ,				__lowerCAmelCase	:  List[str]					):
      _UpperCAmelCase						 =      MobileViTModel(config=__lowerCAmelCase					)
      model.to(__lowerCAmelCase					)
      model.eval()
      _UpperCAmelCase						 =      model(__lowerCAmelCase					)
      self.parent.assertEqual(
          result.last_hidden_state.shape   ,				(
              self.batch_size,
              self.last_hidden_size,
              self.image_size // self.output_stride,
              self.image_size // self.output_stride,
          )   ,				)


    def      lowerCAmelCase_  (					self	:  List[Any]   ,				__lowerCAmelCase	:  Dict   ,				__lowerCAmelCase	:  Dict   ,				__lowerCAmelCase	:  Dict   ,				__lowerCAmelCase	:  Tuple					):
      _UpperCAmelCase						 =      self.num_labels
      _UpperCAmelCase						 =      MobileViTForImageClassification(__lowerCAmelCase					)
      model.to(__lowerCAmelCase					)
      model.eval()
      _UpperCAmelCase						 =      model(__lowerCAmelCase   ,				labels=__lowerCAmelCase					)
      self.parent.assertEqual(result.logits.shape   ,				(self.batch_size, self.num_labels)					)


    def      lowerCAmelCase_  (					self	:  Dict   ,				__lowerCAmelCase	:  str   ,				__lowerCAmelCase	:  Dict   ,				__lowerCAmelCase	:  Optional[Any]   ,				__lowerCAmelCase	:  Optional[Any]					):
      _UpperCAmelCase						 =      self.num_labels
      _UpperCAmelCase						 =      MobileViTForSemanticSegmentation(__lowerCAmelCase					)
      model.to(__lowerCAmelCase					)
      model.eval()
      _UpperCAmelCase						 =      model(__lowerCAmelCase					)
      self.parent.assertEqual(
          result.logits.shape   ,				(
              self.batch_size,
              self.num_labels,
              self.image_size // self.output_stride,
              self.image_size // self.output_stride,
          )   ,				)
      _UpperCAmelCase						 =      model(__lowerCAmelCase   ,				labels=__lowerCAmelCase					)
      self.parent.assertEqual(
          result.logits.shape   ,				(
              self.batch_size,
              self.num_labels,
              self.image_size // self.output_stride,
              self.image_size // self.output_stride,
          )   ,				)


    def      lowerCAmelCase_  (					self	:  List[str]					):
      _UpperCAmelCase						 =      self.prepare_config_and_inputs()
      _UpperCAmelCase ,				_UpperCAmelCase ,				_UpperCAmelCase ,				_UpperCAmelCase						 =      config_and_inputs
      _UpperCAmelCase						 =      {"""pixel_values""": pixel_values}
      return config, inputs_dict



@require_torch
class        a				(		lowerCAmelCase_	,							lowerCAmelCase_	,							unittest.TestCase   ):
    _snake_case     :  List[str]     							=							(
        (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
        if is_torch_available()
        else ()
    )
    _snake_case     :  List[Any]     							=							(
        {
            'feature-extraction': MobileViTModel,
            'image-classification': MobileViTForImageClassification,
            'image-segmentation': MobileViTForSemanticSegmentation,
        }
        if is_torch_available()
        else {}
    )

    _snake_case     :  List[Any]     							=							False
    _snake_case     :  int     							=							False
    _snake_case     :  List[str]     							=							False
    _snake_case     :  Optional[int]     							=							False


    def      lowerCAmelCase_  (					self	:  Dict					):
      _UpperCAmelCase						 =      MobileViTModelTester(self					)
      _UpperCAmelCase						 =      MobileViTConfigTester(self   ,				config_class=__lowerCAmelCase   ,				has_text_modality=__lowerCAmelCase					)


    def      lowerCAmelCase_  (					self	:  int					):
      self.config_tester.run_common_tests()


    @unittest.skip(reason="""MobileViT does not use inputs_embeds"""					)
    def      lowerCAmelCase_  (					self	:  Union[str, Any]					):
      pass


    @unittest.skip(reason="""MobileViT does not support input and output embeddings"""					)
    def      lowerCAmelCase_  (					self	:  str					):
      pass


    @unittest.skip(reason="""MobileViT does not output attentions"""					)
    def      lowerCAmelCase_  (					self	:  Union[str, Any]					):
      pass


    def      lowerCAmelCase_  (					self	:  Any					):
      _UpperCAmelCase ,				_UpperCAmelCase						 =      self.model_tester.prepare_config_and_inputs_for_common()

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

        _UpperCAmelCase						 =      ["""pixel_values"""]
        self.assertListEqual(arg_names[:1]   ,				__lowerCAmelCase					)


    @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""					)
    def      lowerCAmelCase_  (					self	:  int					):
      pass


    def      lowerCAmelCase_  (					self	:  Dict					):
      _UpperCAmelCase						 =      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*__lowerCAmelCase					)


    def      lowerCAmelCase_  (					self	:  Union[str, Any]					):
      def check_hidden_states_output(__lowerCAmelCase	:  int   ,				__lowerCAmelCase	:  Any   ,				__lowerCAmelCase	:  int					):
        _UpperCAmelCase						 =      model_class(__lowerCAmelCase					)
        model.to(__lowerCAmelCase					)
        model.eval()

        with torch.no_grad():
          _UpperCAmelCase						 =      model(**self._prepare_for_class(__lowerCAmelCase   ,				__lowerCAmelCase					)					)

        _UpperCAmelCase						 =      outputs.hidden_states

        _UpperCAmelCase						 =      5
        self.assertEqual(len(__lowerCAmelCase					)   ,				__lowerCAmelCase					)

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

      _UpperCAmelCase ,				_UpperCAmelCase						 =      self.model_tester.prepare_config_and_inputs_for_common()

      for model_class in self.all_model_classes:
        _UpperCAmelCase						 =      True
        check_hidden_states_output(__lowerCAmelCase   ,				__lowerCAmelCase   ,				__lowerCAmelCase					)

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

        check_hidden_states_output(__lowerCAmelCase   ,				__lowerCAmelCase   ,				__lowerCAmelCase					)


    def      lowerCAmelCase_  (					self	:  Optional[int]					):
      _UpperCAmelCase						 =      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase					)


    def      lowerCAmelCase_  (					self	:  Dict					):
      _UpperCAmelCase						 =      self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_semantic_segmentation(*__lowerCAmelCase					)


    @slow
    def      lowerCAmelCase_  (					self	:  Optional[Any]					):
      for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        _UpperCAmelCase						 =      MobileViTModel.from_pretrained(__lowerCAmelCase					)
        self.assertIsNotNone(__lowerCAmelCase					)






def     __UpperCAmelCase					(			):







  """simple docstring"""
  _UpperCAmelCase						 =      Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""		)
  return image


@require_torch
@require_vision
class        a				(		unittest.TestCase   ):


    @cached_property
    def      lowerCAmelCase_  (					self	:  Optional[Any]					):
      return MobileViTImageProcessor.from_pretrained("""apple/mobilevit-xx-small"""					) if is_vision_available() else None


    @slow
    def      lowerCAmelCase_  (					self	:  str					):
      _UpperCAmelCase						 =      MobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small"""					).to(__lowerCAmelCase					)

      _UpperCAmelCase						 =      self.default_image_processor
      _UpperCAmelCase						 =      prepare_img()
      _UpperCAmelCase						 =      image_processor(images=__lowerCAmelCase   ,				return_tensors="""pt"""					).to(__lowerCAmelCase					)

      # forward pass
      with torch.no_grad():
        _UpperCAmelCase						 =      model(**__lowerCAmelCase					)

      # verify the logits
      _UpperCAmelCase						 =      torch.Size((1, 1000)					)
      self.assertEqual(outputs.logits.shape   ,				__lowerCAmelCase					)

      _UpperCAmelCase						 =      torch.tensor([-1.9_364, -1.2_327, -0.4_653]					).to(__lowerCAmelCase					)

      self.assertTrue(torch.allclose(outputs.logits[0, :3]   ,				__lowerCAmelCase   ,				atol=1e-4					)					)


    @slow
    def      lowerCAmelCase_  (					self	:  Dict					):
      _UpperCAmelCase						 =      MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""					)
      _UpperCAmelCase						 =      model.to(__lowerCAmelCase					)

      _UpperCAmelCase						 =      MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""					)

      _UpperCAmelCase						 =      prepare_img()
      _UpperCAmelCase						 =      image_processor(images=__lowerCAmelCase   ,				return_tensors="""pt"""					).to(__lowerCAmelCase					)

      # forward pass
      with torch.no_grad():
        _UpperCAmelCase						 =      model(**__lowerCAmelCase					)
      _UpperCAmelCase						 =      outputs.logits

      # verify the logits
      _UpperCAmelCase						 =      torch.Size((1, 21, 32, 32)					)
      self.assertEqual(logits.shape   ,				__lowerCAmelCase					)

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

      self.assertTrue(torch.allclose(logits[0, :3, :3, :3]   ,				__lowerCAmelCase   ,				atol=1e-4					)					)


    @slow
    def      lowerCAmelCase_  (					self	:  Any					):
      _UpperCAmelCase						 =      MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""					)
      _UpperCAmelCase						 =      model.to(__lowerCAmelCase					)

      _UpperCAmelCase						 =      MobileViTImageProcessor.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""					)

      _UpperCAmelCase						 =      prepare_img()
      _UpperCAmelCase						 =      image_processor(images=__lowerCAmelCase   ,				return_tensors="""pt"""					).to(__lowerCAmelCase					)

      # forward pass
      with torch.no_grad():
        _UpperCAmelCase						 =      model(**__lowerCAmelCase					)

      _UpperCAmelCase						 =      outputs.logits.detach().cpu()

      _UpperCAmelCase						 =      image_processor.post_process_semantic_segmentation(outputs=__lowerCAmelCase   ,				target_sizes=[(50, 60)]					)
      _UpperCAmelCase						 =      torch.Size((50, 60)					)
      self.assertEqual(segmentation[0].shape   ,				__lowerCAmelCase					)

      _UpperCAmelCase						 =      image_processor.post_process_semantic_segmentation(outputs=__lowerCAmelCase					)
      _UpperCAmelCase						 =      torch.Size((32, 32)					)
      self.assertEqual(segmentation[0].shape   ,				__lowerCAmelCase					)

"""simple docstring"""


import random






def     __UpperCAmelCase					(			lowercase   ,lowercase   ,lowercase = False		):







  """simple docstring"""
  _UpperCAmelCase						 =      {i: [] for i in range(lowercase		)}

  # if probability is greater or equal than 1, then generate a complete graph
  if probability >= 1:
    return complete_graph(lowercase		)
  # if probability is lower or equal than 0, then return a graph without edges
  if probability <= 0:
    return graph

  # for each couple of nodes, add an edge from u to v
  # if the number randomly generated is greater than probability probability
  for i in range(lowercase		):
    for j in range(i + 1   ,lowercase		):
      if random.random() < probability:
        graph[i].append(lowercase		)
        if not directed:
          # if the graph is undirected, add an edge in from j to i, either
          graph[j].append(lowercase		)
  return graph






def     __UpperCAmelCase					(			lowercase		):







  """simple docstring"""
  return {
      i: [j for j in range(lowercase		) if i != j] for i in range(lowercase		)
  }


if __name__ == "__main__":
    import doctest

    doctest.testmod()
