

"""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      __a							:






     '''simple docstring'''

     def __init__(						self	,    _a	,    _a=13	,    _a=30	,    _a=2	,    _a=3	,    _a=True	,    _a=True	,    _a=32	,    _a=5	,    _a=4	,    _a=37	,    _a="gelu"	,    _a=0.1	,    _a=0.1	,    _a=10	,    _a=0.02	,    _a=None	,    _a=2	,    )  ->      Optional[Any]:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      int      		=	parent
           SCREAMING_SNAKE_CASE__   :      List[str]      		=	batch_size
           SCREAMING_SNAKE_CASE__   :      Tuple      		=	image_size
           SCREAMING_SNAKE_CASE__   :      List[Any]      		=	patch_size
           SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	num_channels
           SCREAMING_SNAKE_CASE__   :      Dict      		=	is_training
           SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	use_labels
           SCREAMING_SNAKE_CASE__   :      Dict      		=	hidden_size
           SCREAMING_SNAKE_CASE__   :      int      		=	num_hidden_layers
           SCREAMING_SNAKE_CASE__   :      List[str]      		=	num_attention_heads
           SCREAMING_SNAKE_CASE__   :      List[str]      		=	intermediate_size
           SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	hidden_act
           SCREAMING_SNAKE_CASE__   :      int      		=	hidden_dropout_prob
           SCREAMING_SNAKE_CASE__   :      int      		=	attention_probs_dropout_prob
           SCREAMING_SNAKE_CASE__   :      Any      		=	type_sequence_label_size
           SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	initializer_range
           SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	scope
           SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	encoder_stride

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

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


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      Dict      		=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

           SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	None
           if self.use_labels:
                 SCREAMING_SNAKE_CASE__   :      Any      		=	ids_tensor([self.batch_size]	,    self.type_sequence_label_size  )

           SCREAMING_SNAKE_CASE__   :      Any      		=	self.get_config()

           return config, pixel_values, labels

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


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

     def 					_a			(						self	,    _a	,    _a	,    _a  )  ->      Optional[Any]:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	ViTModel(config=__UpperCamelCase  )
           model.to(__UpperCamelCase  )
           model.eval()
           SCREAMING_SNAKE_CASE__   :      Any      		=	model(__UpperCamelCase  )
           self.parent.assertEqual(result.last_hidden_state.shape	,    (self.batch_size, self.seq_length, self.hidden_size)  )

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


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      Tuple      		=	ViTForMaskedImageModeling(config=__UpperCamelCase  )
           model.to(__UpperCamelCase  )
           model.eval()
           SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	model(__UpperCamelCase  )
           self.parent.assertEqual(
               result.reconstruction.shape	,    (self.batch_size, self.num_channels, self.image_size, self.image_size)  )

           # test greyscale images
           SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	1
           SCREAMING_SNAKE_CASE__   :      Dict      		=	ViTForMaskedImageModeling(__UpperCamelCase  )
           model.to(__UpperCamelCase  )
           model.eval()

           SCREAMING_SNAKE_CASE__   :      str      		=	floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
           SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	model(__UpperCamelCase  )
           self.parent.assertEqual(result.reconstruction.shape	,    (self.batch_size, 1, self.image_size, self.image_size)  )

     def 					_a			(						self	,    _a	,    _a	,    _a  )  ->      Dict:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      int      		=	self.type_sequence_label_size
           SCREAMING_SNAKE_CASE__   :      List[Any]      		=	ViTForImageClassification(__UpperCamelCase  )
           model.to(__UpperCamelCase  )
           model.eval()
           SCREAMING_SNAKE_CASE__   :      Dict      		=	model(__UpperCamelCase	,    labels=__UpperCamelCase  )
           self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.type_sequence_label_size)  )

           # test greyscale images
           SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	1
           SCREAMING_SNAKE_CASE__   :      Any      		=	ViTForImageClassification(__UpperCamelCase  )
           model.to(__UpperCamelCase  )
           model.eval()

           SCREAMING_SNAKE_CASE__   :      str      		=	floats_tensor([self.batch_size, 1, self.image_size, self.image_size]  )
           SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	model(__UpperCamelCase  )
           self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.type_sequence_label_size)  )





     def 					_a			(						self  )  ->      Dict:


           """simple docstring"""


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





@require_torch
class      __a							(UpperCamelCase_   ,	UpperCamelCase_   ,	unittest.TestCase):






     '''simple docstring'''
     _SCREAMING_SNAKE_CASE						:int       = (
         (
             ViTModel,
             ViTForImageClassification,
             ViTForMaskedImageModeling,
         )
         if is_torch_available()
         else ()
     )
     _SCREAMING_SNAKE_CASE						:int       = (
         {"""feature-extraction""": ViTModel, """image-classification""": ViTForImageClassification}
         if is_torch_available()
         else {}
     )
     _SCREAMING_SNAKE_CASE						:int       = True

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

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


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      Dict      		=	ViTModelTester(self  )
           SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	ConfigTester(self	,    config_class=__UpperCamelCase	,    has_text_modality=__UpperCamelCase	,    hidden_size=37  )

     def 					_a			(						self  )  ->      str:


           """simple docstring"""


           self.config_tester.run_common_tests()

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


           """simple docstring"""


           pass

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


           """simple docstring"""


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

           for model_class in self.all_model_classes:
                 SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	model_class(__UpperCamelCase  )
                 self.assertIsInstance(model.get_input_embeddings()	,    (nn.Module)  )
                 SCREAMING_SNAKE_CASE__   :      int      		=	model.get_output_embeddings()
                 self.assertTrue(x is None or isinstance(__UpperCamelCase	,    nn.Linear  )  )

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


           """simple docstring"""


           SCREAMING_SNAKE_CASE__		,		SCREAMING_SNAKE_CASE__   :      str      		=	self.model_tester.prepare_config_and_inputs_for_common()

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

                 SCREAMING_SNAKE_CASE__   :      Dict      		=	["""pixel_values"""]
                 self.assertListEqual(arg_names[:1]	,    __UpperCamelCase  )

     def 					_a			(						self  )  ->      Dict:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      str      		=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*__UpperCamelCase  )

     def 					_a			(						self  )  ->      str:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      Any      		=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_masked_image_modeling(*__UpperCamelCase  )

     def 					_a			(						self  )  ->      Tuple:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      Tuple      		=	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*__UpperCamelCase  )





     @slow
     def 					_a			(						self  )  ->      Tuple:


           """simple docstring"""


           for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 SCREAMING_SNAKE_CASE__   :      Dict      		=	ViTModel.from_pretrained(__UpperCamelCase  )
                 self.assertIsNotNone(__UpperCamelCase  )





def  _lowercase					(    )       ->				Dict:
      SCREAMING_SNAKE_CASE__   :      List[str]      		=	Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							)
      return image



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






     '''simple docstring'''

     @cached_property
     def 					_a			(						self  )  ->      Any:


           """simple docstring"""


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

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


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      Tuple      		=	ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224"""  ).to(__UpperCamelCase  )

           SCREAMING_SNAKE_CASE__   :      Any      		=	self.default_image_processor
           SCREAMING_SNAKE_CASE__   :      Any      		=	prepare_img()
           SCREAMING_SNAKE_CASE__   :      Any      		=	image_processor(images=__UpperCamelCase	,    return_tensors="""pt"""  ).to(__UpperCamelCase  )

           # forward pass
           with torch.no_grad():
                 SCREAMING_SNAKE_CASE__   :      int      		=	model(**__UpperCamelCase  )

           # verify the logits
           SCREAMING_SNAKE_CASE__   :      Tuple      		=	torch.Size((1, 1_000)  )
           self.assertEqual(outputs.logits.shape	,    __UpperCamelCase  )

           SCREAMING_SNAKE_CASE__   :      List[Any]      		=	torch.tensor([-0.2_744, 0.8_215, -0.0_836]  ).to(__UpperCamelCase  )

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

     @slow
     def 					_a			(						self  )  ->      int:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      List[str]      		=	ViTModel.from_pretrained("""facebook/dino-vits8"""  ).to(__UpperCamelCase  )

           SCREAMING_SNAKE_CASE__   :      List[Any]      		=	ViTImageProcessor.from_pretrained("""facebook/dino-vits8"""	,    size=480  )
           SCREAMING_SNAKE_CASE__   :      List[str]      		=	prepare_img()
           SCREAMING_SNAKE_CASE__   :      Dict      		=	image_processor(images=__UpperCamelCase	,    return_tensors="""pt"""  )
           SCREAMING_SNAKE_CASE__   :      Dict      		=	inputs.pixel_values.to(__UpperCamelCase  )

           # forward pass
           with torch.no_grad():
                 SCREAMING_SNAKE_CASE__   :      List[str]      		=	model(__UpperCamelCase	,    interpolate_pos_encoding=__UpperCamelCase  )

           # verify the logits
           SCREAMING_SNAKE_CASE__   :      Dict      		=	torch.Size((1, 3_601, 384)  )
           self.assertEqual(outputs.last_hidden_state.shape	,    __UpperCamelCase  )

           SCREAMING_SNAKE_CASE__   :      int      		=	torch.tensor(
               [[4.2_340, 4.3_906, -6.6_692], [4.5_463, 1.8_928, -6.7_257], [4.4_429, 0.8_496, -5.8_585]]  ).to(__UpperCamelCase  )

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





     @slow
     @require_accelerate
     @require_torch_gpu
     def 					_a			(						self  )  ->      Dict:


           """simple docstring"""


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

           SCREAMING_SNAKE_CASE__   :      str      		=	prepare_img()
           SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	image_processor(images=__UpperCamelCase	,    return_tensors="""pt"""  )
           SCREAMING_SNAKE_CASE__   :      Tuple      		=	inputs.pixel_values.to(__UpperCamelCase  )

           # forward pass to make sure inference works in fp16
           with torch.no_grad():
                 SCREAMING_SNAKE_CASE__   :      Tuple      		=	model(__UpperCamelCase  )





"""simple docstring"""


class      __a							:






     '''simple docstring'''

     def __init__(						self	,    _a	,    _a	,    _a  )  ->      str:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      Any      		=	name
           SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	value
           SCREAMING_SNAKE_CASE__   :      List[Any]      		=	weight

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


           """simple docstring"""


           return f'''{self.__class__.__name__}({self.name}, {self.value}, {self.weight})'''

     def 					_a			(						self  )  ->      Dict:


           """simple docstring"""


           return self.value

     def 					_a			(						self  )  ->      int:


           """simple docstring"""


           return self.name

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


           """simple docstring"""


           return self.weight





     def 					_a			(						self  )  ->      Dict:


           """simple docstring"""


           return self.value / self.weight





def  _lowercase					(    __lowerCAmelCase  ,					__lowerCAmelCase  ,					__lowerCAmelCase							)       ->				Dict:
      SCREAMING_SNAKE_CASE__   :      Any      		=	[]
      for i in range(len(__lowerCAmelCase							)							):
            menu.append(Things(name[i]  ,					value[i]  ,					weight[i]							)							)
      return menu




def  _lowercase					(    __lowerCAmelCase  ,					__lowerCAmelCase  ,					__lowerCAmelCase							)       ->				Union[str, Any]:
      SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	sorted(__lowerCAmelCase  ,					key=__lowerCAmelCase  ,					reverse=__lowerCAmelCase							)
      SCREAMING_SNAKE_CASE__   :      str      		=	[]
      SCREAMING_SNAKE_CASE__		,		SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	0.0, 0.0
      for i in range(len(__lowerCAmelCase							)							):
            if (total_cost + items_copy[i].get_weight()) <= max_cost:
                  result.append(items_copy[i]							)
                  total_cost += items_copy[i].get_weight()
                  total_value += items_copy[i].get_value()
      return (result, total_value)




def  _lowercase					(    )       ->				List[str]:
      pass


if __name__ == "__main__":
  import doctest

  doctest.testmod()




