





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




      def 							lowercase__       (     self     :					Optional[Any]    )							-> List[str]:
            _lowerCAmelCase					=				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     :					Optional[int]     ,     __snake_case     :					str     ,     __snake_case     :					int=13     ,     __snake_case     :					Dict=32     ,     __snake_case     :					Optional[int]=2     ,     __snake_case     :					Optional[int]=3     ,     __snake_case     :					List[Any]=6_40     ,     __snake_case     :					List[str]=4     ,     __snake_case     :					Dict="silu"     ,     __snake_case     :					Union[str, Any]=3     ,     __snake_case     :					List[Any]=32     ,     __snake_case     :					List[Any]=0.1     ,     __snake_case     :					Tuple=0.1     ,     __snake_case     :					Tuple=0.1     ,     __snake_case     :					str=0.02     ,     __snake_case     :					Any=True     ,     __snake_case     :					int=True     ,     __snake_case     :					Optional[int]=10     ,     __snake_case     :					str=None     ,     )							-> Optional[int]:
            _lowerCAmelCase					=				parent
            _lowerCAmelCase					=				batch_size
            _lowerCAmelCase					=				image_size
            _lowerCAmelCase					=				patch_size
            _lowerCAmelCase					=				num_channels
            _lowerCAmelCase					=				last_hidden_size
            _lowerCAmelCase					=				num_attention_heads
            _lowerCAmelCase					=				hidden_act
            _lowerCAmelCase					=				conv_kernel_size
            _lowerCAmelCase					=				output_stride
            _lowerCAmelCase					=				hidden_dropout_prob
            _lowerCAmelCase					=				attention_probs_dropout_prob
            _lowerCAmelCase					=				classifier_dropout_prob
            _lowerCAmelCase					=				use_labels
            _lowerCAmelCase					=				is_training
            _lowerCAmelCase					=				num_labels
            _lowerCAmelCase					=				initializer_range
            _lowerCAmelCase					=				scope




      def 							lowercase__       (     self     :					List[Any]    )							-> Optional[Any]:
            _lowerCAmelCase					=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

            _lowerCAmelCase					=				self.get_config()

            return config, pixel_values, labels, pixel_labels




      def 							lowercase__       (     self     :					List[Any]    )							-> List[str]:
            return MobileViTConfig(
                image_size=self.image_size     ,     patch_size=self.patch_size     ,     num_channels=self.num_channels     ,     num_attention_heads=self.num_attention_heads     ,     hidden_act=self.hidden_act     ,     conv_kernel_size=self.conv_kernel_size     ,     output_stride=self.output_stride     ,     hidden_dropout_prob=self.hidden_dropout_prob     ,     attention_probs_dropout_prob=self.attention_probs_dropout_prob     ,     classifier_dropout_prob=self.classifier_dropout_prob     ,     initializer_range=self.initializer_range     ,     )




      def 							lowercase__       (     self     :					List[str]     ,     __snake_case     :					int     ,     __snake_case     :					Tuple     ,     __snake_case     :					List[Any]     ,     __snake_case     :					Dict    )							-> Union[str, Any]:
            _lowerCAmelCase					=				MobileViTModel(config=__snake_case    )
            model.to(__snake_case    )
            model.eval()
            _lowerCAmelCase					=				model(__snake_case    )
            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 							lowercase__       (     self     :					List[str]     ,     __snake_case     :					Tuple     ,     __snake_case     :					List[Any]     ,     __snake_case     :					Tuple     ,     __snake_case     :					Optional[Any]    )							-> Optional[Any]:
            _lowerCAmelCase					=				self.num_labels
            _lowerCAmelCase					=				MobileViTForImageClassification(__snake_case    )
            model.to(__snake_case    )
            model.eval()
            _lowerCAmelCase					=				model(__snake_case     ,     labels=__snake_case    )
            self.parent.assertEqual(result.logits.shape     ,     (self.batch_size, self.num_labels)    )




      def 							lowercase__       (     self     :					int     ,     __snake_case     :					Tuple     ,     __snake_case     :					str     ,     __snake_case     :					Optional[int]     ,     __snake_case     :					Optional[int]    )							-> Optional[int]:
            _lowerCAmelCase					=				self.num_labels
            _lowerCAmelCase					=				MobileViTForSemanticSegmentation(__snake_case    )
            model.to(__snake_case    )
            model.eval()
            _lowerCAmelCase					=				model(__snake_case    )
            self.parent.assertEqual(
                result.logits.shape     ,     (
                    self.batch_size,
                    self.num_labels,
                    self.image_size // self.output_stride,
                    self.image_size // self.output_stride,
                )     ,     )
            _lowerCAmelCase					=				model(__snake_case     ,     labels=__snake_case    )
            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 							lowercase__       (     self     :					List[str]    )							-> Any:
            _lowerCAmelCase					=				self.prepare_config_and_inputs()
            _lowerCAmelCase	,				_lowerCAmelCase	,				_lowerCAmelCase	,				_lowerCAmelCase					=				config_and_inputs
            _lowerCAmelCase					=				{"""pixel_values""": pixel_values}
            return config, inputs_dict




@require_torch
class 					UpperCAmelCase	(     snake_case_				,						snake_case_				,						unittest.TestCase  ):
      _lowercase:     str			=  (
          (MobileViTModel, MobileViTForImageClassification, MobileViTForSemanticSegmentation)
          if is_torch_available()
          else ()
      )
      _lowercase:     Any			=  (
          {
              '''feature-extraction''': MobileViTModel,
              '''image-classification''': MobileViTForImageClassification,
              '''image-segmentation''': MobileViTForSemanticSegmentation,
          }
          if is_torch_available()
          else {}
      )

      _lowercase:     Union[str, Any]			=  False
      _lowercase:     Optional[int]			=  False
      _lowercase:     Optional[Any]			=  False
      _lowercase:     str			=  False




      def 							lowercase__       (     self     :					Optional[Any]    )							-> str:
            _lowerCAmelCase					=				MobileViTModelTester(self    )
            _lowerCAmelCase					=				MobileViTConfigTester(self     ,     config_class=__snake_case     ,     has_text_modality=__snake_case    )




      def 							lowercase__       (     self     :					Tuple    )							-> str:
            self.config_tester.run_common_tests()




      @unittest.skip(reason="""MobileViT does not use inputs_embeds"""    )
      def 							lowercase__       (     self     :					List[Any]    )							-> List[Any]:
            pass




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




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




      def 							lowercase__       (     self     :					str    )							-> Union[str, Any]:
            _lowerCAmelCase	,				_lowerCAmelCase					=				self.model_tester.prepare_config_and_inputs_for_common()

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

                  _lowerCAmelCase					=				["""pixel_values"""]
                  self.assertListEqual(arg_names[:1]     ,     __snake_case    )




      @unittest.skip("""Will be fixed soon by reducing the size of the model used for common tests."""    )
      def 							lowercase__       (     self     :					List[str]    )							-> Optional[int]:
            pass




      def 							lowercase__       (     self     :					str    )							-> Dict:
            _lowerCAmelCase					=				self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*__snake_case    )




      def 							lowercase__       (     self     :					List[Any]    )							-> List[str]:
            def check_hidden_states_output(__snake_case     :					Optional[Any]     ,     __snake_case     :					int     ,     __snake_case     :					str    ):
                  _lowerCAmelCase					=				model_class(__snake_case    )
                  model.to(__snake_case    )
                  model.eval()

                  with torch.no_grad():
                        _lowerCAmelCase					=				model(**self._prepare_for_class(__snake_case     ,     __snake_case    )    )

                  _lowerCAmelCase					=				outputs.hidden_states

                  _lowerCAmelCase					=				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.
                  _lowerCAmelCase					=				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    )

            _lowerCAmelCase	,				_lowerCAmelCase					=				self.model_tester.prepare_config_and_inputs_for_common()

            for model_class in self.all_model_classes:
                  _lowerCAmelCase					=				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"]
                  _lowerCAmelCase					=				True

                  check_hidden_states_output(__snake_case     ,     __snake_case     ,     __snake_case    )




      def 							lowercase__       (     self     :					str    )							-> Union[str, Any]:
            _lowerCAmelCase					=				self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*__snake_case    )




      def 							lowercase__       (     self     :					List[str]    )							-> List[Any]:
            _lowerCAmelCase					=				self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_semantic_segmentation(*__snake_case    )




      @slow
      def 							lowercase__       (     self     :					int    )							-> List[Any]:
            for model_name in MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                  _lowerCAmelCase					=				MobileViTModel.from_pretrained(__snake_case    )
                  self.assertIsNotNone(__snake_case    )




def   UpperCamelCase__ (						):





      """simple docstring"""


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





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




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




      @slow
      def 							lowercase__       (     self     :					Union[str, Any]    )							-> Union[str, Any]:
            _lowerCAmelCase					=				MobileViTForImageClassification.from_pretrained("""apple/mobilevit-xx-small"""    ).to(__snake_case    )

            _lowerCAmelCase					=				self.default_image_processor
            _lowerCAmelCase					=				prepare_img()
            _lowerCAmelCase					=				image_processor(images=__snake_case     ,     return_tensors="""pt"""    ).to(__snake_case    )

            # forward pass
            with torch.no_grad():
                  _lowerCAmelCase					=				model(**__snake_case    )

            # verify the logits
            _lowerCAmelCase					=				torch.Size((1, 10_00)    )
            self.assertEqual(outputs.logits.shape     ,     __snake_case    )

            _lowerCAmelCase					=				torch.tensor([-1.93_64, -1.23_27, -0.46_53]    ).to(__snake_case    )

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




      @slow
      def 							lowercase__       (     self     :					Optional[int]    )							-> str:
            _lowerCAmelCase					=				MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""    )
            _lowerCAmelCase					=				model.to(__snake_case    )

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

            _lowerCAmelCase					=				prepare_img()
            _lowerCAmelCase					=				image_processor(images=__snake_case     ,     return_tensors="""pt"""    ).to(__snake_case    )

            # forward pass
            with torch.no_grad():
                  _lowerCAmelCase					=				model(**__snake_case    )
            _lowerCAmelCase					=				outputs.logits

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

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

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




      @slow
      def 							lowercase__       (     self     :					Any    )							-> Optional[int]:
            _lowerCAmelCase					=				MobileViTForSemanticSegmentation.from_pretrained("""apple/deeplabv3-mobilevit-xx-small"""    )
            _lowerCAmelCase					=				model.to(__snake_case    )

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

            _lowerCAmelCase					=				prepare_img()
            _lowerCAmelCase					=				image_processor(images=__snake_case     ,     return_tensors="""pt"""    ).to(__snake_case    )

            # forward pass
            with torch.no_grad():
                  _lowerCAmelCase					=				model(**__snake_case    )

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

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

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













'''simple docstring'''






from typing import Callable, Optional

from .. import Features
from ..packaged_modules.generator.generator import Generator
from .abc import AbstractDatasetInputStream




class 					UpperCAmelCase	(     snake_case_  ):




      def __init__(     self     :					Union[str, Any]     ,     __snake_case     :					Callable     ,     __snake_case     :					Optional[Features] = None     ,     __snake_case     :					str = None     ,     __snake_case     :					bool = False     ,     __snake_case     :					bool = False     ,     __snake_case     :					Optional[dict] = None     ,     __snake_case     :					Optional[int] = None     ,     **__snake_case     :					Optional[Any]     ,     )							-> Union[str, Any]:
            super().__init__(
                features=__snake_case     ,     cache_dir=__snake_case     ,     keep_in_memory=__snake_case     ,     streaming=__snake_case     ,     num_proc=__snake_case     ,     **__snake_case     ,     )
            _lowerCAmelCase					=				Generator(
                cache_dir=__snake_case     ,     features=__snake_case     ,     generator=__snake_case     ,     gen_kwargs=__snake_case     ,     **__snake_case     ,     )




      def 							lowercase__       (     self     :					str    )							-> Dict:
            # Build iterable dataset
            if self.streaming:
                  _lowerCAmelCase					=				self.builder.as_streaming_dataset(split="""train"""    )
            # Build regular (map-style) dataset
            else:
                  _lowerCAmelCase					=				None
                  _lowerCAmelCase					=				None
                  _lowerCAmelCase					=				None
                  _lowerCAmelCase					=				None

                  self.builder.download_and_prepare(
                      download_config=__snake_case     ,     download_mode=__snake_case     ,     verification_mode=__snake_case     ,     base_path=__snake_case     ,     num_proc=self.num_proc     ,     )
                  _lowerCAmelCase					=				self.builder.as_dataset(
                      split="""train"""     ,     verification_mode=__snake_case     ,     in_memory=self.keep_in_memory    )
            return dataset






