


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





     def __init__( self       :      Union[str, Any]    ,      UpperCAmelCase__       :      List[str]    ,      UpperCAmelCase__       :      Optional[int]=1_3    ,      UpperCAmelCase__       :      Optional[int]=3_0    ,      UpperCAmelCase__       :      Dict=2    ,      UpperCAmelCase__       :      Dict=3    ,      UpperCAmelCase__       :      Any=True    ,      UpperCAmelCase__       :      List[str]=True    ,      UpperCAmelCase__       :      str=3_2    ,      UpperCAmelCase__       :      List[str]=5    ,      UpperCAmelCase__       :      Optional[int]=4    ,      UpperCAmelCase__       :      List[str]=3_7    ,      UpperCAmelCase__       :      Dict="gelu"    ,      UpperCAmelCase__       :      str=0.1    ,      UpperCAmelCase__       :      List[Any]=0.1    ,      UpperCAmelCase__       :      Tuple=1_0    ,      UpperCAmelCase__       :      int=0.02    ,      UpperCAmelCase__       :      Union[str, Any]=None    ,      UpperCAmelCase__       :      Tuple=2    ,      )				->  Tuple:
        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 							__UpperCAmelCase      ( self       :      Optional[int]    )				->  Union[str, Any]:
        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 							__UpperCAmelCase      ( self       :      Tuple    )				->  Optional[int]:
        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 							__UpperCAmelCase      ( self       :      Optional[int]    ,      UpperCAmelCase__       :      Union[str, Any]    ,      UpperCAmelCase__       :      Dict    ,      UpperCAmelCase__       :      int    )				->  Optional[Any]:
        lowerCAmelCase     =			ViTModel(config=UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()
        lowerCAmelCase     =			model(UpperCAmelCase__    )
        self.parent.assertEqual(result.last_hidden_state.shape    ,      (self.batch_size, self.seq_length, self.hidden_size)    )





     def 							__UpperCAmelCase      ( self       :      Any    ,      UpperCAmelCase__       :      Optional[int]    ,      UpperCAmelCase__       :      List[str]    ,      UpperCAmelCase__       :      List[Any]    )				->  Union[str, Any]:
        lowerCAmelCase     =			ViTForMaskedImageModeling(config=UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()
        lowerCAmelCase     =			model(UpperCAmelCase__    )
        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(UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()

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





     def 							__UpperCAmelCase      ( self       :      Optional[Any]    ,      UpperCAmelCase__       :      Tuple    ,      UpperCAmelCase__       :      List[str]    ,      UpperCAmelCase__       :      str    )				->  Tuple:
        lowerCAmelCase     =			self.type_sequence_label_size
        lowerCAmelCase     =			ViTForImageClassification(UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()
        lowerCAmelCase     =			model(UpperCAmelCase__    ,      labels=UpperCAmelCase__    )
        self.parent.assertEqual(result.logits.shape    ,      (self.batch_size, self.type_sequence_label_size)    )

        # test greyscale images
        lowerCAmelCase     =			1
        lowerCAmelCase     =			ViTForImageClassification(UpperCAmelCase__    )
        model.to(UpperCAmelCase__    )
        model.eval()

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





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




@require_torch
class 		UpperCAmelCase_      (  __lowercase       ,	__lowercase       ,	unittest.TestCase		):
     lowerCamelCase				:	Optional[Any]		=     (
         (
             ViTModel,
             ViTForImageClassification,
             ViTForMaskedImageModeling,
         )
         if is_torch_available()
         else ()
     )
     lowerCamelCase				:	Union[str, Any]		=     (
         {'''feature-extraction''': ViTModel, '''image-classification''': ViTForImageClassification}
         if is_torch_available()
         else {}
     )
     lowerCamelCase				:	int		=     True

     lowerCamelCase				:	str		=     False
     lowerCamelCase				:	List[str]		=     False
     lowerCamelCase				:	Optional[int]		=     False





     def 							__UpperCAmelCase      ( self       :      Optional[Any]    )				->  List[str]:
        lowerCAmelCase     =			ViTModelTester(self    )
        lowerCAmelCase     =			ConfigTester(self    ,      config_class=UpperCAmelCase__    ,      has_text_modality=UpperCAmelCase__    ,      hidden_size=3_7    )





     def 							__UpperCAmelCase      ( self       :      str    )				->  str:
        self.config_tester.run_common_tests()





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





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

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





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

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





     def 							__UpperCAmelCase      ( self       :      int    )				->  Any:
        lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*UpperCAmelCase__    )





     def 							__UpperCAmelCase      ( self       :      Any    )				->  Any:
        lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_masked_image_modeling(*UpperCAmelCase__    )





     def 							__UpperCAmelCase      ( self       :      Optional[Any]    )				->  Tuple:
        lowerCAmelCase     =			self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase__    )





     @slow
     def 							__UpperCAmelCase      ( self       :      List[str]    )				->  Optional[int]:
        for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           lowerCAmelCase     =			ViTModel.from_pretrained(UpperCAmelCase__    )
           self.assertIsNotNone(UpperCAmelCase__    )





def 	a_					( ):
   lowerCAmelCase     =			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'				)
   return image




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





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





     @slow
     def 							__UpperCAmelCase      ( self       :      Dict    )				->  Union[str, Any]:
        lowerCAmelCase     =			ViTForImageClassification.from_pretrained('google/vit-base-patch16-224'    ).to(UpperCAmelCase__    )

        lowerCAmelCase     =			self.default_image_processor
        lowerCAmelCase     =			prepare_img()
        lowerCAmelCase     =			image_processor(images=UpperCAmelCase__    ,      return_tensors='pt'    ).to(UpperCAmelCase__    )

        # forward pass
        with torch.no_grad():
           lowerCAmelCase     =			model(**UpperCAmelCase__    )

        # verify the logits
        lowerCAmelCase     =			torch.Size((1, 1_0_0_0)    )
        self.assertEqual(outputs.logits.shape    ,      UpperCAmelCase__    )

        lowerCAmelCase     =			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 							__UpperCAmelCase      ( self       :      int    )				->  List[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.
        lowerCAmelCase     =			ViTModel.from_pretrained('facebook/dino-vits8'    ).to(UpperCAmelCase__    )

        lowerCAmelCase     =			ViTImageProcessor.from_pretrained('facebook/dino-vits8'    ,      size=4_8_0    )
        lowerCAmelCase     =			prepare_img()
        lowerCAmelCase     =			image_processor(images=UpperCAmelCase__    ,      return_tensors='pt'    )
        lowerCAmelCase     =			inputs.pixel_values.to(UpperCAmelCase__    )

        # forward pass
        with torch.no_grad():
           lowerCAmelCase     =			model(UpperCAmelCase__    ,      interpolate_pos_encoding=UpperCAmelCase__    )

        # verify the logits
        lowerCAmelCase     =			torch.Size((1, 3_6_0_1, 3_8_4)    )
        self.assertEqual(outputs.last_hidden_state.shape    ,      UpperCAmelCase__    )

        lowerCAmelCase     =			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 							__UpperCAmelCase      ( self       :      Any    )				->  Optional[int]:
        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=UpperCAmelCase__    ,      return_tensors='pt'    )
        lowerCAmelCase     =			inputs.pixel_values.to(UpperCAmelCase__    )

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









'''simple docstring'''




from ...configuration_utils import PretrainedConfig
from ...utils import logging


__snake_case    						=logging.get_logger(__name__)

__snake_case    						={
    """facebook/s2t-wav2vec2-large-en-de""": (
        """https://huggingface.co/facebook/s2t-wav2vec2-large-en-de/resolve/main/config.json"""
    ),
    # See all Speech2Text models at https://huggingface.co/models?filter=speech2text2
}

class 		UpperCAmelCase_      (  __lowercase		):
     lowerCamelCase				:	Union[str, Any]		=     '''speech_to_text_2'''
     lowerCamelCase				:	Any		=     ['''past_key_values''']
     lowerCamelCase				:	Optional[Any]		=     {'''num_attention_heads''': '''decoder_attention_heads''', '''hidden_size''': '''d_model'''}





     def __init__( self       :      Optional[int]    ,      UpperCAmelCase__       :      Optional[Any]=1_0_0_0_0    ,      UpperCAmelCase__       :      int=6    ,      UpperCAmelCase__       :      Optional[Any]=2_0_4_8    ,      UpperCAmelCase__       :      Union[str, Any]=4    ,      UpperCAmelCase__       :      List[Any]=0.0    ,      UpperCAmelCase__       :      str=True    ,      UpperCAmelCase__       :      str="relu"    ,      UpperCAmelCase__       :      Any=2_5_6    ,      UpperCAmelCase__       :      Optional[Any]=0.1    ,      UpperCAmelCase__       :      Any=0.0    ,      UpperCAmelCase__       :      Tuple=0.0    ,      UpperCAmelCase__       :      List[Any]=0.02    ,      UpperCAmelCase__       :      List[Any]=2    ,      UpperCAmelCase__       :      str=True    ,      UpperCAmelCase__       :      List[str]=1    ,      UpperCAmelCase__       :      Any=0    ,      UpperCAmelCase__       :      Dict=2    ,      UpperCAmelCase__       :      int=1_0_2_4    ,      **UpperCAmelCase__       :      Optional[Any]    ,      )				->  Dict:
        lowerCAmelCase     =			vocab_size
        lowerCAmelCase     =			d_model
        lowerCAmelCase     =			decoder_ffn_dim
        lowerCAmelCase     =			decoder_layers
        lowerCAmelCase     =			decoder_attention_heads
        lowerCAmelCase     =			dropout
        lowerCAmelCase     =			attention_dropout
        lowerCAmelCase     =			activation_dropout
        lowerCAmelCase     =			activation_function
        lowerCAmelCase     =			init_std
        lowerCAmelCase     =			decoder_layerdrop
        lowerCAmelCase     =			use_cache
        lowerCAmelCase     =			decoder_layers
        lowerCAmelCase     =			scale_embedding  # scale factor will be sqrt(d_model) if True
        lowerCAmelCase     =			max_target_positions

        super().__init__(
            pad_token_id=UpperCAmelCase__    ,      bos_token_id=UpperCAmelCase__    ,      eos_token_id=UpperCAmelCase__    ,      decoder_start_token_id=UpperCAmelCase__    ,      **UpperCAmelCase__    ,      )





