






'''simple docstring'''





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 				lowercase       :


    '''simple docstring'''

    def __init__(					self     :     Dict				,     __lowerCamelCase     :     int				,     __lowerCamelCase     :     Dict=13				,     __lowerCamelCase     :     int=30				,     __lowerCamelCase     :     Union[str, Any]=2				,     __lowerCamelCase     :     List[str]=3				,     __lowerCamelCase     :     Optional[Any]=True				,     __lowerCamelCase     :     List[str]=True				,     __lowerCamelCase     :     Optional[Any]=32				,     __lowerCamelCase     :     Optional[Any]=5				,     __lowerCamelCase     :     List[str]=4				,     __lowerCamelCase     :     List[str]=37				,     __lowerCamelCase     :     str="gelu"				,     __lowerCamelCase     :     Union[str, Any]=0.1				,     __lowerCamelCase     :     int=0.1				,     __lowerCamelCase     :     List[Any]=10				,     __lowerCamelCase     :     Union[str, Any]=0.0_2				,     __lowerCamelCase     :     Optional[Any]=None				,     __lowerCamelCase     :     Union[str, Any]=2				,     )							->							str:

     '''simple docstring'''




     lowerCamelCase__  =     parent
     lowerCamelCase__  =     batch_size
     lowerCamelCase__  =     image_size
     lowerCamelCase__  =     patch_size
     lowerCamelCase__  =     num_channels
     lowerCamelCase__  =     is_training
     lowerCamelCase__  =     use_labels
     lowerCamelCase__  =     hidden_size
     lowerCamelCase__  =     num_hidden_layers
     lowerCamelCase__  =     num_attention_heads
     lowerCamelCase__  =     intermediate_size
     lowerCamelCase__  =     hidden_act
     lowerCamelCase__  =     hidden_dropout_prob
     lowerCamelCase__  =     attention_probs_dropout_prob
     lowerCamelCase__  =     type_sequence_label_size
     lowerCamelCase__  =     initializer_range
     lowerCamelCase__  =     scope
     lowerCamelCase__  =     encoder_stride

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

    def    a__				(					self     :     Optional[int]     )							->							List[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]     )

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

     lowerCamelCase__  =     self.get_config()

     return config, pixel_values, labels

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

     '''simple docstring'''




     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=__lowerCamelCase				,     initializer_range=self.initializer_range				,     encoder_stride=self.encoder_stride				,     )

    def    a__				(					self     :     Union[str, Any]				,     __lowerCamelCase     :     List[Any]				,     __lowerCamelCase     :     List[Any]				,     __lowerCamelCase     :     List[str]     )							->							str:

     '''simple docstring'''




     lowerCamelCase__  =     ViTModel(config=__lowerCamelCase     )
     model.to(__lowerCamelCase     )
     model.eval()
     lowerCamelCase__  =     model(__lowerCamelCase     )
     self.parent.assertEqual(result.last_hidden_state.shape				,     (self.batch_size, self.seq_length, self.hidden_size)     )

    def    a__				(					self     :     int				,     __lowerCamelCase     :     Optional[int]				,     __lowerCamelCase     :     Optional[int]				,     __lowerCamelCase     :     List[Any]     )							->							Optional[int]:

     '''simple docstring'''




     lowerCamelCase__  =     ViTForMaskedImageModeling(config=__lowerCamelCase     )
     model.to(__lowerCamelCase     )
     model.eval()
     lowerCamelCase__  =     model(__lowerCamelCase     )
     self.parent.assertEqual(
         result.reconstruction.shape				,     (self.batch_size, self.num_channels, self.image_size, self.image_size)     )

     # test greyscale images
     lowerCamelCase__  =     1
     lowerCamelCase__  =     ViTForMaskedImageModeling(__lowerCamelCase     )
     model.to(__lowerCamelCase     )
     model.eval()

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

    def    a__				(					self     :     Any				,     __lowerCamelCase     :     Dict				,     __lowerCamelCase     :     Union[str, Any]				,     __lowerCamelCase     :     int     )							->							Tuple:

     '''simple docstring'''




     lowerCamelCase__  =     self.type_sequence_label_size
     lowerCamelCase__  =     ViTForImageClassification(__lowerCamelCase     )
     model.to(__lowerCamelCase     )
     model.eval()
     lowerCamelCase__  =     model(__lowerCamelCase				,     labels=__lowerCamelCase     )
     self.parent.assertEqual(result.logits.shape				,     (self.batch_size, self.type_sequence_label_size)     )

     # test greyscale images
     lowerCamelCase__  =     1
     lowerCamelCase__  =     ViTForImageClassification(__lowerCamelCase     )
     model.to(__lowerCamelCase     )
     model.eval()

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




    def    a__				(					self     :     List[str]     )							->							Any:

     '''simple docstring'''




     lowerCamelCase__  =     self.prepare_config_and_inputs()
     (
         (
         lowerCamelCase__
     )  ,	(
         lowerCamelCase__
     )  ,	(
         lowerCamelCase__
     )  ,	
     )  =     config_and_inputs
     lowerCamelCase__  =     {"pixel_values": pixel_values}
     return config, inputs_dict
@require_torch
class 				lowercase       (							_lowerCamelCase ,       _lowerCamelCase ,       unittest.TestCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							(
        (
            ViTModel,
            ViTForImageClassification,
            ViTForMaskedImageModeling,
        )
        if is_torch_available()
        else ()
    )
    lowerCAmelCase__      				=							(
        {"feature-extraction": ViTModel, "image-classification": ViTForImageClassification}
        if is_torch_available()
        else {}
    )
    lowerCAmelCase__      				=							True

    lowerCAmelCase__      				=							False
    lowerCAmelCase__      				=							False
    lowerCAmelCase__      				=							False

    def    a__				(					self     :     List[str]     )							->							Optional[int]:

     '''simple docstring'''




     lowerCamelCase__  =     ViTModelTester(self     )
     lowerCamelCase__  =     ConfigTester(self				,     config_class=__lowerCamelCase				,     has_text_modality=__lowerCamelCase				,     hidden_size=37     )

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

     '''simple docstring'''




     self.config_tester.run_common_tests()

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

     '''simple docstring'''




     pass

    def    a__				(					self     :     Tuple     )							->							int:

     '''simple docstring'''




     lowerCamelCase__  ,	lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs_for_common()

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

    def    a__				(					self     :     Tuple     )							->							str:

     '''simple docstring'''




     lowerCamelCase__  ,	lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs_for_common()

     for model_class in self.all_model_classes:
      lowerCamelCase__  =     model_class(__lowerCamelCase     )
      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]				,     __lowerCamelCase     )

    def    a__				(					self     :     Union[str, Any]     )							->							Optional[int]:

     '''simple docstring'''




     lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*__lowerCamelCase     )

    def    a__				(					self     :     List[Any]     )							->							Optional[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_masked_image_modeling(*__lowerCamelCase     )

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

     '''simple docstring'''




     lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase     )




    @slow
    def    a__				(					self     :     Any     )							->							str:

     '''simple docstring'''




     for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      lowerCamelCase__  =     ViTModel.from_pretrained(__lowerCamelCase     )
      self.assertIsNotNone(__lowerCamelCase     )






def    lowerCamelCase_     (    ):
 lowerCamelCase__  =     Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png")
 return image
@require_torch
@require_vision
class 				lowercase       (							unittest.TestCase      ):


    '''simple docstring'''

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

     '''simple docstring'''




     return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224"     ) if is_vision_available() else None

    @slow
    def    a__				(					self     :     int     )							->							Optional[int]:

     '''simple docstring'''




     lowerCamelCase__  =     ViTForImageClassification.from_pretrained("google/vit-base-patch16-224"     ).to(__lowerCamelCase     )

     lowerCamelCase__  =     self.default_image_processor
     lowerCamelCase__  =     prepare_img()
     lowerCamelCase__  =     image_processor(images=__lowerCamelCase				,     return_tensors="pt"     ).to(__lowerCamelCase     )

     # forward pass
     with torch.no_grad():
      lowerCamelCase__  =     model(**__lowerCamelCase     )

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

     lowerCamelCase__  =     torch.tensor([-0.2_7_4_4, 0.8_2_1_5, -0.0_8_3_6]     ).to(__lowerCamelCase     )

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

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

     '''simple docstring'''




     lowerCamelCase__  =     ViTModel.from_pretrained("facebook/dino-vits8"     ).to(__lowerCamelCase     )

     lowerCamelCase__  =     ViTImageProcessor.from_pretrained("facebook/dino-vits8"				,     size=480     )
     lowerCamelCase__  =     prepare_img()
     lowerCamelCase__  =     image_processor(images=__lowerCamelCase				,     return_tensors="pt"     )
     lowerCamelCase__  =     inputs.pixel_values.to(__lowerCamelCase     )

     # forward pass
     with torch.no_grad():
      lowerCamelCase__  =     model(__lowerCamelCase				,     interpolate_pos_encoding=__lowerCamelCase     )

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

     lowerCamelCase__  =     torch.tensor(
         [[4.2_3_4_0, 4.3_9_0_6, -6.6_6_9_2], [4.5_4_6_3, 1.8_9_2_8, -6.7_2_5_7], [4.4_4_2_9, 0.8_4_9_6, -5.8_5_8_5]]     ).to(__lowerCamelCase     )

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




    @slow
    @require_accelerate
    @require_torch_gpu
    def    a__				(					self     :     Union[str, Any]     )							->							Union[str, Any]:

     '''simple docstring'''




     lowerCamelCase__  =     ViTModel.from_pretrained("facebook/dino-vits8"				,     torch_dtype=torch.floataa				,     device_map="auto"     )
     lowerCamelCase__  =     self.default_image_processor

     lowerCamelCase__  =     prepare_img()
     lowerCamelCase__  =     image_processor(images=__lowerCamelCase				,     return_tensors="pt"     )
     lowerCamelCase__  =     inputs.pixel_values.to(__lowerCamelCase     )

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









'''simple docstring'''





def    lowerCamelCase_     (    lowercase__				,     lowercase__				,     lowercase__):
 return round(float(moles / volume) * nfactor)






def    lowerCamelCase_     (    lowercase__				,     lowercase__				,     lowercase__):
 return round(float((moles * 0.0_821 * temperature) / (volume)))






def    lowerCamelCase_     (    lowercase__				,     lowercase__				,     lowercase__):
 return round(float((moles * 0.0_821 * temperature) / (pressure)))






def    lowerCamelCase_     (    lowercase__				,     lowercase__				,     lowercase__):
 return round(float((pressure * volume) / (0.0_821 * moles)))


if __name__ == "__main__":
 import doctest

 doctest.testmod()

