





import inspect
import unittest

from transformers import ViTConfig
from transformers.testing_utils import (
    require_accelerate,
    require_torch,
    require_torch_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 torch import nn

      from transformers import ViTForImageClassification, ViTForMaskedImageModeling, ViTModel
      from transformers.models.vit.modeling_vit import VIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image

      from transformers import ViTImageProcessor





class 					A_					:







       """simple docstring"""





       def __init__(     self						:						List[Any]    ,__A						:						Dict    ,__A						:						Union[str, Any]=13    ,__A						:						str=30    ,__A						:						Any=2    ,__A						:						Dict=3    ,__A						:						List[str]=True    ,__A						:						Optional[int]=True    ,__A						:						List[Any]=32    ,__A						:						Optional[int]=5    ,__A						:						List[Any]=4    ,__A						:						Optional[Any]=37    ,__A						:						Optional[Any]="gelu"    ,__A						:						Optional[int]=0.1    ,__A						:						Tuple=0.1    ,__A						:						Tuple=10    ,__A						:						Dict=0.02    ,__A						:						List[Any]=None    ,__A						:						Optional[Any]=2    ,)    ->       List[str]:
         _lowercase						    =			parent
         _lowercase						    =			batch_size
         _lowercase						    =			image_size
         _lowercase						    =			patch_size
         _lowercase						    =			num_channels
         _lowercase						    =			is_training
         _lowercase						    =			use_labels
         _lowercase						    =			hidden_size
         _lowercase						    =			num_hidden_layers
         _lowercase						    =			num_attention_heads
         _lowercase						    =			intermediate_size
         _lowercase						    =			hidden_act
         _lowercase						    =			hidden_dropout_prob
         _lowercase						    =			attention_probs_dropout_prob
         _lowercase						    =			type_sequence_label_size
         _lowercase						    =			initializer_range
         _lowercase						    =			scope
         _lowercase						    =			encoder_stride

         # in ViT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
         _lowercase						    =			(image_size // patch_size) ** 2
         _lowercase						    =			num_patches + 1







       def  __UpperCAmelCase			(     self						:						int	)    ->       int:
         _lowercase						    =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

         _lowercase						    =			None
         if self.use_labels:
           _lowercase						    =			ids_tensor([self.batch_size]    ,self.type_sequence_label_size	)

         _lowercase						    =			self.get_config()

         return config, pixel_values, labels







       def  __UpperCAmelCase			(     self						:						Tuple	)    ->       str:
         return ViTConfig(
             image_size=self.image_size    ,patch_size=self.patch_size    ,num_channels=self.num_channels    ,hidden_size=self.hidden_size    ,num_hidden_layers=self.num_hidden_layers    ,num_attention_heads=self.num_attention_heads    ,intermediate_size=self.intermediate_size    ,hidden_act=self.hidden_act    ,hidden_dropout_prob=self.hidden_dropout_prob    ,attention_probs_dropout_prob=self.attention_probs_dropout_prob    ,is_decoder=__A    ,initializer_range=self.initializer_range    ,encoder_stride=self.encoder_stride    ,)







       def  __UpperCAmelCase			(     self						:						str    ,__A						:						Union[str, Any]    ,__A						:						Optional[int]    ,__A						:						List[Any]	)    ->       Union[str, Any]:
         _lowercase						    =			ViTModel(config=__A	)
         model.to(__A	)
         model.eval()
         _lowercase						    =			model(__A	)
         self.parent.assertEqual(result.last_hidden_state.shape    ,(self.batch_size, self.seq_length, self.hidden_size)	)







       def  __UpperCAmelCase			(     self						:						List[Any]    ,__A						:						str    ,__A						:						List[Any]    ,__A						:						int	)    ->       Union[str, Any]:
         _lowercase						    =			ViTForMaskedImageModeling(config=__A	)
         model.to(__A	)
         model.eval()
         _lowercase						    =			model(__A	)
         self.parent.assertEqual(
             result.reconstruction.shape    ,(self.batch_size, self.num_channels, self.image_size, self.image_size)	)

         # test greyscale images
         _lowercase						    =			1
         _lowercase						    =			ViTForMaskedImageModeling(__A	)
         model.to(__A	)
         model.eval()

         _lowercase						    =			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]	)
         _lowercase						    =			model(__A	)
         self.parent.assertEqual(result.reconstruction.shape    ,(self.batch_size, 1, self.image_size, self.image_size)	)







       def  __UpperCAmelCase			(     self						:						str    ,__A						:						Union[str, Any]    ,__A						:						Dict    ,__A						:						List[Any]	)    ->       int:
         _lowercase						    =			self.type_sequence_label_size
         _lowercase						    =			ViTForImageClassification(__A	)
         model.to(__A	)
         model.eval()
         _lowercase						    =			model(__A    ,labels=__A	)
         self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.type_sequence_label_size)	)

         # test greyscale images
         _lowercase						    =			1
         _lowercase						    =			ViTForImageClassification(__A	)
         model.to(__A	)
         model.eval()

         _lowercase						    =			floats_tensor([self.batch_size, 1, self.image_size, self.image_size]	)
         _lowercase						    =			model(__A	)
         self.parent.assertEqual(result.logits.shape    ,(self.batch_size, self.type_sequence_label_size)	)







       def  __UpperCAmelCase			(     self						:						Optional[Any]	)    ->       str:
         _lowercase						    =			self.prepare_config_and_inputs()
         (
             (
             _lowercase
         )    ,		(
             _lowercase
         )    ,		(
             _lowercase
         )    ,		
         )						    =			config_and_inputs
         _lowercase						    =			{'pixel_values': pixel_values}
         return config, inputs_dict





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







       """simple docstring"""





       SCREAMING_SNAKE_CASE_   :			Optional[Any]  			=	(
           (
               ViTModel,
               ViTForImageClassification,
               ViTForMaskedImageModeling,
           )
           if is_torch_available()
           else ()
       )
       SCREAMING_SNAKE_CASE_   :			str  			=	(
           {'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification}
           if is_torch_available()
           else {}
       )
       SCREAMING_SNAKE_CASE_   :			Optional[int]  			=	True

       SCREAMING_SNAKE_CASE_   :			int  			=	False
       SCREAMING_SNAKE_CASE_   :			Dict  			=	False
       SCREAMING_SNAKE_CASE_   :			Optional[int]  			=	False







       def  __UpperCAmelCase			(     self						:						Any	)    ->       Tuple:
         _lowercase						    =			ViTModelTester(self	)
         _lowercase						    =			ConfigTester(self    ,config_class=__A    ,has_text_modality=__A    ,hidden_size=37	)







       def  __UpperCAmelCase			(     self						:						Tuple	)    ->       List[Any]:
         self.config_tester.run_common_tests()







       @unittest.skip(reason='ViT does not use inputs_embeds'	)
       def  __UpperCAmelCase			(     self						:						int	)    ->       List[Any]:
         pass







       def  __UpperCAmelCase			(     self						:						List[str]	)    ->       Optional[Any]:
         _lowercase    ,		_lowercase						    =			self.model_tester.prepare_config_and_inputs_for_common()

         for model_class in self.all_model_classes:
           _lowercase						    =			model_class(__A	)
           self.assertIsInstance(model.get_input_embeddings()    ,(nn.Module)	)
           _lowercase						    =			model.get_output_embeddings()
           self.assertTrue(x is None or isinstance(__A    ,nn.Linear	)	)







       def  __UpperCAmelCase			(     self						:						List[Any]	)    ->       Tuple:
         _lowercase    ,		_lowercase						    =			self.model_tester.prepare_config_and_inputs_for_common()

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

           _lowercase						    =			['pixel_values']
           self.assertListEqual(arg_names[:1]    ,__A	)







       def  __UpperCAmelCase			(     self						:						Dict	)    ->       Optional[Any]:
         _lowercase						    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_model(*__A	)







       def  __UpperCAmelCase			(     self						:						Dict	)    ->       Any:
         _lowercase						    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_masked_image_modeling(*__A	)







       def  __UpperCAmelCase			(     self						:						str	)    ->       Any:
         _lowercase						    =			self.model_tester.prepare_config_and_inputs()
         self.model_tester.create_and_check_for_image_classification(*__A	)







       @slow
       def  __UpperCAmelCase			(     self						:						List[str]	)    ->       Any:
         for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           _lowercase						    =			ViTModel.from_pretrained(__A	)
           self.assertIsNotNone(__A	)

def 				SCREAMING_SNAKE_CASE__							(	)   ->    Dict:
  _lowercase						    =			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'  )
  return image







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







       """simple docstring"""





       @cached_property
       def  __UpperCAmelCase			(     self						:						List[Any]	)    ->       List[str]:
         return ViTImageProcessor.from_pretrained('google/vit-base-patch16-224'	) if is_vision_available() else None







       @slow
       def  __UpperCAmelCase			(     self						:						int	)    ->       Tuple:
         _lowercase						    =			ViTForImageClassification.from_pretrained('google/vit-base-patch16-224'	).to(__A	)

         _lowercase						    =			self.default_image_processor
         _lowercase						    =			prepare_img()
         _lowercase						    =			image_processor(images=__A    ,return_tensors='pt'	).to(__A	)

         # forward pass
         with torch.no_grad():
           _lowercase						    =			model(**__A	)

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

         _lowercase						    =			torch.tensor([-0.2744, 0.8215, -0.0836]	).to(__A	)

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







       @slow
       def  __UpperCAmelCase			(     self						:						List[Any]	)    ->       Any:
         # ViT models have an `interpolate_pos_encoding` argument in their forward method,
         # allowing to interpolate the pre-trained position embeddings in order to use
         # the model on higher resolutions. The DINO model by Facebook AI leverages this
         # to visualize self-attention on higher resolution images.
         _lowercase						    =			ViTModel.from_pretrained('facebook/dino-vits8'	).to(__A	)

         _lowercase						    =			ViTImageProcessor.from_pretrained('facebook/dino-vits8'    ,size=480	)
         _lowercase						    =			prepare_img()
         _lowercase						    =			image_processor(images=__A    ,return_tensors='pt'	)
         _lowercase						    =			inputs.pixel_values.to(__A	)

         # forward pass
         with torch.no_grad():
           _lowercase						    =			model(__A    ,interpolate_pos_encoding=__A	)

         # verify the logits
         _lowercase						    =			torch.Size((1, 3601, 384)	)
         self.assertEqual(outputs.last_hidden_state.shape    ,__A	)

         _lowercase						    =			torch.tensor(
             [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]]	).to(__A	)

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







       @slow
       @require_accelerate
       @require_torch_gpu
       def  __UpperCAmelCase			(     self						:						str	)    ->       Dict:
         _lowercase						    =			ViTModel.from_pretrained('facebook/dino-vits8'    ,torch_dtype=torch.floataa    ,device_map='auto'	)
         _lowercase						    =			self.default_image_processor

         _lowercase						    =			prepare_img()
         _lowercase						    =			image_processor(images=__A    ,return_tensors='pt'	)
         _lowercase						    =			inputs.pixel_values.to(__A	)

         # forward pass to make sure inference works in fp16
         with torch.no_grad():
           _lowercase						    =			model(__A	)






from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


_lowerCamelCase      							=   {
    'configuration_clipseg': [
        'CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'CLIPSegConfig',
        'CLIPSegTextConfig',
        'CLIPSegVisionConfig',
    ],
    'processing_clipseg': ['CLIPSegProcessor'],
}

try:
       if not is_torch_available():
              raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
       pass
else:
       _lowerCamelCase      							=   [
           'CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST',
           'CLIPSegModel',
           'CLIPSegPreTrainedModel',
           'CLIPSegTextModel',
           'CLIPSegVisionModel',
           'CLIPSegForImageSegmentation',
       ]

if TYPE_CHECKING:
       from .configuration_clipseg import (
           CLIPSEG_PRETRAINED_CONFIG_ARCHIVE_MAP,
           CLIPSegConfig,
           CLIPSegTextConfig,
           CLIPSegVisionConfig,
       )
       from .processing_clipseg import CLIPSegProcessor

       try:
              if not is_torch_available():
                     raise OptionalDependencyNotAvailable()
       except OptionalDependencyNotAvailable:
              pass
       else:
              from .modeling_clipseg import (
                  CLIPSEG_PRETRAINED_MODEL_ARCHIVE_LIST,
                  CLIPSegForImageSegmentation,
                  CLIPSegModel,
                  CLIPSegPreTrainedModel,
                  CLIPSegTextModel,
                  CLIPSegVisionModel,
              )

else:
       import sys

       _lowerCamelCase      							=   _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)

