






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 							A_    (						__lowercase			):






 '''simple docstring'''




 def  snake_case__				(	self) ->		List[str]:

     """simple docstring"""



     _UpperCAmelCase				:      Union[str, Any]			  =				self.config_class(**self.inputs_dict)
     self.parent.assertTrue(hasattr(_A							,  '''width_multiplier'''))



class 							A_    :






 '''simple docstring'''




 def __init__(	self							,  _A							,  _A=13							,  _A=64							,  _A=2							,  _A=3							,  _A="swish"							,  _A=3							,  _A=32							,  _A=0.1							,  _A=0.02							,  _A=True							,  _A=True							,  _A=10							,  _A=None							,  _A=0.25							,  _A=0.0							,  _A=0.0							,  ) ->		List[Any]:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[int]			  =				parent
     _UpperCAmelCase				:      str			  =				batch_size
     _UpperCAmelCase				:      Tuple			  =				image_size
     _UpperCAmelCase				:      str			  =				patch_size
     _UpperCAmelCase				:      Optional[Any]			  =				num_channels
     _UpperCAmelCase				:      Union[str, Any]			  =				make_divisible(512 * width_multiplier							,  divisor=8)
     _UpperCAmelCase				:      Tuple			  =				hidden_act
     _UpperCAmelCase				:      Tuple			  =				conv_kernel_size
     _UpperCAmelCase				:      Tuple			  =				output_stride
     _UpperCAmelCase				:      Dict			  =				classifier_dropout_prob
     _UpperCAmelCase				:      Optional[Any]			  =				use_labels
     _UpperCAmelCase				:      Tuple			  =				is_training
     _UpperCAmelCase				:      Union[str, Any]			  =				num_labels
     _UpperCAmelCase				:      Tuple			  =				initializer_range
     _UpperCAmelCase				:      Optional[int]			  =				scope
     _UpperCAmelCase				:      Any			  =				width_multiplier
     _UpperCAmelCase				:      str			  =				ffn_dropout
     _UpperCAmelCase				:      List[str]			  =				attn_dropout


 def  snake_case__				(	self) ->		Optional[int]:

     """simple docstring"""



     _UpperCAmelCase				:      Any			  =				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

     _UpperCAmelCase				:      Any			  =				self.get_config()

     return config, pixel_values, labels, pixel_labels


 def  snake_case__				(	self) ->		List[str]:

     """simple docstring"""



     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  snake_case__				(	self							,  _A							,  _A							,  _A							,  _A) ->		str:

     """simple docstring"""



     _UpperCAmelCase				:      List[Any]			  =				MobileViTVaModel(config=_A)
     model.to(_A)
     model.eval()
     _UpperCAmelCase				:      Dict			  =				model(_A)
     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  snake_case__				(	self							,  _A							,  _A							,  _A							,  _A) ->		str:

     """simple docstring"""



     _UpperCAmelCase				:      Dict			  =				self.num_labels
     _UpperCAmelCase				:      int			  =				MobileViTVaForImageClassification(_A)
     model.to(_A)
     model.eval()
     _UpperCAmelCase				:      List[Any]			  =				model(_A							,  labels=_A)
     self.parent.assertEqual(result.logits.shape							,  (self.batch_size, self.num_labels))


 def  snake_case__				(	self							,  _A							,  _A							,  _A							,  _A) ->		List[Any]:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[int]			  =				self.num_labels
     _UpperCAmelCase				:      Tuple			  =				MobileViTVaForSemanticSegmentation(_A)
     model.to(_A)
     model.eval()
     _UpperCAmelCase				:      Tuple			  =				model(_A)
     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				:      int			  =				model(_A							,  labels=_A)
     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  snake_case__				(	self) ->		str:

     """simple docstring"""



     _UpperCAmelCase				:      List[str]			  =				self.prepare_config_and_inputs()
     _UpperCAmelCase  , _UpperCAmelCase  , _UpperCAmelCase  , _UpperCAmelCase				:      int			  =				config_and_inputs
     _UpperCAmelCase				:      Optional[Any]			  =				{'''pixel_values''': pixel_values}
     return config, inputs_dict



@require_torch
class 							A_    (						__lowercase ,   __lowercase ,   unittest.TestCase			):






 '''simple docstring'''




 _SCREAMING_SNAKE_CASE							:			Optional[Any] =					(
     (MobileViTVaModel, MobileViTVaForImageClassification, MobileViTVaForSemanticSegmentation)
     if is_torch_available()
     else ()
 )

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

 _SCREAMING_SNAKE_CASE							:			str =					False
 _SCREAMING_SNAKE_CASE							:			str =					False
 _SCREAMING_SNAKE_CASE							:			Optional[int] =					False
 _SCREAMING_SNAKE_CASE							:			int =					False


 def  snake_case__				(	self) ->		int:

     """simple docstring"""



     _UpperCAmelCase				:      Union[str, Any]			  =				MobileViTVaModelTester(self)
     _UpperCAmelCase				:      str			  =				MobileViTVaConfigTester(self							,  config_class=_A							,  has_text_modality=_A)


 def  snake_case__				(	self) ->		Tuple:

     """simple docstring"""



     self.config_tester.run_common_tests()


 @unittest.skip(reason='''MobileViTV2 does not use inputs_embeds''')
 def  snake_case__				(	self) ->		List[str]:

     """simple docstring"""



     pass


 @unittest.skip(reason='''MobileViTV2 does not support input and output embeddings''')
 def  snake_case__				(	self) ->		Any:

     """simple docstring"""



     pass


 @unittest.skip(reason='''MobileViTV2 does not output attentions''')
 def  snake_case__				(	self) ->		Tuple:

     """simple docstring"""



     pass


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

     """simple docstring"""



     pass


 @unittest.skip('''Will be fixed soon by reducing the size of the model used for common tests.''')
 def  snake_case__				(	self) ->		int:

     """simple docstring"""



     pass


 def  snake_case__				(	self) ->		Union[str, Any]:

     """simple docstring"""



     _UpperCAmelCase  , _UpperCAmelCase				:      Optional[Any]			  =				self.model_tester.prepare_config_and_inputs_for_common()

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

         _UpperCAmelCase				:      Optional[int]			  =				['''pixel_values''']
         self.assertListEqual(arg_names[:1]							,  _A)


 def  snake_case__				(	self) ->		Tuple:

     """simple docstring"""



     _UpperCAmelCase				:      Dict			  =				self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*_A)


 def  snake_case__				(	self) ->		Any:

     """simple docstring"""



     def check_hidden_states_output(_A							,  _A							,  _A):
         _UpperCAmelCase				:      List[Any]			  =				model_class(_A)
         model.to(_A)
         model.eval()

         with torch.no_grad():
             _UpperCAmelCase				:      Optional[int]			  =				model(**self._prepare_for_class(_A							,  _A))

         _UpperCAmelCase				:      List[str]			  =				outputs.hidden_states

         _UpperCAmelCase				:      str			  =				5
         self.assertEqual(len(_A)							,  _A)

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

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

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

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

         check_hidden_states_output(_A							,  _A							,  _A)


 def  snake_case__				(	self) ->		List[str]:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[Any]			  =				self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*_A)


 def  snake_case__				(	self) ->		int:

     """simple docstring"""



     _UpperCAmelCase				:      List[str]			  =				self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_semantic_segmentation(*_A)


 @slow
 def  snake_case__				(	self) ->		List[str]:

     """simple docstring"""



     for model_name in MOBILEVITV2_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
         _UpperCAmelCase				:      List[Any]			  =				MobileViTVaModel.from_pretrained(_A)
         self.assertIsNotNone(_A)



def      _lowerCamelCase	(						)      ->					Optional[Any]:
    _UpperCAmelCase				:      Any			  =				Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png''' )
    return image


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






 '''simple docstring'''




 @cached_property
 def  snake_case__				(	self) ->		List[Any]:

     """simple docstring"""



     return (
         MobileViTImageProcessor.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''')
         if is_vision_available()
         else None
     )


 @slow
 def  snake_case__				(	self) ->		Optional[Any]:

     """simple docstring"""



     _UpperCAmelCase				:      List[Any]			  =				MobileViTVaForImageClassification.from_pretrained('''apple/mobilevitv2-1.0-imagenet1k-256''').to(
         _A)

     _UpperCAmelCase				:      Optional[int]			  =				self.default_image_processor
     _UpperCAmelCase				:      Optional[Any]			  =				prepare_img()
     _UpperCAmelCase				:      Optional[Any]			  =				image_processor(images=_A							,  return_tensors='''pt''').to(_A)

     # forward pass
     with torch.no_grad():
         _UpperCAmelCase				:      Union[str, Any]			  =				model(**_A)

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

     _UpperCAmelCase				:      Optional[int]			  =				torch.tensor([-1.63_36e00, -7.32_04e-02, -5.18_83e-01]).to(_A)

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


 @slow
 def  snake_case__				(	self) ->		int:

     """simple docstring"""



     _UpperCAmelCase				:      Dict			  =				MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''')
     _UpperCAmelCase				:      str			  =				model.to(_A)

     _UpperCAmelCase				:      int			  =				MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''')

     _UpperCAmelCase				:      Tuple			  =				prepare_img()
     _UpperCAmelCase				:      Tuple			  =				image_processor(images=_A							,  return_tensors='''pt''').to(_A)

     # forward pass
     with torch.no_grad():
         _UpperCAmelCase				:      Optional[Any]			  =				model(**_A)
     _UpperCAmelCase				:      int			  =				outputs.logits

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

     _UpperCAmelCase				:      int			  =				torch.tensor(
         [
             [[7.0863, 7.1525, 6.8201], [6.6931, 6.8770, 6.8933], [6.2978, 7.0366, 6.9636]],
             [[-3.7134, -3.6712, -3.6675], [-3.5825, -3.3549, -3.4777], [-3.3435, -3.3979, -3.2857]],
             [[-2.9329, -2.8003, -2.7369], [-3.0564, -2.4780, -2.0207], [-2.6889, -1.9298, -1.7640]],
         ]							,  device=_A							,  )

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


 @slow
 def  snake_case__				(	self) ->		Dict:

     """simple docstring"""



     _UpperCAmelCase				:      Dict			  =				MobileViTVaForSemanticSegmentation.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''')
     _UpperCAmelCase				:      int			  =				model.to(_A)

     _UpperCAmelCase				:      int			  =				MobileViTImageProcessor.from_pretrained('''shehan97/mobilevitv2-1.0-voc-deeplabv3''')

     _UpperCAmelCase				:      List[str]			  =				prepare_img()
     _UpperCAmelCase				:      Optional[Any]			  =				image_processor(images=_A							,  return_tensors='''pt''').to(_A)

     # forward pass
     with torch.no_grad():
         _UpperCAmelCase				:      List[str]			  =				model(**_A)

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

     _UpperCAmelCase				:      Dict			  =				image_processor.post_process_semantic_segmentation(outputs=_A							,  target_sizes=[(50, 60)])
     _UpperCAmelCase				:      List[Any]			  =				torch.Size((50, 60))
     self.assertEqual(segmentation[0].shape							,  _A)

     _UpperCAmelCase				:      List[Any]			  =				image_processor.post_process_semantic_segmentation(outputs=_A)
     _UpperCAmelCase				:      Tuple			  =				torch.Size((32, 32))
     self.assertEqual(segmentation[0].shape							,  _A)












import importlib
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path

import transformers
import transformers.models.auto
from transformers.models.auto.configuration_auto import CONFIG_MAPPING, AutoConfig
from transformers.models.bert.configuration_bert import BertConfig
from transformers.models.roberta.configuration_roberta import RobertaConfig
from transformers.testing_utils import DUMMY_UNKNOWN_IDENTIFIER, get_tests_dir


sys.path.append(str(Path(__file__).parent.parent.parent.parent / 'utils'))

from test_module.custom_configuration import CustomConfig  # noqa E402


SCREAMING_SNAKE_CASE 							=						get_tests_dir('fixtures/dummy-config.json')
class 							A_    (						unittest.TestCase			):






 '''simple docstring'''




 def  snake_case__				(	self) ->		Optional[int]:

     """simple docstring"""



     _UpperCAmelCase				:      Union[str, Any]			  =				0


 def  snake_case__				(	self) ->		Union[str, Any]:

     """simple docstring"""



     self.assertIsNotNone(transformers.models.auto.__spec__)
     self.assertIsNotNone(importlib.util.find_spec('''transformers.models.auto'''))


 def  snake_case__				(	self) ->		Optional[Any]:

     """simple docstring"""



     _UpperCAmelCase				:      List[str]			  =				AutoConfig.from_pretrained('''bert-base-uncased''')
     self.assertIsInstance(_A							,  _A)


 def  snake_case__				(	self) ->		Dict:

     """simple docstring"""



     _UpperCAmelCase				:      Tuple			  =				AutoConfig.from_pretrained(_A)
     self.assertIsInstance(_A							,  _A)


 def  snake_case__				(	self) ->		Optional[int]:

     """simple docstring"""



     _UpperCAmelCase				:      Optional[Any]			  =				AutoConfig.from_pretrained(_A)
     self.assertIsInstance(_A							,  _A)


 def  snake_case__				(	self) ->		Any:

     """simple docstring"""



     _UpperCAmelCase				:      str			  =				AutoConfig.for_model('''roberta''')
     self.assertIsInstance(_A							,  _A)


 def  snake_case__				(	self) ->		int:

     """simple docstring"""



     with tempfile.TemporaryDirectory() as tmp_dir:
         # This model name contains bert and roberta, but roberta ends up being picked.
         _UpperCAmelCase				:      str			  =				os.path.join(_A							,  '''fake-roberta''')
         os.makedirs(_A							,  exist_ok=_A)
         with open(os.path.join(_A							,  '''config.json''')							,  '''w''') as f:
             f.write(json.dumps({}))
         _UpperCAmelCase				:      Any			  =				AutoConfig.from_pretrained(_A)
         self.assertEqual(type(_A)							,  _A)


 def  snake_case__				(	self) ->		List[Any]:

     """simple docstring"""



     try:
         AutoConfig.register('''custom'''							,  _A)
         # Wrong model type will raise an error
         with self.assertRaises(_A):
             AutoConfig.register('''model'''							,  _A)
         # Trying to register something existing in the Transformers library will raise an error
         with self.assertRaises(_A):
             AutoConfig.register('''bert'''							,  _A)

         # Now that the config is registered, it can be used as any other config with the auto-API
         _UpperCAmelCase				:      Tuple			  =				CustomConfig()
         with tempfile.TemporaryDirectory() as tmp_dir:
             config.save_pretrained(_A)
             _UpperCAmelCase				:      Tuple			  =				AutoConfig.from_pretrained(_A)
             self.assertIsInstance(_A							,  _A)

     finally:
         if "custom" in CONFIG_MAPPING._extra_content:
             del CONFIG_MAPPING._extra_content["custom"]


 def  snake_case__				(	self) ->		Union[str, Any]:

     """simple docstring"""



     with self.assertRaisesRegex(
         _A							,  '''bert-base is not a local folder and is not a valid model identifier'''):
         _UpperCAmelCase				:      Tuple			  =				AutoConfig.from_pretrained('''bert-base''')


 def  snake_case__				(	self) ->		int:

     """simple docstring"""



     with self.assertRaisesRegex(
         _A							,  R'''aaaaaa is not a valid git identifier \(branch name, tag name or commit id\)'''):
         _UpperCAmelCase				:      List[Any]			  =				AutoConfig.from_pretrained(_A							,  revision='''aaaaaa''')


 def  snake_case__				(	self) ->		Optional[Any]:

     """simple docstring"""



     with self.assertRaisesRegex(
         _A							,  '''hf-internal-testing/no-config-test-repo does not appear to have a file named config.json.'''							,  ):
         _UpperCAmelCase				:      List[str]			  =				AutoConfig.from_pretrained('''hf-internal-testing/no-config-test-repo''')


 def  snake_case__				(	self) ->		List[str]:

     """simple docstring"""



     with self.assertRaises(_A):
         _UpperCAmelCase				:      Dict			  =				AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model''')
     # If remote code is disabled, we can't load this config.
     with self.assertRaises(_A):
         _UpperCAmelCase				:      Optional[int]			  =				AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model'''							,  trust_remote_code=_A)

     _UpperCAmelCase				:      int			  =				AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model'''							,  trust_remote_code=_A)
     self.assertEqual(config.__class__.__name__							,  '''NewModelConfig''')

     # Test config can be reloaded.
     with tempfile.TemporaryDirectory() as tmp_dir:
         config.save_pretrained(_A)
         _UpperCAmelCase				:      Any			  =				AutoConfig.from_pretrained(_A							,  trust_remote_code=_A)
     self.assertEqual(reloaded_config.__class__.__name__							,  '''NewModelConfig''')


 def  snake_case__				(	self) ->		Tuple:

     """simple docstring"""



     class 							A_    (						__lowercase			):






      '''simple docstring'''




      _SCREAMING_SNAKE_CASE							:			Union[str, Any] =					"new-model"

     try:
         AutoConfig.register('''new-model'''							,  _A)
         # If remote code is not set, the default is to use local
         _UpperCAmelCase				:      List[str]			  =				AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model''')
         self.assertEqual(config.__class__.__name__							,  '''NewModelConfigLocal''')

         # If remote code is disabled, we load the local one.
         _UpperCAmelCase				:      List[Any]			  =				AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model'''							,  trust_remote_code=_A)
         self.assertEqual(config.__class__.__name__							,  '''NewModelConfigLocal''')

         # If remote is enabled, we load from the Hub
         _UpperCAmelCase				:      Dict			  =				AutoConfig.from_pretrained('''hf-internal-testing/test_dynamic_model'''							,  trust_remote_code=_A)
         self.assertEqual(config.__class__.__name__							,  '''NewModelConfig''')

     finally:
         if "new-model" in CONFIG_MAPPING._extra_content:
             del CONFIG_MAPPING._extra_content["new-model"]




