

import enum
import warnings

from .. import MODEL_FOR_CAUSAL_LM_MAPPING, TF_MODEL_FOR_CAUSAL_LM_MAPPING
from ..utils import add_end_docstrings, is_tf_available
from .base import PIPELINE_INIT_ARGS, Pipeline


if is_tf_available():
						import tensorflow as tf



class   __lowercase				( enum.Enum	):




			"""simple docstring"""







			_UpperCAmelCase   :							Optional[Any]										=     0
			_UpperCAmelCase   :							Any										=     1
			_UpperCAmelCase   :							str										=     2







@add_end_docstrings(UpperCAmelCase_	)
class   __lowercase				( UpperCAmelCase_	):




			"""simple docstring"""







			_UpperCAmelCase   :							Any										=     '''
    In 1991, the remains of Russian Tsar Nicholas II and his family (except for Alexei and Maria) are discovered. The
    voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the remainder of the story. 1883 Western
    Siberia, a young Grigori Rasputin is asked by his father and a group of men to perform magic. Rasputin has a vision
    and denounces one of the men as a horse thief. Although his father initially slaps him for making such an
    accusation, Rasputin watches as the man is chased outside and beaten. Twenty years later, Rasputin sees a vision of
    the Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous, with people, even a bishop,
    begging for his blessing. <eod> </s> <eos>
    '''



			def __init__( self  :     Dict   ,						*lowerCAmelCase__  :     Dict   ,						**lowerCAmelCase__  :     Any):
									super().__init__(*lowerCAmelCase__   ,						**lowerCAmelCase__)
									self.check_model_type(
									    TF_MODEL_FOR_CAUSAL_LM_MAPPING if self.framework == "tf" else MODEL_FOR_CAUSAL_LM_MAPPING)
									if "prefix" not in self._preprocess_params:
															# This is very specific. The logic is quite complex and needs to be done
															# as a "default".
															# It also defines both some preprocess_kwargs and generate_kwargs
															# which is why we cannot put them in their respective methods.
															SCREAMING_SNAKE_CASE_: Optional[Any]  		=       None
															if self.model.config.prefix is not None:
																					SCREAMING_SNAKE_CASE_: List[Any]  		=       self.model.config.prefix
															if prefix is None and self.model.__class__.__name__ in [
															    "XLNetLMHeadModel",
															    "TransfoXLLMHeadModel",
															    "TFXLNetLMHeadModel",
															    "TFTransfoXLLMHeadModel",
															]:
																					# For XLNet and TransformerXL we add an article to the prompt to give more state to the model.
																					SCREAMING_SNAKE_CASE_: List[Any]  		=       self.XL_PREFIX
															if prefix is not None:
																					# Recalculate some generate_kwargs linked to prefix.
																					SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: List[str]  		=       self._sanitize_parameters(prefix=lowerCAmelCase__   ,						**self._forward_params)
																					SCREAMING_SNAKE_CASE_: int  		=       {**self._preprocess_params, **preprocess_params}
																					SCREAMING_SNAKE_CASE_: List[Any]  		=       {**self._forward_params, **forward_params}



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]   ,						lowerCAmelCase__  :     Optional[Any]=None   ,						lowerCAmelCase__  :     Dict=None   ,						lowerCAmelCase__  :     Any=None   ,						lowerCAmelCase__  :     Any=None   ,						lowerCAmelCase__  :     Tuple=None   ,						lowerCAmelCase__  :     Union[str, Any]=None   ,						lowerCAmelCase__  :     Any=None   ,						lowerCAmelCase__  :     int=None   ,						**lowerCAmelCase__  :     Tuple   ,						):
									SCREAMING_SNAKE_CASE_: str  		=       {}
									if prefix is not None:
															SCREAMING_SNAKE_CASE_: str  		=       prefix
									if prefix:
															SCREAMING_SNAKE_CASE_: str  		=       self.tokenizer(
															    lowerCAmelCase__   ,						padding=lowerCAmelCase__   ,						add_special_tokens=lowerCAmelCase__   ,						return_tensors=self.framework)
															SCREAMING_SNAKE_CASE_: Dict  		=       prefix_inputs["input_ids"].shape[-1]

									if handle_long_generation is not None:
															if handle_long_generation not in {"hole"}:
																					raise ValueError(
																					    F"{handle_long_generation} is not a valid value for `handle_long_generation` parameter expected"
																					    " [None, 'hole']")
															SCREAMING_SNAKE_CASE_: Any  		=       handle_long_generation

									preprocess_params.update(lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       generate_kwargs

									SCREAMING_SNAKE_CASE_: str  		=       {}
									if return_full_text is not None and return_type is None:
															if return_text is not None:
																					raise ValueError("`return_text` is mutually exclusive with `return_full_text`")
															if return_tensors is not None:
																					raise ValueError("`return_full_text` is mutually exclusive with `return_tensors`")
															SCREAMING_SNAKE_CASE_: List[Any]  		=       ReturnType.FULL_TEXT if return_full_text else ReturnType.NEW_TEXT
									if return_tensors is not None and return_type is None:
															if return_text is not None:
																					raise ValueError("`return_text` is mutually exclusive with `return_tensors`")
															SCREAMING_SNAKE_CASE_: Dict  		=       ReturnType.TENSORS
									if return_type is not None:
															SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       return_type
									if clean_up_tokenization_spaces is not None:
															SCREAMING_SNAKE_CASE_: List[Any]  		=       clean_up_tokenization_spaces

									if stop_sequence is not None:
															SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.tokenizer.encode(lowerCAmelCase__   ,						add_special_tokens=lowerCAmelCase__)
															if len(lowerCAmelCase__) > 1:
																					warnings.warn(
																					    "Stopping on a multiple token sequence is not yet supported on transformers. The first token of"
																					    " the stop sequence will be used as the stop sequence string in the interim.")
															SCREAMING_SNAKE_CASE_: Optional[int]  		=       stop_sequence_ids[0]

									return preprocess_params, forward_params, postprocess_params



			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]   ,						*lowerCAmelCase__  :     Dict   ,						**lowerCAmelCase__  :     Any):
									# Parse arguments
									if self.model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
															kwargs.update({"add_space_before_punct_symbol": True})

									return super()._parse_and_tokenize(*lowerCAmelCase__   ,						**lowerCAmelCase__)



			def __call__( self  :     Optional[int]   ,						lowerCAmelCase__  :     List[str]   ,						**lowerCAmelCase__  :     Optional[int]):
									return super().__call__(lowerCAmelCase__   ,						**lowerCAmelCase__)



			def        _SCREAMING_SNAKE_CASE			( self  :     int   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     Dict=""   ,						lowerCAmelCase__  :     Tuple=None   ,						**lowerCAmelCase__  :     List[str]):
									SCREAMING_SNAKE_CASE_: Any  		=       self.tokenizer(
									    prefix + prompt_text   ,						padding=lowerCAmelCase__   ,						add_special_tokens=lowerCAmelCase__   ,						return_tensors=self.framework)
									SCREAMING_SNAKE_CASE_: Dict  		=       prompt_text

									if handle_long_generation == "hole":
															SCREAMING_SNAKE_CASE_: List[Any]  		=       inputs["input_ids"].shape[-1]
															if "max_new_tokens" in generate_kwargs:
																					SCREAMING_SNAKE_CASE_: str  		=       generate_kwargs["max_new_tokens"]
															else:
																					SCREAMING_SNAKE_CASE_: List[Any]  		=       generate_kwargs.get("max_length"   ,						self.model.config.max_length) - cur_len
																					if new_tokens < 0:
																											raise ValueError("We cannot infer how many new tokens are expected")
															if cur_len + new_tokens > self.tokenizer.model_max_length:
																					SCREAMING_SNAKE_CASE_: Any  		=       self.tokenizer.model_max_length - new_tokens
																					if keep_length <= 0:
																											raise ValueError(
																											    "We cannot use `hole` to handle this generation the number of desired tokens exceeds the"
																											    " models max length")

																					SCREAMING_SNAKE_CASE_: Tuple  		=       inputs["input_ids"][:, -keep_length:]
																					if "attention_mask" in inputs:
																											SCREAMING_SNAKE_CASE_: Optional[Any]  		=       inputs["attention_mask"][:, -keep_length:]

									return inputs



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]   ,						lowerCAmelCase__  :     Dict   ,						**lowerCAmelCase__  :     Tuple):
									SCREAMING_SNAKE_CASE_: Dict  		=       model_inputs["input_ids"]
									SCREAMING_SNAKE_CASE_: Tuple  		=       model_inputs.get("attention_mask"   ,						lowerCAmelCase__)
									# Allow empty prompts
									if input_ids.shape[1] == 0:
															SCREAMING_SNAKE_CASE_: Tuple  		=       None
															SCREAMING_SNAKE_CASE_: Any  		=       None
															SCREAMING_SNAKE_CASE_: Tuple  		=       1
									else:
															SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       input_ids.shape[0]
									SCREAMING_SNAKE_CASE_: int  		=       model_inputs.pop("prompt_text")

									# If there is a prefix, we may need to adjust the generation length. Do so without permanently modifying
									# generate_kwargs, as some of the parameterization may come from the initialization of the pipeline.
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       generate_kwargs.pop("prefix_length"   ,						0)
									if prefix_length > 0:
															SCREAMING_SNAKE_CASE_: str  		=       "max_new_tokens" in generate_kwargs or (
															    "generation_config" in generate_kwargs
															    and generate_kwargs["generation_config"].max_new_tokens is not None
															)
															if not has_max_new_tokens:
																					SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       generate_kwargs.get("max_length") or self.model.config.max_length
																					generate_kwargs["max_length"] += prefix_length
															SCREAMING_SNAKE_CASE_: Dict  		=       "min_new_tokens" in generate_kwargs or (
															    "generation_config" in generate_kwargs
															    and generate_kwargs["generation_config"].min_new_tokens is not None
															)
															if not has_min_new_tokens and "min_length" in generate_kwargs:
																					generate_kwargs["min_length"] += prefix_length

        # BS x SL
									SCREAMING_SNAKE_CASE_: Any  		=       self.model.generate(input_ids=lowerCAmelCase__   ,						attention_mask=lowerCAmelCase__   ,						**lowerCAmelCase__)
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       generated_sequence.shape[0]
									if self.framework == "pt":
															SCREAMING_SNAKE_CASE_: int  		=       generated_sequence.reshape(lowerCAmelCase__   ,						out_b // in_b   ,						*generated_sequence.shape[1:])
									elif self.framework == "tf":
															SCREAMING_SNAKE_CASE_: Dict  		=       tf.reshape(lowerCAmelCase__   ,						(in_b, out_b // in_b, *generated_sequence.shape[1:]))
									return {"generated_sequence": generated_sequence, "input_ids": input_ids, "prompt_text": prompt_text}




			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]   ,						lowerCAmelCase__  :     Union[str, Any]   ,						lowerCAmelCase__  :     Optional[int]=ReturnType.FULL_TEXT   ,						lowerCAmelCase__  :     Union[str, Any]=True):
									SCREAMING_SNAKE_CASE_: Any  		=       model_outputs["generated_sequence"][0]
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       model_outputs["input_ids"]
									SCREAMING_SNAKE_CASE_: Dict  		=       model_outputs["prompt_text"]
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       generated_sequence.numpy().tolist()
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       []
									for sequence in generated_sequence:
															if return_type == ReturnType.TENSORS:
																					SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       {"generated_token_ids": sequence}
															elif return_type in {ReturnType.NEW_TEXT, ReturnType.FULL_TEXT}:
																					# Decode text
																					SCREAMING_SNAKE_CASE_: str  		=       self.tokenizer.decode(
																					    lowerCAmelCase__   ,						skip_special_tokens=lowerCAmelCase__   ,						clean_up_tokenization_spaces=lowerCAmelCase__   ,						)

																					# Remove PADDING prompt of the sequence if XLNet or Transfo-XL model is used
																					if input_ids is None:
																											SCREAMING_SNAKE_CASE_: Tuple  		=       0
																					else:
																											SCREAMING_SNAKE_CASE_: str  		=       len(
																											    self.tokenizer.decode(
																											        input_ids[0]   ,						skip_special_tokens=lowerCAmelCase__   ,						clean_up_tokenization_spaces=lowerCAmelCase__   ,						))

																					if return_type == ReturnType.FULL_TEXT:
																											SCREAMING_SNAKE_CASE_: List[str]  		=       prompt_text + text[prompt_length:]
																					else:
																											SCREAMING_SNAKE_CASE_: int  		=       text[prompt_length:]

																					SCREAMING_SNAKE_CASE_: Optional[Any]  		=       {"generated_text": all_text}
															records.append(lowerCAmelCase__)

									return records









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  :     Any   ,						lowerCAmelCase__  :     Union[str, Any]   ,						lowerCAmelCase__  :     Any=13   ,						lowerCAmelCase__  :     Tuple=30   ,						lowerCAmelCase__  :     List[str]=2   ,						lowerCAmelCase__  :     int=3   ,						lowerCAmelCase__  :     Optional[int]=True   ,						lowerCAmelCase__  :     List[str]=True   ,						lowerCAmelCase__  :     str=32   ,						lowerCAmelCase__  :     Any=5   ,						lowerCAmelCase__  :     str=4   ,						lowerCAmelCase__  :     int=37   ,						lowerCAmelCase__  :     Optional[Any]="gelu"   ,						lowerCAmelCase__  :     Optional[int]=0.1   ,						lowerCAmelCase__  :     Dict=0.1   ,						lowerCAmelCase__  :     Tuple=10   ,						lowerCAmelCase__  :     Optional[Any]=0.02   ,						lowerCAmelCase__  :     List[str]=None   ,						lowerCAmelCase__  :     Union[str, Any]=2   ,						):
									SCREAMING_SNAKE_CASE_: str  		=       parent
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       batch_size
									SCREAMING_SNAKE_CASE_: str  		=       image_size
									SCREAMING_SNAKE_CASE_: Tuple  		=       patch_size
									SCREAMING_SNAKE_CASE_: int  		=       num_channels
									SCREAMING_SNAKE_CASE_: List[str]  		=       is_training
									SCREAMING_SNAKE_CASE_: str  		=       use_labels
									SCREAMING_SNAKE_CASE_: int  		=       hidden_size
									SCREAMING_SNAKE_CASE_: List[Any]  		=       num_hidden_layers
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       num_attention_heads
									SCREAMING_SNAKE_CASE_: Any  		=       intermediate_size
									SCREAMING_SNAKE_CASE_: str  		=       hidden_act
									SCREAMING_SNAKE_CASE_: str  		=       hidden_dropout_prob
									SCREAMING_SNAKE_CASE_: List[str]  		=       attention_probs_dropout_prob
									SCREAMING_SNAKE_CASE_: int  		=       type_sequence_label_size
									SCREAMING_SNAKE_CASE_: Dict  		=       initializer_range
									SCREAMING_SNAKE_CASE_: Dict  		=       scope
									SCREAMING_SNAKE_CASE_: Dict  		=       encoder_stride

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



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

									SCREAMING_SNAKE_CASE_: str  		=       None
									if self.use_labels:
															SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       ids_tensor([self.batch_size]   ,						self.type_sequence_label_size)

									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.get_config()

									return config, pixel_values, labels



			def        _SCREAMING_SNAKE_CASE			( self  :     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=lowerCAmelCase__   ,						initializer_range=self.initializer_range   ,						encoder_stride=self.encoder_stride   ,						)



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     int   ,						lowerCAmelCase__  :     Tuple):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       ViTModel(config=lowerCAmelCase__)
									model.to(lowerCAmelCase__)
									model.eval()
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       model(lowerCAmelCase__)
									self.parent.assertEqual(result.last_hidden_state.shape   ,						(self.batch_size, self.seq_length, self.hidden_size))



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]   ,						lowerCAmelCase__  :     Optional[Any]   ,						lowerCAmelCase__  :     Tuple   ,						lowerCAmelCase__  :     Dict):
									SCREAMING_SNAKE_CASE_: Optional[int]  		=       ViTForMaskedImageModeling(config=lowerCAmelCase__)
									model.to(lowerCAmelCase__)
									model.eval()
									SCREAMING_SNAKE_CASE_: str  		=       model(lowerCAmelCase__)
									self.parent.assertEqual(
									    result.reconstruction.shape   ,						(self.batch_size, self.num_channels, self.image_size, self.image_size))

									# test greyscale images
									SCREAMING_SNAKE_CASE_: Dict  		=       1
									SCREAMING_SNAKE_CASE_: List[str]  		=       ViTForMaskedImageModeling(lowerCAmelCase__)
									model.to(lowerCAmelCase__)
									model.eval()

									SCREAMING_SNAKE_CASE_: List[str]  		=       floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
									SCREAMING_SNAKE_CASE_: str  		=       model(lowerCAmelCase__)
									self.parent.assertEqual(result.reconstruction.shape   ,						(self.batch_size, 1, self.image_size, self.image_size))



			def        _SCREAMING_SNAKE_CASE			( self  :     Any   ,						lowerCAmelCase__  :     List[str]   ,						lowerCAmelCase__  :     List[str]   ,						lowerCAmelCase__  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: Tuple  		=       self.type_sequence_label_size
									SCREAMING_SNAKE_CASE_: List[str]  		=       ViTForImageClassification(lowerCAmelCase__)
									model.to(lowerCAmelCase__)
									model.eval()
									SCREAMING_SNAKE_CASE_: Any  		=       model(lowerCAmelCase__   ,						labels=lowerCAmelCase__)
									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_: List[str]  		=       ViTForImageClassification(lowerCAmelCase__)
									model.to(lowerCAmelCase__)
									model.eval()

									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
									SCREAMING_SNAKE_CASE_: Dict  		=       model(lowerCAmelCase__)
									self.parent.assertEqual(result.logits.shape   ,						(self.batch_size, self.type_sequence_label_size))




			def        _SCREAMING_SNAKE_CASE			( self  :     List[Any]):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       self.prepare_config_and_inputs()
									(
									    (
									    SCREAMING_SNAKE_CASE_
									)		,    (
									    SCREAMING_SNAKE_CASE_
									)		,    (
									    SCREAMING_SNAKE_CASE_
									)		,    
									): List[str]  		=       config_and_inputs
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       {"pixel_values": pixel_values}
									return config, inputs_dict







@require_torch
class   __lowercase				( UpperCAmelCase_		,       UpperCAmelCase_		,       unittest.TestCase	):




			"""simple docstring"""







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

			_UpperCAmelCase   :							List[Any]										=     False
			_UpperCAmelCase   :							Optional[Any]										=     False
			_UpperCAmelCase   :							Tuple										=     False



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]):
									SCREAMING_SNAKE_CASE_: List[str]  		=       ViTModelTester(self)
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       ConfigTester(self   ,						config_class=lowerCAmelCase__   ,						has_text_modality=lowerCAmelCase__   ,						hidden_size=37)



			def        _SCREAMING_SNAKE_CASE			( self  :     Any):
									self.config_tester.run_common_tests()



			@unittest.skip(reason="ViT does not use inputs_embeds")
			def        _SCREAMING_SNAKE_CASE			( self  :     str):
									pass



			def        _SCREAMING_SNAKE_CASE			( self  :     str):
									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															SCREAMING_SNAKE_CASE_: Dict  		=       model_class(lowerCAmelCase__)
															self.assertIsInstance(model.get_input_embeddings()   ,						(nn.Module))
															SCREAMING_SNAKE_CASE_: List[Any]  		=       model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(lowerCAmelCase__   ,						nn.Linear))



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[int]):
									SCREAMING_SNAKE_CASE_		,    SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.model_tester.prepare_config_and_inputs_for_common()

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

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



			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: Tuple  		=       self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowerCAmelCase__)



			def        _SCREAMING_SNAKE_CASE			( self  :     Optional[Any]):
									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_masked_image_modeling(*lowerCAmelCase__)



			def        _SCREAMING_SNAKE_CASE			( self  :     List[str]):
									SCREAMING_SNAKE_CASE_: int  		=       self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__)




			@slow
			def        _SCREAMING_SNAKE_CASE			( self  :     int):
									for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
															SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       ViTModel.from_pretrained(lowerCAmelCase__)
															self.assertIsNotNone(lowerCAmelCase__)







def 			A_      (    ):
						SCREAMING_SNAKE_CASE_: List[Any]  		=       Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"    )
						return image



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




			"""simple docstring"""







			@cached_property
			def        _SCREAMING_SNAKE_CASE			( self  :     int):
									return ViTImageProcessor.from_pretrained("google/vit-base-patch16-224") if is_vision_available() else None



			@slow
			def        _SCREAMING_SNAKE_CASE			( self  :     Union[str, Any]):
									SCREAMING_SNAKE_CASE_: int  		=       ViTForImageClassification.from_pretrained("google/vit-base-patch16-224").to(lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       self.default_image_processor
									SCREAMING_SNAKE_CASE_: str  		=       prepare_img()
									SCREAMING_SNAKE_CASE_: Optional[Any]  		=       image_processor(images=lowerCAmelCase__   ,						return_tensors="pt").to(lowerCAmelCase__)

									# forward pass
									with torch.no_grad():
															SCREAMING_SNAKE_CASE_: Optional[int]  		=       model(**lowerCAmelCase__)

									# verify the logits
									SCREAMING_SNAKE_CASE_: Any  		=       torch.Size((1, 1000))
									self.assertEqual(outputs.logits.shape   ,						lowerCAmelCase__)

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

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



			@slow
			def        _SCREAMING_SNAKE_CASE			( self  :     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.
									SCREAMING_SNAKE_CASE_: str  		=       ViTModel.from_pretrained("facebook/dino-vits8").to(lowerCAmelCase__)

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

									# forward pass
									with torch.no_grad():
															SCREAMING_SNAKE_CASE_: Optional[int]  		=       model(lowerCAmelCase__   ,						interpolate_pos_encoding=lowerCAmelCase__)

									# verify the logits
									SCREAMING_SNAKE_CASE_: Tuple  		=       torch.Size((1, 3601, 384))
									self.assertEqual(outputs.last_hidden_state.shape   ,						lowerCAmelCase__)

									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       torch.tensor(
									    [[4.2340, 4.3906, -6.6692], [4.5463, 1.8928, -6.7257], [4.4429, 0.8496, -5.8585]]).to(lowerCAmelCase__)

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




			@slow
			@require_accelerate
			@require_torch_gpu
			def        _SCREAMING_SNAKE_CASE			( self  :     int):
									SCREAMING_SNAKE_CASE_: Dict  		=       ViTModel.from_pretrained("facebook/dino-vits8"   ,						torch_dtype=torch.floataa   ,						device_map="auto")
									SCREAMING_SNAKE_CASE_: int  		=       self.default_image_processor

									SCREAMING_SNAKE_CASE_: Union[str, Any]  		=       prepare_img()
									SCREAMING_SNAKE_CASE_: Dict  		=       image_processor(images=lowerCAmelCase__   ,						return_tensors="pt")
									SCREAMING_SNAKE_CASE_: str  		=       inputs.pixel_values.to(lowerCAmelCase__)

									# forward pass to make sure inference works in fp16
									with torch.no_grad():
															SCREAMING_SNAKE_CASE_: str  		=       model(lowerCAmelCase__)






