






'''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 	SCREAMING_SNAKE_CASE	:




       def __init__(					self      : Optional[Any]	,    A__      : List[Any]	,    A__      : Optional[int]=13	,    A__      : Union[str, Any]=30	,    A__      : Optional[Any]=2	,    A__      : Optional[int]=3	,    A__      : Dict=True	,    A__      : Tuple=True	,    A__      : Any=32	,    A__      : List[str]=5	,    A__      : Union[str, Any]=4	,    A__      : Union[str, Any]=37	,    A__      : str="gelu"	,    A__      : str=0.1	,    A__      : int=0.1	,    A__      : Dict=10	,    A__      : str=0.02	,    A__      : Tuple=None	,    A__      : List[str]=2	,    ):


            """simple docstring"""







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

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




       def 					a_					(					self      : Any					):


            """simple docstring"""







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

            __lowerCamelCase						:       Optional[int]				   =				None
            if self.use_labels:
                 __lowerCamelCase						:       str				   =				ids_tensor([self.batch_size]	,    self.type_sequence_label_size					)

            __lowerCamelCase						:       int				   =				self.get_config()

            return config, pixel_values, labels




       def 					a_					(					self      : List[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=_a	,    initializer_range=self.initializer_range	,    encoder_stride=self.encoder_stride	,    )




       def 					a_					(					self      : Dict	,    A__      : Optional[int]	,    A__      : List[Any]	,    A__      : Any					):


            """simple docstring"""







            __lowerCamelCase						:       List[Any]				   =				ViTModel(config=_a					)
            model.to(_a					)
            model.eval()
            __lowerCamelCase						:       Any				   =				model(_a					)
            self.parent.assertEqual(result.last_hidden_state.shape	,    (self.batch_size, self.seq_length, self.hidden_size)					)




       def 					a_					(					self      : List[Any]	,    A__      : List[str]	,    A__      : Any	,    A__      : Optional[int]					):


            """simple docstring"""







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

            # test greyscale images
            __lowerCamelCase						:       Any				   =				1
            __lowerCamelCase						:       List[str]				   =				ViTForMaskedImageModeling(_a					)
            model.to(_a					)
            model.eval()

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




       def 					a_					(					self      : List[Any]	,    A__      : str	,    A__      : Optional[int]	,    A__      : Dict					):


            """simple docstring"""







            __lowerCamelCase						:       int				   =				self.type_sequence_label_size
            __lowerCamelCase						:       Any				   =				ViTForImageClassification(_a					)
            model.to(_a					)
            model.eval()
            __lowerCamelCase						:       Any				   =				model(_a	,    labels=_a					)
            self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.type_sequence_label_size)					)

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

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




       def 					a_					(					self      : Optional[int]					):


            """simple docstring"""







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







@require_torch
class 	SCREAMING_SNAKE_CASE	(      __SCREAMING_SNAKE_CASE    ,   __SCREAMING_SNAKE_CASE    ,   unittest.TestCase  ):
       snake_case__    :     Optional[int]   		=			(
           (
               ViTModel,
               ViTForImageClassification,
               ViTForMaskedImageModeling,
           )
           if is_torch_available()
           else ()
       )
       snake_case__    :     List[Any]   		=			(
           {'feature-extraction': ViTModel, 'image-classification': ViTForImageClassification}
           if is_torch_available()
           else {}
       )
       snake_case__    :     int   		=			True

       snake_case__    :     Dict   		=			False
       snake_case__    :     List[str]   		=			False
       snake_case__    :     Any   		=			False




       def 					a_					(					self      : int					):


            """simple docstring"""







            __lowerCamelCase						:       Optional[Any]				   =				ViTModelTester(self					)
            __lowerCamelCase						:       List[Any]				   =				ConfigTester(self	,    config_class=_a	,    has_text_modality=_a	,    hidden_size=37					)




       def 					a_					(					self      : Union[str, Any]					):


            """simple docstring"""







            self.config_tester.run_common_tests()




       @unittest.skip(reason="""ViT does not use inputs_embeds"""					)
       def 					a_					(					self      : int					):


            """simple docstring"""







            pass




       def 					a_					(					self      : int					):


            """simple docstring"""







            __lowerCamelCase						:       Dict				   =				self.model_tester.prepare_config_and_inputs_for_common()

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




       def 					a_					(					self      : Optional[Any]					):


            """simple docstring"""







            __lowerCamelCase						:       Dict				   =				self.model_tester.prepare_config_and_inputs_for_common()

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

                 __lowerCamelCase						:       Optional[int]				   =				["""pixel_values"""]
                 self.assertListEqual(arg_names[:1]	,    _a					)




       def 					a_					(					self      : Optional[int]					):


            """simple docstring"""







            __lowerCamelCase						:       int				   =				self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*_a					)




       def 					a_					(					self      : Union[str, Any]					):


            """simple docstring"""







            __lowerCamelCase						:       List[Any]				   =				self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_masked_image_modeling(*_a					)




       def 					a_					(					self      : str					):


            """simple docstring"""







            __lowerCamelCase						:       Union[str, Any]				   =				self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*_a					)




       @slow
       def 					a_					(					self      : Optional[Any]					):


            """simple docstring"""







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

def     __lowercase  ()   ->     List[str]:


     """simple docstring"""
     __lowerCamelCase						:       List[str]				   =				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""     )
     return image







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




       @cached_property
       def 					a_					(					self      : Optional[int]					):


            """simple docstring"""







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




       @slow
       def 					a_					(					self      : str					):


            """simple docstring"""







            __lowerCamelCase						:       Optional[int]				   =				ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224"""					).to(_a					)

            __lowerCamelCase						:       str				   =				self.default_image_processor
            __lowerCamelCase						:       Union[str, Any]				   =				prepare_img()
            __lowerCamelCase						:       int				   =				image_processor(images=_a	,    return_tensors="""pt"""					).to(_a					)

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

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

            __lowerCamelCase						:       List[Any]				   =				torch.tensor([-0.2744, 0.8215, -0.0836]					).to(_a					)

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




       @slow
       def 					a_					(					self      : List[str]					):


            """simple docstring"""







            __lowerCamelCase						:       List[Any]				   =				ViTModel.from_pretrained("""facebook/dino-vits8"""					).to(_a					)

            __lowerCamelCase						:       Tuple				   =				ViTImageProcessor.from_pretrained("""facebook/dino-vits8"""	,    size=480					)
            __lowerCamelCase						:       int				   =				prepare_img()
            __lowerCamelCase						:       Optional[int]				   =				image_processor(images=_a	,    return_tensors="""pt"""					)
            __lowerCamelCase						:       Optional[int]				   =				inputs.pixel_values.to(_a					)

            # forward pass
            with torch.no_grad():
                 __lowerCamelCase						:       Union[str, Any]				   =				model(_a	,    interpolate_pos_encoding=_a					)

            # verify the logits
            __lowerCamelCase						:       Union[str, Any]				   =				torch.Size((1, 3601, 384)					)
            self.assertEqual(outputs.last_hidden_state.shape	,    _a					)

            __lowerCamelCase						:       Optional[Any]				   =				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 					a_					(					self      : Tuple					):


            """simple docstring"""







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

            __lowerCamelCase						:       Optional[Any]				   =				prepare_img()
            __lowerCamelCase						:       str				   =				image_processor(images=_a	,    return_tensors="""pt"""					)
            __lowerCamelCase						:       Optional[int]				   =				inputs.pixel_values.to(_a					)

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











'''simple docstring'''

UpperCAmelCase__						:List[Any]          =			256
# Modulus to hash a string
UpperCAmelCase__						:str          =			1_000_003
def     __lowercase  (_lowercase,						_lowercase     )   ->     bool:


     """simple docstring"""
     __lowerCamelCase						:       str				   =				len(_lowercase     )
     __lowerCamelCase						:       List[str]				   =				len(_lowercase     )
     if p_len > t_len:
          return False

     __lowerCamelCase						:       Optional[Any]				   =				0
     __lowerCamelCase						:       Tuple				   =				0
     __lowerCamelCase						:       Dict				   =				1

     # Calculating the hash of pattern and substring of text
     for i in range(_lowercase     ):
          __lowerCamelCase						:       Optional[int]				   =				(ord(pattern[i]     ) + p_hash * alphabet_size) % modulus
          __lowerCamelCase						:       Dict				   =				(ord(text[i]     ) + text_hash * alphabet_size) % modulus
          if i == p_len - 1:
               continue
          __lowerCamelCase						:       Dict				   =				(modulus_power * alphabet_size) % modulus

     for i in range(0,						t_len - p_len + 1     ):
          if text_hash == p_hash and text[i : i + p_len] == pattern:
               return True
          if i == t_len - p_len:
               continue
          # Calculate the https://en.wikipedia.org/wiki/Rolling_hash
          __lowerCamelCase						:       Dict				   =				(
              (text_hash - ord(text[i]     ) * modulus_power) * alphabet_size
              + ord(text[i + p_len]     )
          ) % modulus
     return False
def     __lowercase  ()   ->     None:


     """simple docstring"""
     __lowerCamelCase						:       List[Any]				   =				"""abc1abc12"""
     __lowerCamelCase						:       Optional[Any]				   =				"""alskfjaldsabc1abc1abc12k23adsfabcabc"""
     __lowerCamelCase						:       List[Any]				   =				"""alskfjaldsk23adsfabcabc"""
     assert rabin_karp(_lowercase,						_lowercase     ) and not rabin_karp(_lowercase,						_lowercase     )

     # Test 2)
     __lowerCamelCase						:       Optional[int]				   =				"""ABABX"""
     __lowerCamelCase						:       Dict				   =				"""ABABZABABYABABX"""
     assert rabin_karp(_lowercase,						_lowercase     )

     # Test 3)
     __lowerCamelCase						:       Any				   =				"""AAAB"""
     __lowerCamelCase						:       int				   =				"""ABAAAAAB"""
     assert rabin_karp(_lowercase,						_lowercase     )

     # Test 4)
     __lowerCamelCase						:       Any				   =				"""abcdabcy"""
     __lowerCamelCase						:       Dict				   =				"""abcxabcdabxabcdabcdabcy"""
     assert rabin_karp(_lowercase,						_lowercase     )

     # Test 5)
     __lowerCamelCase						:       str				   =				"""Lü"""
     __lowerCamelCase						:       str				   =				"""Lüsai"""
     assert rabin_karp(_lowercase,						_lowercase     )
     __lowerCamelCase						:       Tuple				   =				"""Lue"""
     assert not rabin_karp(_lowercase,						_lowercase     )
     print("""Success."""     )


if __name__ == "__main__":
   test_rabin_karp()



