



'''simple docstring'''




import shutil
import tempfile
import unittest

from transformers import SPIECE_UNDERLINE, BatchEncoding, MBartTokenizer, MBartTokenizerFast, is_torch_available
from transformers.testing_utils import (
    get_tests_dir,
    nested_simplify,
    require_sentencepiece,
    require_tokenizers,
    require_torch,
)

from ...test_tokenization_common import TokenizerTesterMixin


lowerCamelCase							:Union[str, Any]       = get_tests_dir('''fixtures/test_sentencepiece.model''')


if is_torch_available():
						from transformers.models.mbart.modeling_mbart import shift_tokens_right

lowerCamelCase							:Dict       = 2_5_0_0_0_4
lowerCamelCase							:Dict       = 2_5_0_0_2_0







@require_sentencepiece
@require_tokenizers
class      _lowerCAmelCase							(      __UpperCAmelCase				,      unittest.TestCase			):
	__SCREAMING_SNAKE_CASE       :		int		      = MBartTokenizer
	__SCREAMING_SNAKE_CASE       :		Optional[Any]		      = MBartTokenizerFast
	__SCREAMING_SNAKE_CASE       :		int		      = True
	__SCREAMING_SNAKE_CASE       :		List[str]		      = True


	def    _a     (self							):
				super().setUp()

				# We have a SentencePiece fixture for testing
				A_     :						Dict     =					MBartTokenizer(lowercase	,				keep_accents=lowercase							)
				tokenizer.save_pretrained(self.tmpdirname							)


	def    _a     (self							):
				A_     :						Any     =					MBartTokenizer(lowercase	,				keep_accents=lowercase							)

				A_     :						int     =					tokenizer.tokenize("""This is a test"""							)
				self.assertListEqual(lowercase	,				["""▁This""", """▁is""", """▁a""", """▁t""", """est"""]							)

				self.assertListEqual(
				    tokenizer.convert_tokens_to_ids(lowercase							)	,				[value + tokenizer.fairseq_offset for value in [285, 46, 10, 170, 382]]	,				)

				A_     :						List[Any]     =					tokenizer.tokenize("""I was born in 92000, and this is falsé."""							)
				self.assertListEqual(
				    lowercase	,				[
				        SPIECE_UNDERLINE + """I""",
				        SPIECE_UNDERLINE + """was""",
				        SPIECE_UNDERLINE + """b""",
				        """or""",
				        """n""",
				        SPIECE_UNDERLINE + """in""",
				        SPIECE_UNDERLINE + """""",
				        """9""",
				        """2""",
				        """0""",
				        """0""",
				        """0""",
				        """,""",
				        SPIECE_UNDERLINE + """and""",
				        SPIECE_UNDERLINE + """this""",
				        SPIECE_UNDERLINE + """is""",
				        SPIECE_UNDERLINE + """f""",
				        """al""",
				        """s""",
				        """é""",
				        """.""",
				    ]	,				)
				A_     :						Dict     =					tokenizer.convert_tokens_to_ids(lowercase							)
				self.assertListEqual(
				    lowercase	,				[
				        value + tokenizer.fairseq_offset
				        for value in [8, 21, 84, 55, 24, 19, 7, 2, 602, 347, 347, 347, 3, 12, 66, 46, 72, 80, 6, 2, 4]
				        #                                       ^ unk: 2 + 1 = 3                  unk: 2 + 1 = 3 ^
				    ]	,				)

				A_     :						List[str]     =					tokenizer.convert_ids_to_tokens(lowercase							)
				self.assertListEqual(
				    lowercase	,				[
				        SPIECE_UNDERLINE + """I""",
				        SPIECE_UNDERLINE + """was""",
				        SPIECE_UNDERLINE + """b""",
				        """or""",
				        """n""",
				        SPIECE_UNDERLINE + """in""",
				        SPIECE_UNDERLINE + """""",
				        """<unk>""",
				        """2""",
				        """0""",
				        """0""",
				        """0""",
				        """,""",
				        SPIECE_UNDERLINE + """and""",
				        SPIECE_UNDERLINE + """this""",
				        SPIECE_UNDERLINE + """is""",
				        SPIECE_UNDERLINE + """f""",
				        """al""",
				        """s""",
				        """<unk>""",
				        """.""",
				    ]	,				)


	def    _a     (self							):
				if not self.test_slow_tokenizer:
							# as we don't have a slow version, we can't compare the outputs between slow and fast versions
							return

				A_     :						Any     =					(self.rust_tokenizer_class, """hf-internal-testing/tiny-random-mbart""", {})
				for tokenizer, pretrained_name, kwargs in self.tokenizers_list:
							with self.subTest(F'{tokenizer.__class__.__name__} ({pretrained_name})'							):
										A_     :						Union[str, Any]     =					self.rust_tokenizer_class.from_pretrained(lowercase	,				**lowercase							)
										A_     :						List[Any]     =					self.tokenizer_class.from_pretrained(lowercase	,				**lowercase							)

										A_     :						str     =					tempfile.mkdtemp()

										A_     :						Optional[Any]     =					tokenizer_r.save_pretrained(lowercase							)
										A_     :						Dict     =					tokenizer_p.save_pretrained(lowercase							)

										# Checks it save with the same files + the tokenizer.json file for the fast one
										self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files							)							)
										A_     :						str     =					tuple(f for f in tokenizer_r_files if """tokenizer.json""" not in f							)
										self.assertSequenceEqual(lowercase	,				lowercase							)

										# Checks everything loads correctly in the same way
										A_     :						Optional[int]     =					tokenizer_r.from_pretrained(lowercase							)
										A_     :						Dict     =					tokenizer_p.from_pretrained(lowercase							)

										# Check special tokens are set accordingly on Rust and Python
										for key in tokenizer_pp.special_tokens_map:
													self.assertTrue(hasattr(lowercase	,				lowercase							)							)
													# self.assertEqual(getattr(tokenizer_rp, key), getattr(tokenizer_pp, key))
													# self.assertEqual(getattr(tokenizer_rp, key + "_id"), getattr(tokenizer_pp, key + "_id"))

										shutil.rmtree(lowercase							)

										# Save tokenizer rust, legacy_format=True
										A_     :						Union[str, Any]     =					tempfile.mkdtemp()

										A_     :						Union[str, Any]     =					tokenizer_r.save_pretrained(lowercase	,				legacy_format=lowercase							)
										A_     :						Dict     =					tokenizer_p.save_pretrained(lowercase							)

										# Checks it save with the same files
										self.assertSequenceEqual(lowercase	,				lowercase							)

										# Checks everything loads correctly in the same way
										A_     :						Optional[int]     =					tokenizer_r.from_pretrained(lowercase							)
										A_     :						Any     =					tokenizer_p.from_pretrained(lowercase							)

										# Check special tokens are set accordingly on Rust and Python
										for key in tokenizer_pp.special_tokens_map:
													self.assertTrue(hasattr(lowercase	,				lowercase							)							)

										shutil.rmtree(lowercase							)

										# Save tokenizer rust, legacy_format=False
										A_     :						List[str]     =					tempfile.mkdtemp()

										A_     :						List[Any]     =					tokenizer_r.save_pretrained(lowercase	,				legacy_format=lowercase							)
										A_     :						List[Any]     =					tokenizer_p.save_pretrained(lowercase							)

										# Checks it saved the tokenizer.json file
										self.assertTrue(any("""tokenizer.json""" in f for f in tokenizer_r_files							)							)

										# Checks everything loads correctly in the same way
										A_     :						List[str]     =					tokenizer_r.from_pretrained(lowercase							)
										A_     :						List[str]     =					tokenizer_p.from_pretrained(lowercase							)

										# Check special tokens are set accordingly on Rust and Python
										for key in tokenizer_pp.special_tokens_map:
													self.assertTrue(hasattr(lowercase	,				lowercase							)							)

										shutil.rmtree(lowercase							)







@require_torch
@require_sentencepiece
@require_tokenizers
class      _lowerCAmelCase							(      unittest.TestCase			):
	__SCREAMING_SNAKE_CASE       :		Tuple		      = 'facebook/mbart-large-en-ro'
	__SCREAMING_SNAKE_CASE       :		Optional[int]		      = [
	    ' UN Chief Says There Is No Military Solution in Syria',
	    ' Secretary-General Ban Ki-moon says his response to Russia\'s stepped up military support for Syria is that "there is no military solution" to the nearly five-year conflict and more weapons will only worsen the violence and misery for millions of people.',
	]
	__SCREAMING_SNAKE_CASE       :		Union[str, Any]		      = [
	    'Şeful ONU declară că nu există o soluţie militară în Siria',
	    'Secretarul General Ban Ki-moon declară că răspunsul său la intensificarea sprijinului militar al Rusiei'
	    ' pentru Siria este că "nu există o soluţie militară" la conflictul de aproape cinci ani şi că noi arme nu vor'
	    ' face decât să înrăutăţească violenţele şi mizeria pentru milioane de oameni.',
	]
	__SCREAMING_SNAKE_CASE       :		Union[str, Any]		      = [8_274, 127_873, 25_916, 7, 8_622, 2_071, 438, 67_485, 53, 187_895, 23, 51_712, 2, EN_CODE]


	@classmethod
	def    _a     (cls							):
				A_     :						MBartTokenizer     =					MBartTokenizer.from_pretrained(
				    cls.checkpoint_name	,				src_lang="""en_XX"""	,				tgt_lang="""ro_RO"""							)
				A_     :						str     =					1
				return cls


	def    _a     (self							):
				self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ar_AR"""]	,				250001							)
				self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""en_EN"""]	,				250004							)
				self.assertEqual(self.tokenizer.fairseq_tokens_to_ids["""ro_RO"""]	,				250020							)


	def    _a     (self							):
				A_     :						Any     =					self.tokenizer.batch_encode_plus(self.src_text							).input_ids[0]
				self.assertListEqual(self.expected_src_tokens	,				lowercase							)


	def    _a     (self							):
				self.assertIn(lowercase	,				self.tokenizer.all_special_ids							)
				A_     :						List[str]     =					[RO_CODE, 884, 9019, 96, 9, 916, 86792, 36, 18743, 15596, 5, 2]
				A_     :						Optional[Any]     =					self.tokenizer.decode(lowercase	,				skip_special_tokens=lowercase							)
				A_     :						str     =					self.tokenizer.decode(generated_ids[1:]	,				skip_special_tokens=lowercase							)
				self.assertEqual(lowercase	,				lowercase							)
				self.assertNotIn(self.tokenizer.eos_token	,				lowercase							)


	def    _a     (self							):
				A_     :						Optional[int]     =					["""this is gunna be a long sentence """ * 20]
				assert isinstance(src_text[0]	,				lowercase							)
				A_     :						str     =					10
				A_     :						List[str]     =					self.tokenizer(lowercase	,				max_length=lowercase	,				truncation=lowercase							).input_ids[0]
				self.assertEqual(ids[-2]	,				2							)
				self.assertEqual(ids[-1]	,				lowercase							)
				self.assertEqual(len(lowercase							)	,				lowercase							)


	def    _a     (self							):
				self.assertListEqual(self.tokenizer.convert_tokens_to_ids(["""<mask>""", """ar_AR"""]							)	,				[250026, 250001]							)


	def    _a     (self							):
				A_     :						int     =					tempfile.mkdtemp()
				A_     :						Any     =					self.tokenizer.fairseq_tokens_to_ids
				self.tokenizer.save_pretrained(lowercase							)
				A_     :						Optional[Any]     =					MBartTokenizer.from_pretrained(lowercase							)
				self.assertDictEqual(new_tok.fairseq_tokens_to_ids	,				lowercase							)


	@require_torch
	def    _a     (self							):
				A_     :						Dict     =					self.tokenizer(self.src_text	,				text_target=self.tgt_text	,				padding=lowercase	,				return_tensors="""pt"""							)
				A_     :						Optional[Any]     =					shift_tokens_right(batch["""labels"""]	,				self.tokenizer.pad_token_id							)

				# fairseq batch: https://gist.github.com/sshleifer/cba08bc2109361a74ac3760a7e30e4f4
				assert batch.input_ids[1][-2:].tolist() == [2, EN_CODE]
				assert batch.decoder_input_ids[1][0].tolist() == RO_CODE
				assert batch.decoder_input_ids[1][-1] == 2
				assert batch.labels[1][-2:].tolist() == [2, RO_CODE]


	@require_torch
	def    _a     (self							):
				A_     :						List[str]     =					self.tokenizer(
				    self.src_text	,				text_target=self.tgt_text	,				padding=lowercase	,				truncation=lowercase	,				max_length=len(self.expected_src_tokens							)	,				return_tensors="""pt"""	,				)

				A_     :						List[str]     =					shift_tokens_right(batch["""labels"""]	,				self.tokenizer.pad_token_id							)

				self.assertIsInstance(lowercase	,				lowercase							)

				self.assertEqual((2, 14)	,				batch.input_ids.shape							)
				self.assertEqual((2, 14)	,				batch.attention_mask.shape							)
				A_     :						Optional[int]     =					batch.input_ids.tolist()[0]
				self.assertListEqual(self.expected_src_tokens	,				lowercase							)
				self.assertEqual(2	,				batch.decoder_input_ids[0, -1]							)  # EOS
				# Test that special tokens are reset
				self.assertEqual(self.tokenizer.prefix_tokens	,				[]							)
				self.assertEqual(self.tokenizer.suffix_tokens	,				[self.tokenizer.eos_token_id, EN_CODE]							)


	def    _a     (self							):
				A_     :						Union[str, Any]     =					self.tokenizer(self.src_text	,				padding=lowercase	,				truncation=lowercase	,				max_length=3	,				return_tensors="""pt"""							)
				A_     :						Any     =					self.tokenizer(
				    text_target=self.tgt_text	,				padding=lowercase	,				truncation=lowercase	,				max_length=10	,				return_tensors="""pt"""							)
				A_     :						Optional[Any]     =					targets["""input_ids"""]
				A_     :						Union[str, Any]     =					shift_tokens_right(lowercase	,				self.tokenizer.pad_token_id							)

				self.assertEqual(batch.input_ids.shape[1]	,				3							)
				self.assertEqual(batch.decoder_input_ids.shape[1]	,				10							)


	@require_torch
	def    _a     (self							):
				A_     :						int     =					self.tokenizer._build_translation_inputs(
				    """A test"""	,				return_tensors="""pt"""	,				src_lang="""en_XX"""	,				tgt_lang="""ar_AR"""							)

				self.assertEqual(
				    nested_simplify(lowercase							)	,				{
				        # A, test, EOS, en_XX
				        """input_ids""": [[62, 3034, 2, 250004]],
				        """attention_mask""": [[1, 1, 1, 1]],
				        # ar_AR
				        """forced_bos_token_id""": 250001,
				    }	,				)




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

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


	def    _a     (self							):
				A_     :						str     =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]							)

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

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

				return config, pixel_values, labels


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


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


	def    _a     (self	,				lowercase	,				lowercase	,				lowercase							):
				A_     :						List[str]     =					ViTForMaskedImageModeling(config=lowercase							)
				model.to(lowercase							)
				model.eval()
				A_     :						Tuple     =					model(lowercase							)
				self.parent.assertEqual(
				    result.reconstruction.shape	,				(self.batch_size, self.num_channels, self.image_size, self.image_size)							)

				# test greyscale images
				A_     :						Union[str, Any]     =					1
				A_     :						Any     =					ViTForMaskedImageModeling(lowercase							)
				model.to(lowercase							)
				model.eval()

				A_     :						str     =					floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
				A_     :						Optional[int]     =					model(lowercase							)
				self.parent.assertEqual(result.reconstruction.shape	,				(self.batch_size, 1, self.image_size, self.image_size)							)


	def    _a     (self	,				lowercase	,				lowercase	,				lowercase							):
				A_     :						Dict     =					self.type_sequence_label_size
				A_     :						str     =					ViTForImageClassification(lowercase							)
				model.to(lowercase							)
				model.eval()
				A_     :						List[str]     =					model(lowercase	,				labels=lowercase							)
				self.parent.assertEqual(result.logits.shape	,				(self.batch_size, self.type_sequence_label_size)							)

				# test greyscale images
				A_     :						Any     =					1
				A_     :						str     =					ViTForImageClassification(lowercase							)
				model.to(lowercase							)
				model.eval()

				A_     :						Optional[int]     =					floats_tensor([self.batch_size, 1, self.image_size, self.image_size]							)
				A_     :						Union[str, Any]     =					model(lowercase							)
				self.parent.assertEqual(result.logits.shape	,				(self.batch_size, self.type_sequence_label_size)							)


	def    _a     (self							):
				A_     :						str     =					self.prepare_config_and_inputs()
				(
				    (
				    A_
				),   (
				    A_
				),   (
				    A_
				),   
				)     :						Optional[int]     =					config_and_inputs
				A_     :						Tuple     =					{"""pixel_values""": pixel_values}
				return config, inputs_dict







@require_torch
class      _lowerCAmelCase							(      __UpperCAmelCase				,      __UpperCAmelCase				,      unittest.TestCase			):
	__SCREAMING_SNAKE_CASE       :		Any		      = (
	    (
	        ViTModel,
	        ViTForImageClassification,
	        ViTForMaskedImageModeling,
	    )
	    if is_torch_available()
	    else ()
	)
	__SCREAMING_SNAKE_CASE       :		Union[str, Any]		      = (
	    {'feature-extraction': ViTModel, 'image-classification': ViTForImageClassification}
	    if is_torch_available()
	    else {}
	)
	__SCREAMING_SNAKE_CASE       :		Union[str, Any]		      = True

	__SCREAMING_SNAKE_CASE       :		Dict		      = False
	__SCREAMING_SNAKE_CASE       :		Optional[int]		      = False
	__SCREAMING_SNAKE_CASE       :		Optional[int]		      = False


	def    _a     (self							):
				A_     :						Any     =					ViTModelTester(self							)
				A_     :						str     =					ConfigTester(self	,				config_class=lowercase	,				has_text_modality=lowercase	,				hidden_size=37							)


	def    _a     (self							):
				self.config_tester.run_common_tests()


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


	def    _a     (self							):
				A_,   A_     :						Union[str, Any]     =					self.model_tester.prepare_config_and_inputs_for_common()

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


	def    _a     (self							):
				A_,   A_     :						List[Any]     =					self.model_tester.prepare_config_and_inputs_for_common()

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

							A_     :						Dict     =					["""pixel_values"""]
							self.assertListEqual(arg_names[:1]	,				lowercase							)


	def    _a     (self							):
				A_     :						Tuple     =					self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*lowercase							)


	def    _a     (self							):
				A_     :						List[Any]     =					self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_masked_image_modeling(*lowercase							)


	def    _a     (self							):
				A_     :						Dict     =					self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*lowercase							)


	@slow
	def    _a     (self							):
				for model_name in VIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							A_     :						Dict     =					ViTModel.from_pretrained(lowercase							)
							self.assertIsNotNone(lowercase							)






def      a      (			):
			'''simple docstring'''





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







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


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


	@slow
	def    _a     (self							):
				A_     :						Optional[int]     =					ViTForImageClassification.from_pretrained("""google/vit-base-patch16-224"""							).to(lowercase							)

				A_     :						List[str]     =					self.default_image_processor
				A_     :						Tuple     =					prepare_img()
				A_     :						int     =					image_processor(images=lowercase	,				return_tensors="""pt"""							).to(lowercase							)

				# forward pass
				with torch.no_grad():
							A_     :						str     =					model(**lowercase							)

				# verify the logits
				A_     :						Dict     =					torch.Size((1, 1000)							)
				self.assertEqual(outputs.logits.shape	,				lowercase							)

				A_     :						str     =					torch.tensor([-0.27_44, 0.82_15, -0.08_36]							).to(lowercase							)

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


	@slow
	def    _a     (self							):
				# 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.
				A_     :						Optional[int]     =					ViTModel.from_pretrained("""facebook/dino-vits8"""							).to(lowercase							)

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

				# forward pass
				with torch.no_grad():
							A_     :						int     =					model(lowercase	,				interpolate_pos_encoding=lowercase							)

				# verify the logits
				A_     :						int     =					torch.Size((1, 3601, 384)							)
				self.assertEqual(outputs.last_hidden_state.shape	,				lowercase							)

				A_     :						List[Any]     =					torch.tensor(
				    [[4.23_40, 4.39_06, -6.66_92], [4.54_63, 1.89_28, -6.72_57], [4.44_29, 0.84_96, -5.85_85]]							).to(lowercase							)

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


	@slow
	@require_accelerate
	@require_torch_gpu
	def    _a     (self							):
				A_     :						List[Any]     =					ViTModel.from_pretrained("""facebook/dino-vits8"""	,				torch_dtype=torch.floataa	,				device_map="""auto"""							)
				A_     :						int     =					self.default_image_processor

				A_     :						Any     =					prepare_img()
				A_     :						List[str]     =					image_processor(images=lowercase	,				return_tensors="""pt"""							)
				A_     :						Any     =					inputs.pixel_values.to(lowercase							)

				# forward pass to make sure inference works in fp16
				with torch.no_grad():
							A_     :						Optional[Any]     =					model(lowercase							)