





'''simple docstring'''






import json
import os
import re
import shutil
import tempfile
import unittest
from typing import Tuple

from transformers import AddedToken, BatchEncoding, PerceiverTokenizer
from transformers.utils import cached_property, is_tf_available, is_torch_available

from ...test_tokenization_common import TokenizerTesterMixin


if is_torch_available():
		A   : Optional[int]             =			'pt'
elif is_tf_available():
		A   : str             =			'tf'
else:
		A   : Dict             =			'jax'







class 			lowerCamelCase					(						__UpperCAmelCase     ,							unittest.TestCase  ):
					_SCREAMING_SNAKE_CASE							   =    PerceiverTokenizer
					_SCREAMING_SNAKE_CASE							   =    False


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[Any]       ):





											'''simple docstring'''





											super().setUp()
											_snake_case:   Union[str, Any]  					=		PerceiverTokenizer()
											tokenizer.save_pretrained(self.tmpdirname       )


					@cached_property
					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ):





											'''simple docstring'''





											return PerceiverTokenizer.from_pretrained('deepmind/language-perceiver'       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Any       ,     **__snake_case	:  Tuple       ):





											'''simple docstring'''





											return self.tokenizer_class.from_pretrained(self.tmpdirname       ,     **__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[int]       ,     __snake_case	:  int       ,     __snake_case	:  List[Any]=False       ,     __snake_case	:  Dict=20       ,     __snake_case	:  str=5       ):





											'''simple docstring'''





											_snake_case:   Optional[Any]  					=		[]
											for i in range(len(__snake_case       )       ):
																	try:
																							_snake_case:   List[Any]  					=		tokenizer.decode([i]       ,     clean_up_tokenization_spaces=__snake_case       )
																	except UnicodeDecodeError:
																							pass
																	toks.append((i, tok)       )

											_snake_case:   List[str]  					=		list(filter(lambda __snake_case       : re.match(R'^[ a-zA-Z]+$'       ,     t[1]       )       ,     __snake_case       )       )
											_snake_case:   int  					=		list(filter(lambda __snake_case       : [t[0]] == tokenizer.encode(t[1]       ,     add_special_tokens=__snake_case       )       ,     __snake_case       )       )
											if max_length is not None and len(__snake_case       ) > max_length:
																	_snake_case:   int  					=		toks[:max_length]
											if min_length is not None and len(__snake_case       ) < min_length and len(__snake_case       ) > 0:
																	while len(__snake_case       ) < min_length:
																							_snake_case:   Optional[Any]  					=		toks + toks
        # toks_str = [t[1] for t in toks]
											_snake_case:   Union[str, Any]  					=		[t[0] for t in toks]

											# Ensure consistency
											_snake_case:   List[Any]  					=		tokenizer.decode(__snake_case       ,     clean_up_tokenization_spaces=__snake_case       )
											if " " not in output_txt and len(__snake_case       ) > 1:
																	_snake_case:   Any  					=		(
																	    tokenizer.decode([toks_ids[0]]       ,     clean_up_tokenization_spaces=__snake_case       )
																	    + ' '
																	    + tokenizer.decode(toks_ids[1:]       ,     clean_up_tokenization_spaces=__snake_case       )
																	)
											if with_prefix_space:
																	_snake_case:   Optional[Any]  					=		' ' + output_txt
											_snake_case:   int  					=		tokenizer.encode(__snake_case       ,     add_special_tokens=__snake_case       )
											return output_txt, output_ids


					def    SCREAMING_SNAKE_CASE_		(					self	:  Any       ):





											'''simple docstring'''





											_snake_case:   Optional[int]  					=		self.perceiver_tokenizer
											_snake_case:   List[str]  					=		'Unicode €.'
											_snake_case:   Dict  					=		tokenizer(__snake_case       )
											_snake_case:   List[Any]  					=		[4, 91, 1_16, 1_11, 1_05, 1_17, 1_06, 1_07, 38, 2_32, 1_36, 1_78, 52, 5]
											self.assertEqual(encoded['input_ids']       ,     __snake_case       )

											# decoding
											_snake_case:   Union[str, Any]  					=		tokenizer.decode(__snake_case       )
											self.assertEqual(__snake_case       ,     '[CLS]Unicode €.[SEP]'       )

											_snake_case:   Union[str, Any]  					=		tokenizer('e è é ê ë'       )
											_snake_case:   Optional[Any]  					=		[4, 1_07, 38, 2_01, 1_74, 38, 2_01, 1_75, 38, 2_01, 1_76, 38, 2_01, 1_77, 5]
											self.assertEqual(encoded['input_ids']       ,     __snake_case       )
											# decoding
											_snake_case:   Optional[Any]  					=		tokenizer.decode(__snake_case       )
											self.assertEqual(__snake_case       ,     '[CLS]e è é ê ë[SEP]'       )

											# encode/decode, but with `encode` instead of `__call__`
											self.assertEqual(tokenizer.decode(tokenizer.encode('e è é ê ë'       )       )       ,     '[CLS]e è é ê ë[SEP]'       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ):





											'''simple docstring'''





											_snake_case:   Dict  					=		self.perceiver_tokenizer
											_snake_case:   List[Any]  					=		['A long paragraph for summarization.', 'Another paragraph for summarization.']
											# fmt: off
											_snake_case:   Dict  					=		[4, 71, 38, 1_14, 1_17, 1_16, 1_09, 38, 1_18, 1_03, 1_20, 1_03, 1_09, 1_20, 1_03, 1_18, 1_10, 38, 1_08, 1_17, 1_20, 38, 1_21, 1_23, 1_15, 1_15, 1_03, 1_20, 1_11, 1_28, 1_03, 1_22, 1_11, 1_17, 1_16, 52, 5, 0]
											# fmt: on
											_snake_case:   Union[str, Any]  					=		tokenizer(__snake_case       ,     padding=__snake_case       ,     return_tensors=__snake_case       )
											self.assertIsInstance(__snake_case       ,     __snake_case       )

											if FRAMEWORK != "jax":
																	_snake_case:   Union[str, Any]  					=		list(batch.input_ids.numpy()[0]       )
											else:
																	_snake_case:   Any  					=		list(batch.input_ids.tolist()[0]       )

											self.assertListEqual(__snake_case       ,     __snake_case       )

											self.assertEqual((2, 38)       ,     batch.input_ids.shape       )
											self.assertEqual((2, 38)       ,     batch.attention_mask.shape       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[Any]       ):





											'''simple docstring'''





											_snake_case:   List[str]  					=		self.perceiver_tokenizer
											_snake_case:   Optional[Any]  					=		['A long paragraph for summarization.', 'Another paragraph for summarization.']
											_snake_case:   Dict  					=		tokenizer(__snake_case       ,     padding=__snake_case       ,     return_tensors=__snake_case       )
											# check if input_ids are returned and no decoder_input_ids
											self.assertIn('input_ids'       ,     __snake_case       )
											self.assertIn('attention_mask'       ,     __snake_case       )
											self.assertNotIn('decoder_input_ids'       ,     __snake_case       )
											self.assertNotIn('decoder_attention_mask'       ,     __snake_case       )


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





											'''simple docstring'''





											_snake_case:   Dict  					=		self.perceiver_tokenizer
											_snake_case:   Dict  					=		[
											    'Summary of the text.',
											    'Another summary.',
											]
											_snake_case:   int  					=		tokenizer(
											    text_target=__snake_case       ,     max_length=32       ,     padding='max_length'       ,     truncation=__snake_case       ,     return_tensors=__snake_case       )
											self.assertEqual(32       ,     targets['input_ids'].shape[1]       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Tuple       ):





											'''simple docstring'''





											_snake_case:   Dict  					=		self.get_tokenizers()
											for tokenizer in tokenizers:
																	with self.subTest(f'''{tokenizer.__class__.__name__}'''       ):
																							self.assertNotEqual(tokenizer.model_max_length       ,     42       )

        # Now let's start the test
											_snake_case:   str  					=		self.get_tokenizers()
											for tokenizer in tokenizers:
																	with self.subTest(f'''{tokenizer.__class__.__name__}'''       ):
																							# Isolate this from the other tests because we save additional tokens/etc
																							_snake_case:   List[Any]  					=		tempfile.mkdtemp()

																							_snake_case:   Tuple  					=		' He is very happy, UNwant\u00E9d,running'
																							_snake_case:   Union[str, Any]  					=		tokenizer.encode(__snake_case       ,     add_special_tokens=__snake_case       )
																							tokenizer.save_pretrained(__snake_case       )

																							_snake_case:   Any  					=		tokenizer.__class__.from_pretrained(__snake_case       )
																							_snake_case:   Optional[int]  					=		after_tokenizer.encode(__snake_case       ,     add_special_tokens=__snake_case       )
																							self.assertListEqual(__snake_case       ,     __snake_case       )

																							shutil.rmtree(__snake_case       )

											_snake_case:   Optional[Any]  					=		self.get_tokenizers(model_max_length=42       )
											for tokenizer in tokenizers:
																	with self.subTest(f'''{tokenizer.__class__.__name__}'''       ):
																							# Isolate this from the other tests because we save additional tokens/etc
																							_snake_case:   Dict  					=		tempfile.mkdtemp()

																							_snake_case:   Union[str, Any]  					=		' He is very happy, UNwant\u00E9d,running'
																							tokenizer.add_tokens(['bim', 'bambam']       )
																							_snake_case:   str  					=		tokenizer.additional_special_tokens
																							additional_special_tokens.append('new_additional_special_token'       )
																							tokenizer.add_special_tokens({'additional_special_tokens': additional_special_tokens}       )
																							_snake_case:   Optional[int]  					=		tokenizer.encode(__snake_case       ,     add_special_tokens=__snake_case       )
																							tokenizer.save_pretrained(__snake_case       )

																							_snake_case:   Optional[int]  					=		tokenizer.__class__.from_pretrained(__snake_case       )
																							_snake_case:   Optional[Any]  					=		after_tokenizer.encode(__snake_case       ,     add_special_tokens=__snake_case       )
																							self.assertListEqual(__snake_case       ,     __snake_case       )
																							self.assertIn('new_additional_special_token'       ,     after_tokenizer.additional_special_tokens       )
																							self.assertEqual(after_tokenizer.model_max_length       ,     42       )

																							_snake_case:   Union[str, Any]  					=		tokenizer.__class__.from_pretrained(__snake_case       ,     model_max_length=43       )
																							self.assertEqual(tokenizer.model_max_length       ,     43       )

																							shutil.rmtree(__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Any       ):





											'''simple docstring'''





											_snake_case:   Any  					=		[]
											if self.test_slow_tokenizer:
																	tokenizer_list.append((self.tokenizer_class, self.get_tokenizer())       )

											if self.test_rust_tokenizer:
																	tokenizer_list.append((self.rust_tokenizer_class, self.get_rust_tokenizer())       )

											for tokenizer_class, tokenizer_utils in tokenizer_list:
																	with tempfile.TemporaryDirectory() as tmp_dir:
																							tokenizer_utils.save_pretrained(__snake_case       )

																							with open(os.path.join(__snake_case       ,     'special_tokens_map.json'       )       ,     encoding='utf-8'       ) as json_file:
																													_snake_case:   Tuple  					=		json.load(__snake_case       )

																							with open(os.path.join(__snake_case       ,     'tokenizer_config.json'       )       ,     encoding='utf-8'       ) as json_file:
																													_snake_case:   Optional[int]  					=		json.load(__snake_case       )

																							_snake_case:   List[str]  					=		[f'''<extra_id_{i}>''' for i in range(1_25       )]

																							_snake_case:   int  					=		added_tokens_extra_ids + [
																							    'an_additional_special_token'
																							]
																							_snake_case:   List[Any]  					=		added_tokens_extra_ids + [
																							    'an_additional_special_token'
																							]

																							with open(os.path.join(__snake_case       ,     'special_tokens_map.json'       )       ,     'w'       ,     encoding='utf-8'       ) as outfile:
																													json.dump(__snake_case       ,     __snake_case       )
																							with open(os.path.join(__snake_case       ,     'tokenizer_config.json'       )       ,     'w'       ,     encoding='utf-8'       ) as outfile:
																													json.dump(__snake_case       ,     __snake_case       )

																							# the following checks allow us to verify that our test works as expected, i.e. that the tokenizer takes
																							# into account the new value of additional_special_tokens given in the "tokenizer_config.json" and
																							# "special_tokens_map.json" files
																							_snake_case:   str  					=		tokenizer_class.from_pretrained(
																							    __snake_case       ,     )
																							self.assertIn(
																							    'an_additional_special_token'       ,     tokenizer_without_change_in_init.additional_special_tokens       )
																							self.assertEqual(
																							    ['an_additional_special_token']       ,     tokenizer_without_change_in_init.convert_ids_to_tokens(
																							        tokenizer_without_change_in_init.convert_tokens_to_ids(['an_additional_special_token']       )       )       ,     )

																							# Now we test that we can change the value of additional_special_tokens in the from_pretrained
																							_snake_case:   int  					=		added_tokens_extra_ids + [AddedToken('a_new_additional_special_token'       ,     lstrip=__snake_case       )]
																							_snake_case:   Union[str, Any]  					=		tokenizer_class.from_pretrained(
																							    __snake_case       ,     additional_special_tokens=__snake_case       ,     )

																							self.assertIn('a_new_additional_special_token'       ,     tokenizer.additional_special_tokens       )
																							self.assertEqual(
																							    ['a_new_additional_special_token']       ,     tokenizer.convert_ids_to_tokens(
																							        tokenizer.convert_tokens_to_ids(['a_new_additional_special_token']       )       )       ,     )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Any       ):





											'''simple docstring'''





											_snake_case:   Union[str, Any]  					=		self.perceiver_tokenizer
											self.assertEqual(tokenizer.decode([1_78]       )       ,     '�'       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ):





											'''simple docstring'''





											pass


					def    SCREAMING_SNAKE_CASE_		(					self	:  str       ):





											'''simple docstring'''





											pass


					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ):





											'''simple docstring'''





											pass


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[Any]       ):





											'''simple docstring'''





											pass




					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ):





											'''simple docstring'''





											_snake_case:   Union[str, Any]  					=		self.get_tokenizers(fast=__snake_case       ,     do_lower_case=__snake_case       )
											for tokenizer in tokenizers:
																	with self.subTest(f'''{tokenizer.__class__.__name__}'''       ):
																							_snake_case:   Optional[Any]  					=		['[CLS]', 't', 'h', 'i', 's', ' ', 'i', 's', ' ', 'a', ' ', 't', 'e', 's', 't', '[SEP]']
																							_snake_case:   Optional[int]  					=		tokenizer.convert_tokens_to_string(__snake_case       )

																							self.assertIsInstance(__snake_case       ,     __snake_case       )












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


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





											'''simple docstring'''





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

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


					def    SCREAMING_SNAKE_CASE_		(					self	:  str       ):





											'''simple docstring'''





											_snake_case:   List[str]  					=		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

											_snake_case:   Union[str, Any]  					=		self.get_config()

											return config, pixel_values, labels


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


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ,     __snake_case	:  int       ,     __snake_case	:  Optional[int]       ,     __snake_case	:  List[str]       ):





											'''simple docstring'''





											_snake_case:   Dict  					=		ViTModel(config=__snake_case       )
											model.to(__snake_case       )
											model.eval()
											_snake_case:   Tuple  					=		model(__snake_case       )
											self.parent.assertEqual(result.last_hidden_state.shape       ,     (self.batch_size, self.seq_length, self.hidden_size)       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[Any]       ,     __snake_case	:  Union[str, Any]       ,     __snake_case	:  Union[str, Any]       ,     __snake_case	:  int       ):





											'''simple docstring'''





											_snake_case:   int  					=		ViTForMaskedImageModeling(config=__snake_case       )
											model.to(__snake_case       )
											model.eval()
											_snake_case:   Dict  					=		model(__snake_case       )
											self.parent.assertEqual(
											    result.reconstruction.shape       ,     (self.batch_size, self.num_channels, self.image_size, self.image_size)       )

											# test greyscale images
											_snake_case:   List[str]  					=		1
											_snake_case:   Tuple  					=		ViTForMaskedImageModeling(__snake_case       )
											model.to(__snake_case       )
											model.eval()

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


					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ,     __snake_case	:  Union[str, Any]       ,     __snake_case	:  Optional[int]       ,     __snake_case	:  Dict       ):





											'''simple docstring'''





											_snake_case:   Optional[int]  					=		self.type_sequence_label_size
											_snake_case:   Union[str, Any]  					=		ViTForImageClassification(__snake_case       )
											model.to(__snake_case       )
											model.eval()
											_snake_case:   List[Any]  					=		model(__snake_case       ,     labels=__snake_case       )
											self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.type_sequence_label_size)       )

											# test greyscale images
											_snake_case:   Tuple  					=		1
											_snake_case:   Optional[int]  					=		ViTForImageClassification(__snake_case       )
											model.to(__snake_case       )
											model.eval()

											_snake_case:   List[Any]  					=		floats_tensor([self.batch_size, 1, self.image_size, self.image_size]       )
											_snake_case:   Any  					=		model(__snake_case       )
											self.parent.assertEqual(result.logits.shape       ,     (self.batch_size, self.type_sequence_label_size)       )




					def    SCREAMING_SNAKE_CASE_		(					self	:  Tuple       ):





											'''simple docstring'''





											_snake_case:   Any  					=		self.prepare_config_and_inputs()
											(
											    (
											    _snake_case
											)					,						(
											    _snake_case
											)					,						(
											    _snake_case
											)					,						
											):   int  					=		config_and_inputs
											_snake_case:   Dict  					=		{'pixel_values': pixel_values}
											return config, inputs_dict







@require_torch
class 			lowerCamelCase					(						__UpperCAmelCase     ,							__UpperCAmelCase     ,							unittest.TestCase  ):
					_SCREAMING_SNAKE_CASE							   =    (
					    (
					        ViTModel,
					        ViTForImageClassification,
					        ViTForMaskedImageModeling,
					    )
					    if is_torch_available()
					    else ()
					)
					_SCREAMING_SNAKE_CASE							   =    (
					    {"feature-extraction": ViTModel, "image-classification": ViTForImageClassification}
					    if is_torch_available()
					    else {}
					)
					_SCREAMING_SNAKE_CASE							   =    True

					_SCREAMING_SNAKE_CASE							   =    False
					_SCREAMING_SNAKE_CASE							   =    False
					_SCREAMING_SNAKE_CASE							   =    False


					def    SCREAMING_SNAKE_CASE_		(					self	:  Tuple       ):





											'''simple docstring'''





											_snake_case:   Optional[int]  					=		ViTModelTester(self       )
											_snake_case:   Union[str, Any]  					=		ConfigTester(self       ,     config_class=__snake_case       ,     has_text_modality=__snake_case       ,     hidden_size=37       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ):





											'''simple docstring'''





											self.config_tester.run_common_tests()


					@unittest.skip(reason='ViT does not use inputs_embeds'       )
					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ):





											'''simple docstring'''





											pass


					def    SCREAMING_SNAKE_CASE_		(					self	:  str       ):





											'''simple docstring'''





											_snake_case					,						_snake_case:   Dict  					=		self.model_tester.prepare_config_and_inputs_for_common()

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


					def    SCREAMING_SNAKE_CASE_		(					self	:  Any       ):





											'''simple docstring'''





											_snake_case					,						_snake_case:   List[Any]  					=		self.model_tester.prepare_config_and_inputs_for_common()

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

																	_snake_case:   str  					=		['pixel_values']
																	self.assertListEqual(arg_names[:1]       ,     __snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[Any]       ):





											'''simple docstring'''





											_snake_case:   List[Any]  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*__snake_case       )


					def    SCREAMING_SNAKE_CASE_		(					self	:  List[str]       ):





											'''simple docstring'''





											_snake_case:   int  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_masked_image_modeling(*__snake_case       )


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





											'''simple docstring'''





											_snake_case:   str  					=		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*__snake_case       )




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





											'''simple docstring'''





											for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																	_snake_case:   Any  					=		ViTModel.from_pretrained(__snake_case       )
																	self.assertIsNotNone(__snake_case       )





def       lowercase_      (		)   ->List[Any]:
						_snake_case:   Dict  					=		Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'						)
						return image







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


					@cached_property
					def    SCREAMING_SNAKE_CASE_		(					self	:  Optional[Any]       ):





											'''simple docstring'''





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


					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  Dict       ):





											'''simple docstring'''





											_snake_case:   Optional[int]  					=		ViTForImageClassification.from_pretrained('google/vit-base-patch16-224'       ).to(__snake_case       )

											_snake_case:   Dict  					=		self.default_image_processor
											_snake_case:   Optional[Any]  					=		prepare_img()
											_snake_case:   List[str]  					=		image_processor(images=__snake_case       ,     return_tensors='pt'       ).to(__snake_case       )

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

											# verify the logits
											_snake_case:   Union[str, Any]  					=		torch.Size((1, 10_00)       )
											self.assertEqual(outputs.logits.shape       ,     __snake_case       )

											_snake_case:   Dict  					=		torch.tensor([-0.2_744, 0.8_215, -0.0_836]       ).to(__snake_case       )

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


					@slow
					def    SCREAMING_SNAKE_CASE_		(					self	:  Union[str, Any]       ):





											'''simple docstring'''





											_snake_case:   str  					=		ViTModel.from_pretrained('facebook/dino-vits8'       ).to(__snake_case       )

											_snake_case:   Any  					=		ViTImageProcessor.from_pretrained('facebook/dino-vits8'       ,     size=4_80       )
											_snake_case:   Optional[int]  					=		prepare_img()
											_snake_case:   Dict  					=		image_processor(images=__snake_case       ,     return_tensors='pt'       )
											_snake_case:   Optional[Any]  					=		inputs.pixel_values.to(__snake_case       )

											# forward pass
											with torch.no_grad():
																	_snake_case:   str  					=		model(__snake_case       ,     interpolate_pos_encoding=__snake_case       )

											# verify the logits
											_snake_case:   List[str]  					=		torch.Size((1, 36_01, 3_84)       )
											self.assertEqual(outputs.last_hidden_state.shape       ,     __snake_case       )

											_snake_case:   Any  					=		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(__snake_case       )

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




					@slow
					@require_accelerate
					@require_torch_gpu
					def    SCREAMING_SNAKE_CASE_		(					self	:  int       ):





											'''simple docstring'''





											_snake_case:   List[Any]  					=		ViTModel.from_pretrained('facebook/dino-vits8'       ,     torch_dtype=torch.floataa       ,     device_map='auto'       )
											_snake_case:   Dict  					=		self.default_image_processor

											_snake_case:   Any  					=		prepare_img()
											_snake_case:   str  					=		image_processor(images=__snake_case       ,     return_tensors='pt'       )
											_snake_case:   Any  					=		inputs.pixel_values.to(__snake_case       )

											# forward pass to make sure inference works in fp16
											with torch.no_grad():
																	_snake_case:   int  					=		model(__snake_case       )





