import inspect
import unittest

from transformers import MobileViTVaConfig
from transformers.testing_utils import require_torch, require_torch_multi_gpu, 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 MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation, MobileViTVaModel
      from transformers.models.mobilevitva.modeling_mobilevitva import (
          MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST,
          make_divisible,
      )


if is_vision_available():
      from PIL import Image

      from transformers import MobileViTImageProcessor



class   snake_case_       (		__A       ):






   def       __UpperCamelCase     (      self				:     Optional[Any]  )					->						List[str]:
       lowercase__ :   str    					=				self.config_class(**self.inputs_dict  )
       self.parent.assertTrue(hasattr(lowercase_	,						"width_multiplier"  )  )



class   snake_case_       :






   def __init__(      self				:     Optional[int]	,						lowercase_				:     Union[str, Any]	,						lowercase_				:     List[str]=13	,						lowercase_				:     List[str]=64	,						lowercase_				:     Any=2	,						lowercase_				:     Dict=3	,						lowercase_				:     Tuple="swish"	,						lowercase_				:     List[Any]=3	,						lowercase_				:     List[Any]=32	,						lowercase_				:     str=0.1	,						lowercase_				:     Any=0.02	,						lowercase_				:     Optional[int]=True	,						lowercase_				:     List[str]=True	,						lowercase_				:     Optional[Any]=10	,						lowercase_				:     List[str]=None	,						lowercase_				:     int=0.25	,						lowercase_				:     List[str]=0.0	,						lowercase_				:     str=0.0	,						)					->						Dict:
       lowercase__ :   Optional[int]    					=				parent
       lowercase__ :   Optional[Any]    					=				batch_size
       lowercase__ :   str    					=				image_size
       lowercase__ :   Union[str, Any]    					=				patch_size
       lowercase__ :   Tuple    					=				num_channels
       lowercase__ :   Optional[int]    					=				make_divisible(5_12 * width_multiplier	,						divisor=8  )
       lowercase__ :   Optional[Any]    					=				hidden_act
       lowercase__ :   Union[str, Any]    					=				conv_kernel_size
       lowercase__ :   Tuple    					=				output_stride
       lowercase__ :   Dict    					=				classifier_dropout_prob
       lowercase__ :   Optional[int]    					=				use_labels
       lowercase__ :   Dict    					=				is_training
       lowercase__ :   Optional[int]    					=				num_labels
       lowercase__ :   Tuple    					=				initializer_range
       lowercase__ :   List[Any]    					=				scope
       lowercase__ :   List[Any]    					=				width_multiplier
       lowercase__ :   Optional[Any]    					=				ffn_dropout
       lowercase__ :   List[Any]    					=				attn_dropout






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

       lowercase__ :   Union[str, Any]    					=				None
       lowercase__ :   List[Any]    					=				None
       if self.use_labels:
           lowercase__ :   int    					=				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__ :   Dict    					=				self.get_config()

       return config, pixel_values, labels, pixel_labels






   def       __UpperCamelCase     (      self				:     Any  )					->						List[str]:
       return MobileViTVaConfig(
           image_size=self.image_size	,						patch_size=self.patch_size	,						num_channels=self.num_channels	,						hidden_act=self.hidden_act	,						conv_kernel_size=self.conv_kernel_size	,						output_stride=self.output_stride	,						classifier_dropout_prob=self.classifier_dropout_prob	,						initializer_range=self.initializer_range	,						width_multiplier=self.width_multiplier	,						ffn_dropout=self.ffn_dropout_prob	,						attn_dropout=self.attn_dropout_prob	,						)






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






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



@require_torch
class   snake_case_       (		__A  ,__A  ,unittest.TestCase       ):
   __A	:		Optional[int]         =				(
       (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
       if is_torch_available()
       else ()
   )

   __A	:		Tuple         =				(
       {
           "feature-extraction": MobileViTVaModel,
           "image-classification": MobileViTVaForImageClassification,
           "image-segmentation": MobileViTVaForSemanticSegmentation,
       }
       if is_torch_available()
       else {}
   )

   __A	:		List[Any]         =				False
   __A	:		List[str]         =				False
   __A	:		List[str]         =				False
   __A	:		List[Any]         =				False






   def       __UpperCamelCase     (      self				:     str  )					->						List[Any]:
       lowercase__ :   int    					=				MobileViTVaModelTester(self  )
       lowercase__ :   Optional[int]    					=				MobileViTVaConfigTester(self	,						config_class=lowercase_	,						has_text_modality=lowercase_  )






   def       __UpperCamelCase     (      self				:     Any  )					->						Union[str, Any]:
       self.config_tester.run_common_tests()






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






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






   @unittest.skip(reason="MobileViTV2 does not output attentions"  )
   def       __UpperCamelCase     (      self				:     str  )					->						Optional[int]:
       pass






   @require_torch_multi_gpu
   @unittest.skip(reason="Got `CUDA error: misaligned address` for tests after this one being run."  )
   def       __UpperCamelCase     (      self				:     Any  )					->						int:
       pass






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






   def       __UpperCamelCase     (      self				:     Optional[int]  )					->						Union[str, Any]:
       lowercase__					,   lowercase__ :   Dict    					=				self.model_tester.prepare_config_and_inputs_for_common()

       for model_class in self.all_model_classes:
           lowercase__ :   Union[str, Any]    					=				model_class(lowercase_  )
           lowercase__ :   List[Any]    					=				inspect.signature(model.forward  )
           # signature.parameters is an OrderedDict => so arg_names order is deterministic
           lowercase__ :   List[str]    					=				[*signature.parameters.keys()]

           lowercase__ :   List[str]    					=				["pixel_values"]
           self.assertListEqual(arg_names[:1]	,						lowercase_  )






   def       __UpperCamelCase     (      self				:     Union[str, Any]  )					->						Any:
       lowercase__ :   List[Any]    					=				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowercase_  )






   def       __UpperCamelCase     (      self				:     Union[str, Any]  )					->						Dict:
       def check_hidden_states_output(lowercase_				:     int	,						lowercase_				:     Dict	,						lowercase_				:     Dict  ):
           lowercase__ :   Any    					=				model_class(lowercase_  )
           model.to(lowercase_  )
           model.eval()

           with torch.no_grad():
               lowercase__ :   Optional[Any]    					=				model(**self._prepare_for_class(lowercase_	,						lowercase_  )  )

           lowercase__ :   Optional[int]    					=				outputs.hidden_states

           lowercase__ :   Any    					=				5
           self.assertEqual(len(lowercase_  )	,						lowercase_  )

           # MobileViTV2's feature maps are of shape (batch_size, num_channels, height, width)
           # with the width and height being successively divided by 2.
           lowercase__ :   Optional[int]    					=				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  )

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

       for model_class in self.all_model_classes:
           lowercase__ :   Tuple    					=				True
           check_hidden_states_output(lowercase_	,						lowercase_	,						lowercase_  )

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

           check_hidden_states_output(lowercase_	,						lowercase_	,						lowercase_  )






   def       __UpperCamelCase     (      self				:     List[Any]  )					->						str:
       lowercase__ :   str    					=				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_image_classification(*lowercase_  )






   def       __UpperCamelCase     (      self				:     Any  )					->						int:
       lowercase__ :   Dict    					=				self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_semantic_segmentation(*lowercase_  )







   @slow
   def       __UpperCamelCase     (      self				:     Union[str, Any]  )					->						List[str]:
       for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowercase__ :   Tuple    					=				MobileViTVaModel.from_pretrained(lowercase_  )
           self.assertIsNotNone(lowercase_  )



def 			lowercase_				(			):
    lowercase__ :   Optional[int]    					=				Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
    return image



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






   @cached_property
   def       __UpperCamelCase     (      self				:     List[Any]  )					->						Optional[Any]:
       return (
           MobileViTImageProcessor.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"  )
           if is_vision_available()
           else None
       )






   @slow
   def       __UpperCamelCase     (      self				:     Union[str, Any]  )					->						List[str]:
       lowercase__ :   List[str]    					=				MobileViTVaForImageClassification.from_pretrained("apple/mobilevitv2-1.0-imagenet1k-256"  ).to(
           lowercase_  )

       lowercase__ :   int    					=				self.default_image_processor
       lowercase__ :   int    					=				prepare_img()
       lowercase__ :   Optional[int]    					=				image_processor(images=lowercase_	,						return_tensors="pt"  ).to(lowercase_  )

       # forward pass
       with torch.no_grad():
           lowercase__ :   str    					=				model(**lowercase_  )

       # verify the logits
       lowercase__ :   Optional[int]    					=				torch.Size((1, 10_00)  )
       self.assertEqual(outputs.logits.shape	,						lowercase_  )

       lowercase__ :   Tuple    					=				torch.tensor([-1.63_36E00, -7.32_04E-02, -5.18_83E-01]  ).to(lowercase_  )

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






   @slow
   def       __UpperCamelCase     (      self				:     Tuple  )					->						Optional[int]:
       lowercase__ :   Dict    					=				MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"  )
       lowercase__ :   int    					=				model.to(lowercase_  )

       lowercase__ :   Any    					=				MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"  )

       lowercase__ :   List[str]    					=				prepare_img()
       lowercase__ :   int    					=				image_processor(images=lowercase_	,						return_tensors="pt"  ).to(lowercase_  )

       # forward pass
       with torch.no_grad():
           lowercase__ :   str    					=				model(**lowercase_  )
       lowercase__ :   Tuple    					=				outputs.logits

       # verify the logits
       lowercase__ :   Union[str, Any]    					=				torch.Size((1, 21, 32, 32)  )
       self.assertEqual(logits.shape	,						lowercase_  )

       lowercase__ :   Optional[Any]    					=				torch.tensor(
           [
               [[7.08_63, 7.15_25, 6.82_01], [6.69_31, 6.87_70, 6.89_33], [6.29_78, 7.03_66, 6.96_36]],
               [[-3.71_34, -3.67_12, -3.66_75], [-3.58_25, -3.35_49, -3.47_77], [-3.34_35, -3.39_79, -3.28_57]],
               [[-2.93_29, -2.80_03, -2.73_69], [-3.05_64, -2.47_80, -2.02_07], [-2.68_89, -1.92_98, -1.76_40]],
           ]	,						device=lowercase_	,						)

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







   @slow
   def       __UpperCamelCase     (      self				:     Any  )					->						List[str]:
       lowercase__ :   Dict    					=				MobileViTVaForSemanticSegmentation.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"  )
       lowercase__ :   int    					=				model.to(lowercase_  )

       lowercase__ :   Optional[int]    					=				MobileViTImageProcessor.from_pretrained("shehan97/mobilevitv2-1.0-voc-deeplabv3"  )

       lowercase__ :   List[str]    					=				prepare_img()
       lowercase__ :   Tuple    					=				image_processor(images=lowercase_	,						return_tensors="pt"  ).to(lowercase_  )

       # forward pass
       with torch.no_grad():
           lowercase__ :   Optional[Any]    					=				model(**lowercase_  )

       lowercase__ :   Tuple    					=				outputs.logits.detach().cpu()

       lowercase__ :   List[str]    					=				image_processor.post_process_semantic_segmentation(outputs=lowercase_	,						target_sizes=[(50, 60)]  )
       lowercase__ :   List[str]    					=				torch.Size((50, 60)  )
       self.assertEqual(segmentation[0].shape	,						lowercase_  )

       lowercase__ :   int    					=				image_processor.post_process_semantic_segmentation(outputs=lowercase_  )
       lowercase__ :   Dict    					=				torch.Size((32, 32)  )
       self.assertEqual(segmentation[0].shape	,						lowercase_  )





# Copyright 2021 The HuggingFace Inc. team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from packaging import version

from .. import __version__
from .constants import IMAGENET_DEFAULT_MEAN, IMAGENET_DEFAULT_STD, IMAGENET_STANDARD_MEAN, IMAGENET_STANDARD_STD
from .doc import (
    add_code_sample_docstrings,
    add_end_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    copy_func,
    replace_return_docstrings,
)
from .generic import (
    ContextManagers,
    ExplicitEnum,
    ModelOutput,
    PaddingStrategy,
    TensorType,
    add_model_info_to_auto_map,
    cached_property,
    can_return_loss,
    expand_dims,
    find_labels,
    flatten_dict,
    infer_framework,
    is_jax_tensor,
    is_numpy_array,
    is_tensor,
    is_tf_symbolic_tensor,
    is_tf_tensor,
    is_torch_device,
    is_torch_dtype,
    is_torch_tensor,
    reshape,
    squeeze,
    strtobool,
    tensor_size,
    to_numpy,
    to_py_obj,
    transpose,
    working_or_temp_dir,
)
from .hub import (
    CLOUDFRONT_DISTRIB_PREFIX,
    DISABLE_TELEMETRY,
    HF_MODULES_CACHE,
    HUGGINGFACE_CO_PREFIX,
    HUGGINGFACE_CO_RESOLVE_ENDPOINT,
    PYTORCH_PRETRAINED_BERT_CACHE,
    PYTORCH_TRANSFORMERS_CACHE,
    S3_BUCKET_PREFIX,
    TRANSFORMERS_CACHE,
    TRANSFORMERS_DYNAMIC_MODULE_NAME,
    EntryNotFoundError,
    PushToHubMixin,
    RepositoryNotFoundError,
    RevisionNotFoundError,
    cached_file,
    default_cache_path,
    define_sagemaker_information,
    download_url,
    extract_commit_hash,
    get_cached_models,
    get_file_from_repo,
    get_full_repo_name,
    has_file,
    http_user_agent,
    is_offline_mode,
    is_remote_url,
    move_cache,
    send_example_telemetry,
    try_to_load_from_cache,
)
from .import_utils import (
    ENV_VARS_TRUE_AND_AUTO_VALUES,
    ENV_VARS_TRUE_VALUES,
    TORCH_FX_REQUIRED_VERSION,
    USE_JAX,
    USE_TF,
    USE_TORCH,
    DummyObject,
    OptionalDependencyNotAvailable,
    _LazyModule,
    ccl_version,
    direct_transformers_import,
    get_torch_version,
    is_accelerate_available,
    is_apex_available,
    is_bitsandbytes_available,
    is_bsa_available,
    is_coloredlogs_available,
    is_cython_available,
    is_datasets_available,
    is_decord_available,
    is_detectrona_available,
    is_faiss_available,
    is_flax_available,
    is_ftfy_available,
    is_in_notebook,
    is_ipex_available,
    is_jieba_available,
    is_jumanpp_available,
    is_kenlm_available,
    is_keras_nlp_available,
    is_librosa_available,
    is_natten_available,
    is_ninja_available,
    is_onnx_available,
    is_openai_available,
    is_optimum_available,
    is_pandas_available,
    is_peft_available,
    is_phonemizer_available,
    is_protobuf_available,
    is_psutil_available,
    is_pyanvml_available,
    is_pyctcdecode_available,
    is_pytesseract_available,
    is_pytest_available,
    is_pytorch_quantization_available,
    is_rjieba_available,
    is_sacremoses_available,
    is_safetensors_available,
    is_sagemaker_dp_enabled,
    is_sagemaker_mp_enabled,
    is_scipy_available,
    is_sentencepiece_available,
    is_seqio_available,
    is_sklearn_available,
    is_soundfile_availble,
    is_spacy_available,
    is_speech_available,
    is_sudachi_available,
    is_tensorflow_probability_available,
    is_tensorflow_text_available,
    is_tfaonnx_available,
    is_tf_available,
    is_timm_available,
    is_tokenizers_available,
    is_torch_available,
    is_torch_bfaa_available,
    is_torch_bfaa_cpu_available,
    is_torch_bfaa_gpu_available,
    is_torch_compile_available,
    is_torch_cuda_available,
    is_torch_fx_available,
    is_torch_fx_proxy,
    is_torch_mps_available,
    is_torch_neuroncore_available,
    is_torch_tensorrt_fx_available,
    is_torch_tfaa_available,
    is_torch_tpu_available,
    is_torchaudio_available,
    is_torchdistx_available,
    is_torchdynamo_available,
    is_torchvision_available,
    is_training_run_on_sagemaker,
    is_vision_available,
    requires_backends,
    torch_only_method,
)


_lowerCamelCase					   ="""pytorch_model.bin"""
_lowerCamelCase					   ="""pytorch_model.bin.index.json"""
_lowerCamelCase					   ="""adapter_config.json"""
_lowerCamelCase					   ="""adapter_model.bin"""
_lowerCamelCase					   ="""adapter_model.safetensors"""
_lowerCamelCase					   ="""tf_model.h5"""
_lowerCamelCase					   ="""tf_model.h5.index.json"""
_lowerCamelCase					   ="""model.ckpt"""
_lowerCamelCase					   ="""flax_model.msgpack"""
_lowerCamelCase					   ="""flax_model.msgpack.index.json"""
_lowerCamelCase					   ="""model.safetensors"""
_lowerCamelCase					   ="""model.safetensors.index.json"""
_lowerCamelCase					   ="""config.json"""
_lowerCamelCase					   ="""preprocessor_config.json"""
_lowerCamelCase					   =FEATURE_EXTRACTOR_NAME
_lowerCamelCase					   ="""generation_config.json"""
_lowerCamelCase					   ="""modelcard.json"""

_lowerCamelCase					   ="""▁"""
_lowerCamelCase					   =SENTENCEPIECE_UNDERLINE  # Kept for backward compatibility

_lowerCamelCase					   =[
    [[0, 1, 0, 1], [1, 0, 0, 1]]
] * 2  # Needs to have 0s and 1s only since XLM uses it for langs too.
_lowerCamelCase					   =[[7, 6, 0, 0, 1], [1, 2, 3, 0, 0], [0, 0, 0, 4, 5]]
_lowerCamelCase					   =[[1, 1, 1, 1, 1], [1, 1, 1, 0, 0], [0, 0, 0, 1, 1]]





def     _a					(						lowerCamelCase							):
 if version.parse(lowerCamelCase							) < version.parse(lowerCamelCase							):
  if "dev" in min_version:
   lowerCamelCase		:	Optional[int]							=      (
       """This example requires a source install from HuggingFace Transformers (see """
       """`https://huggingface.co/docs/transformers/installation#install-from-source`),"""
   )
  else:
   lowerCamelCase		:	int							=      F'''This example requires a minimum version of {min_version},'''
  error_message += F''' but the version found is {__version__}.\n'''
  raise ImportError(
      error_message
      + """Check out https://github.com/huggingface/transformers/tree/main/examples#important-note for the examples corresponding to other """
      """versions of HuggingFace Transformers."""							)




