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






   """simple docstring"""
   def 		_lowerCamelCase			(self					)     ->  Tuple:
        lowercase_       :							int  					=       self.config_class(**self.inputs_dict					)
        self.parent.assertTrue(hasattr(_a							,					'hidden_sizes'					)					)
        self.parent.assertTrue(hasattr(_a							,					'neck_hidden_sizes'					)					)
        self.parent.assertTrue(hasattr(_a							,					'num_attention_heads'					)					)



class    UpperCAmelCase__	:






   """simple docstring"""
   def __init__(self							,					_a							,					_a=13							,					_a=32							,					_a=2							,					_a=3							,					_a=640							,					_a=4							,					_a="silu"							,					_a=3							,					_a=32							,					_a=0.1							,					_a=0.1							,					_a=0.1							,					_a=0.02							,					_a=True							,					_a=True							,					_a=10							,					_a=None							,					)     ->  Optional[Any]:
        lowercase_       :							Dict  					=       parent
        lowercase_       :							Optional[int]  					=       batch_size
        lowercase_       :							List[str]  					=       image_size
        lowercase_       :							int  					=       patch_size
        lowercase_       :							Optional[Any]  					=       num_channels
        lowercase_       :							Dict  					=       last_hidden_size
        lowercase_       :							Any  					=       num_attention_heads
        lowercase_       :							Any  					=       hidden_act
        lowercase_       :							Union[str, Any]  					=       conv_kernel_size
        lowercase_       :							Optional[int]  					=       output_stride
        lowercase_       :							List[Any]  					=       hidden_dropout_prob
        lowercase_       :							Optional[Any]  					=       attention_probs_dropout_prob
        lowercase_       :							Any  					=       classifier_dropout_prob
        lowercase_       :							Dict  					=       use_labels
        lowercase_       :							str  					=       is_training
        lowercase_       :							List[Any]  					=       num_labels
        lowercase_       :							Union[str, Any]  					=       initializer_range
        lowercase_       :							Optional[Any]  					=       scope
   def 		_lowerCamelCase			(self					)     ->  Optional[int]:
        lowercase_       :							List[str]  					=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

        lowercase_       :							str  					=       None
        lowercase_       :							Dict  					=       None
        if self.use_labels:
             lowercase_       :							str  					=       ids_tensor([self.batch_size]							,					self.num_labels					)
             lowercase_       :							List[Any]  					=       ids_tensor([self.batch_size, self.image_size, self.image_size]							,					self.num_labels					)

        lowercase_       :							Any  					=       self.get_config()

        return config, pixel_values, labels, pixel_labels
   def 		_lowerCamelCase			(self					)     ->  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 		_lowerCamelCase			(self							,					_a							,					_a							,					_a							,					_a					)     ->  Optional[int]:
        lowercase_       :							Optional[Any]  					=       TFMobileViTModel(config=_a					)
        lowercase_       :							List[Any]  					=       model(_a							,					training=_a					)
        lowercase_       :							Dict  					=       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							,					_a							,					_a							,					_a							,					_a					)     ->  List[Any]:
        lowercase_       :							List[Any]  					=       self.num_labels
        lowercase_       :							int  					=       TFMobileViTForImageClassification(_a					)
        lowercase_       :							List[Any]  					=       model(_a							,					labels=_a							,					training=_a					)
        self.parent.assertEqual(result.logits.shape							,					(self.batch_size, self.num_labels)					)
   def 		_lowerCamelCase			(self							,					_a							,					_a							,					_a							,					_a					)     ->  List[Any]:
        lowercase_       :							str  					=       self.num_labels
        lowercase_       :							int  					=       TFMobileViTForSemanticSegmentation(_a					)
        lowercase_       :							Tuple  					=       self.image_size // self.output_stride

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

        lowercase_       :							List[Any]  					=       model(_a							,					labels=_a							,					training=_a					)
        self.parent.assertEqual(
            result.logits.shape							,					(self.batch_size, self.num_labels, expected_height, expected_width)					)





   def 		_lowerCamelCase			(self					)     ->  Any:
        lowercase_       :							str  					=       self.prepare_config_and_inputs()
        lowercase_					,lowercase_					,lowercase_					,lowercase_       :							int  					=       config_and_inputs
        lowercase_       :							Any  					=       {'pixel_values': pixel_values}
        return config, inputs_dict



@require_tf
class    UpperCAmelCase__	(							_snake_case       ,  _snake_case       ,  unittest.TestCase      ):






   """simple docstring"""
   A				:							Optional[int]			     =     (
       (TFMobileViTModel, TFMobileViTForImageClassification, TFMobileViTForSemanticSegmentation)
       if is_tf_available()
       else ()
   )
   A				:							Optional[Any]			     =     (
       {'''feature-extraction''': TFMobileViTModel, '''image-classification''': TFMobileViTForImageClassification}
       if is_tf_available()
       else {}
   )

   A				:							Optional[int]			     =     False
   A				:							str			     =     False
   A				:							List[Any]			     =     False
   A				:							str			     =     False
   A				:							int			     =     False
   def 		_lowerCamelCase			(self					)     ->  str:
        lowercase_       :							int  					=       TFMobileViTModelTester(self					)
        lowercase_       :							Any  					=       TFMobileViTConfigTester(self							,					config_class=_a							,					has_text_modality=_a					)
   def 		_lowerCamelCase			(self					)     ->  str:
        self.config_tester.run_common_tests()
   @unittest.skip(reason='MobileViT does not use inputs_embeds'					)
   def 		_lowerCamelCase			(self					)     ->  List[Any]:
        pass
   @unittest.skip(reason='MobileViT does not support input and output embeddings'					)
   def 		_lowerCamelCase			(self					)     ->  Dict:
        pass
   @unittest.skip(reason='MobileViT does not output attentions'					)
   def 		_lowerCamelCase			(self					)     ->  Tuple:
        pass
   def 		_lowerCamelCase			(self					)     ->  List[Any]:
        lowercase_					,lowercase_       :							Dict  					=       self.model_tester.prepare_config_and_inputs_for_common()

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

             lowercase_       :							Tuple  					=       ['pixel_values']
             self.assertListEqual(arg_names[:1]							,					_a					)
   def 		_lowerCamelCase			(self					)     ->  str:
        lowercase_       :							Optional[int]  					=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*_a					)
   def 		_lowerCamelCase			(self					)     ->  Optional[int]:
        def check_hidden_states_output(_a							,					_a							,					_a					):
             lowercase_       :							str  					=       model_class(_a					)

             lowercase_       :							List[Any]  					=       model(**self._prepare_for_class(_a							,					_a					)					)

             lowercase_       :							str  					=       outputs.hidden_states

             lowercase_       :							List[str]  					=       5
             self.assertEqual(len(_a					)							,					_a					)

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

        lowercase_					,lowercase_       :							List[Any]  					=       self.model_tester.prepare_config_and_inputs_for_common()

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

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

             check_hidden_states_output(_a							,					_a							,					_a					)
   def 		_lowerCamelCase			(self					)     ->  Any:
        lowercase_       :							Union[str, Any]  					=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*_a					)
   def 		_lowerCamelCase			(self					)     ->  Optional[Any]:
        lowercase_       :							List[str]  					=       self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_semantic_segmentation(*_a					)
   @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					)     ->  Dict:
        super().test_dataset_conversion()
   def 		_lowerCamelCase			(self							,					_a							,					_a							,					_a=2e-1							,					_a=2e-1					)     ->  Dict:
        self.assertTrue(np.allclose(_a							,					_a							,					atol=_a							,					rtol=_a					)					)
   @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					)     ->  str:
        lowercase_					,lowercase_       :							Dict  					=       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":
                  lowercase_       :							Any  					=       model_class(_a					)
                  if getattr(_a							,					'hf_compute_loss'							,					_a					):
                       super().test_keras_fit()
   def 		_lowerCamelCase			(self					)     ->  int:
        lowercase_					,lowercase_       :							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":
                  lowercase_       :							List[Any]  					=       5

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

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

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

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

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

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

                  for index, value in sorted_tuple_index_mapping:
                       lowercase_       :							List[str]  					=       prepared_for_class[value]

                  lowercase_       :							int  					=       tuple(_a					)

                  # Send to model
                  lowercase_       :							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					)     ->  str:
        for model_name in TF_MOBILEVIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             lowercase_       :							int  					=       TFMobileViTModel.from_pretrained(_a					)
             self.assertIsNotNone(_a					)



def _UpperCamelCase (							):
     lowercase_       :							List[Any]  					=       Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
     return image






@require_tf
class    UpperCAmelCase__	(							unittest.TestCase      ):






   """simple docstring"""
   @slow
   def 		_lowerCamelCase			(self					)     ->  List[Any]:
        lowercase_       :							int  					=       TFMobileViTForImageClassification.from_pretrained('apple/mobilevit-xx-small'					)

        lowercase_       :							str  					=       MobileViTImageProcessor.from_pretrained('apple/mobilevit-xx-small'					)
        lowercase_       :							Optional[Any]  					=       prepare_img()
        lowercase_       :							List[Any]  					=       image_processor(images=_a							,					return_tensors='tf'					)

        # forward pass
        lowercase_       :							Optional[int]  					=       model(**_a							,					training=_a					)

        # verify the logits
        lowercase_       :							Tuple  					=       tf.TensorShape((1, 1_000)					)
        self.assertEqual(outputs.logits.shape							,					_a					)

        lowercase_       :							Optional[Any]  					=       tf.constant([-1.93_64, -1.23_27, -0.46_53]					)

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





   @slow
   def 		_lowerCamelCase			(self					)     ->  Optional[Any]:
        # `from_pt` will be removed
        lowercase_       :							List[Any]  					=       TFMobileViTForSemanticSegmentation.from_pretrained('apple/deeplabv3-mobilevit-xx-small'					)

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

        lowercase_       :							Optional[Any]  					=       prepare_img()
        lowercase_       :							Union[str, Any]  					=       image_processor(images=_a							,					return_tensors='tf'					)

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

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

        lowercase_       :							Optional[int]  					=       tf.constant(
            [
                [[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]],
            ]					)

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





'''simple docstring'''




from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL
from PIL import Image

from ...utils import BaseOutput, is_torch_available, is_transformers_available


@dataclass
# Copied from diffusers.pipelines.stable_diffusion.__init__.StableDiffusionPipelineOutput with Stable->Alt
class    UpperCAmelCase__	(							_snake_case      ):






   """simple docstring"""
   A				:							Union[List[PIL.Image.Image], np.ndarray]
   A				:							Optional[List[bool]]


if is_transformers_available() and is_torch_available():
 from .modeling_roberta_series import RobertaSeriesModelWithTransformation
 from .pipeline_alt_diffusion import AltDiffusionPipeline
 from .pipeline_alt_diffusion_imgaimg import AltDiffusionImgaImgPipeline




