

import inspect
import unittest

from datasets import load_dataset
from packaging import version

from transformers import BeitConfig
from transformers.models.auto import get_values
from transformers.testing_utils import require_torch, require_torch_multi_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, _config_zero_init, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
					import torch
					from torch import nn

					from transformers import (
					    MODEL_MAPPING,
					    BeitForImageClassification,
					    BeitForMaskedImageModeling,
					    BeitForSemanticSegmentation,
					    BeitModel,
					)
					from transformers.models.beit.modeling_beit import BEIT_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
					import PIL
					from PIL import Image

					from transformers import BeitImageProcessor






class 	A_		:
							def __init__(		self		:      str       ,SCREAMING_SNAKE_CASE__		:      Optional[int]       ,SCREAMING_SNAKE_CASE__		:      List[str]=1_0_0       ,SCREAMING_SNAKE_CASE__		:      Union[str, Any]=1_3       ,SCREAMING_SNAKE_CASE__		:      List[str]=3_0       ,SCREAMING_SNAKE_CASE__		:      Tuple=2       ,SCREAMING_SNAKE_CASE__		:      Optional[int]=3       ,SCREAMING_SNAKE_CASE__		:      Union[str, Any]=True       ,SCREAMING_SNAKE_CASE__		:      List[Any]=True       ,SCREAMING_SNAKE_CASE__		:      Optional[Any]=3_2       ,SCREAMING_SNAKE_CASE__		:      List[str]=4       ,SCREAMING_SNAKE_CASE__		:      Optional[Any]=4       ,SCREAMING_SNAKE_CASE__		:      int=3_7       ,SCREAMING_SNAKE_CASE__		:      Any="gelu"       ,SCREAMING_SNAKE_CASE__		:      Any=0.1       ,SCREAMING_SNAKE_CASE__		:      Dict=0.1       ,SCREAMING_SNAKE_CASE__		:      Dict=1_0       ,SCREAMING_SNAKE_CASE__		:      List[Any]=0.02       ,SCREAMING_SNAKE_CASE__		:      Union[str, Any]=3       ,SCREAMING_SNAKE_CASE__		:      Optional[int]=None       ,SCREAMING_SNAKE_CASE__		:      Dict=[0, 1, 2, 3]       ,):
								__lowerCamelCase    :    Union[str, Any] 	=			parent
								__lowerCamelCase    :    Any 	=			1_0_0
								__lowerCamelCase    :    Optional[int] 	=			batch_size
								__lowerCamelCase    :    str 	=			image_size
								__lowerCamelCase    :    List[Any] 	=			patch_size
								__lowerCamelCase    :    Optional[Any] 	=			num_channels
								__lowerCamelCase    :    Any 	=			is_training
								__lowerCamelCase    :    List[Any] 	=			use_labels
								__lowerCamelCase    :    str 	=			hidden_size
								__lowerCamelCase    :    Tuple 	=			num_hidden_layers
								__lowerCamelCase    :    Union[str, Any] 	=			num_attention_heads
								__lowerCamelCase    :    Dict 	=			intermediate_size
								__lowerCamelCase    :    int 	=			hidden_act
								__lowerCamelCase    :    Any 	=			hidden_dropout_prob
								__lowerCamelCase    :    Tuple 	=			attention_probs_dropout_prob
								__lowerCamelCase    :    List[Any] 	=			type_sequence_label_size
								__lowerCamelCase    :    Optional[Any] 	=			initializer_range
								__lowerCamelCase    :    List[Any] 	=			scope
								__lowerCamelCase    :    int 	=			out_indices
								__lowerCamelCase    :    int 	=			num_labels

								# in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
								__lowerCamelCase    :    Union[str, Any] 	=			(image_size // patch_size) ** 2
								__lowerCamelCase    :    Optional[Any] 	=			num_patches + 1
							def    lowerCAmelCase					(		self		:      Dict):
								__lowerCamelCase    :    Optional[int] 	=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

								__lowerCamelCase    :    Union[str, Any] 	=			None
								__lowerCamelCase    :    List[Any] 	=			None
								if self.use_labels:
									__lowerCamelCase    :    Tuple 	=			ids_tensor([self.batch_size]       ,self.type_sequence_label_size)
									__lowerCamelCase    :    List[Any] 	=			ids_tensor([self.batch_size, self.image_size, self.image_size]       ,self.num_labels)

								__lowerCamelCase    :    Optional[int] 	=			self.get_config()

								return config, pixel_values, labels, pixel_labels
							def    lowerCAmelCase					(		self		:      Dict):
								return BeitConfig(
								    vocab_size=self.vocab_size       ,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=SCREAMING_SNAKE_CASE__       ,initializer_range=self.initializer_range       ,out_indices=self.out_indices       ,)
							def    lowerCAmelCase					(		self		:      List[str]       ,SCREAMING_SNAKE_CASE__		:      List[str]       ,SCREAMING_SNAKE_CASE__		:      Optional[Any]       ,SCREAMING_SNAKE_CASE__		:      Optional[int]       ,SCREAMING_SNAKE_CASE__		:      int):
								__lowerCamelCase    :    str 	=			BeitModel(config=SCREAMING_SNAKE_CASE__)
								model.to(SCREAMING_SNAKE_CASE__)
								model.eval()
								__lowerCamelCase    :    Optional[Any] 	=			model(SCREAMING_SNAKE_CASE__)
								self.parent.assertEqual(result.last_hidden_state.shape       ,(self.batch_size, self.seq_length, self.hidden_size))
							def    lowerCAmelCase					(		self		:      Optional[Any]       ,SCREAMING_SNAKE_CASE__		:      List[Any]       ,SCREAMING_SNAKE_CASE__		:      List[str]       ,SCREAMING_SNAKE_CASE__		:      str       ,SCREAMING_SNAKE_CASE__		:      List[Any]):
								__lowerCamelCase    :    Dict 	=			BeitForMaskedImageModeling(config=SCREAMING_SNAKE_CASE__)
								model.to(SCREAMING_SNAKE_CASE__)
								model.eval()
								__lowerCamelCase    :    Any 	=			model(SCREAMING_SNAKE_CASE__)
								self.parent.assertEqual(result.logits.shape       ,(self.batch_size, self.seq_length - 1, self.vocab_size))
							def    lowerCAmelCase					(		self		:      int       ,SCREAMING_SNAKE_CASE__		:      Any       ,SCREAMING_SNAKE_CASE__		:      Dict       ,SCREAMING_SNAKE_CASE__		:      Optional[Any]       ,SCREAMING_SNAKE_CASE__		:      Tuple):
								__lowerCamelCase    :    List[str] 	=			self.type_sequence_label_size
								__lowerCamelCase    :    Optional[Any] 	=			BeitForImageClassification(SCREAMING_SNAKE_CASE__)
								model.to(SCREAMING_SNAKE_CASE__)
								model.eval()
								__lowerCamelCase    :    int 	=			model(SCREAMING_SNAKE_CASE__       ,labels=SCREAMING_SNAKE_CASE__)
								self.parent.assertEqual(result.logits.shape       ,(self.batch_size, self.type_sequence_label_size))

								# test greyscale images
								__lowerCamelCase    :    str 	=			1
								__lowerCamelCase    :    Tuple 	=			BeitForImageClassification(SCREAMING_SNAKE_CASE__)
								model.to(SCREAMING_SNAKE_CASE__)
								model.eval()

								__lowerCamelCase    :    Tuple 	=			floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
								__lowerCamelCase    :    Any 	=			model(SCREAMING_SNAKE_CASE__       ,labels=SCREAMING_SNAKE_CASE__)
								self.parent.assertEqual(result.logits.shape       ,(self.batch_size, self.type_sequence_label_size))
							def    lowerCAmelCase					(		self		:      int       ,SCREAMING_SNAKE_CASE__		:      int       ,SCREAMING_SNAKE_CASE__		:      Optional[int]       ,SCREAMING_SNAKE_CASE__		:      Optional[int]       ,SCREAMING_SNAKE_CASE__		:      Tuple):
								__lowerCamelCase    :    Any 	=			self.num_labels
								__lowerCamelCase    :    Tuple 	=			BeitForSemanticSegmentation(SCREAMING_SNAKE_CASE__)
								model.to(SCREAMING_SNAKE_CASE__)
								model.eval()
								__lowerCamelCase    :    List[Any] 	=			model(SCREAMING_SNAKE_CASE__)
								self.parent.assertEqual(
								    result.logits.shape       ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2))
								__lowerCamelCase    :    int 	=			model(SCREAMING_SNAKE_CASE__       ,labels=SCREAMING_SNAKE_CASE__)
								self.parent.assertEqual(
								    result.logits.shape       ,(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2))


							def    lowerCAmelCase					(		self		:      List[Any]):
								__lowerCamelCase    :    int 	=			self.prepare_config_and_inputs()
								__lowerCamelCase	,			__lowerCamelCase	,			__lowerCamelCase	,			__lowerCamelCase    :    Dict 	=			config_and_inputs
								__lowerCamelCase    :    int 	=			{'pixel_values': pixel_values}
								return config, inputs_dict






@require_torch
class 	A_		(	SCREAMING_SNAKE_CASE      ,							SCREAMING_SNAKE_CASE      ,							unittest.TestCase    ):
							_UpperCAmelCase   :  Union[str, Any]										=				(
							    (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
							    if is_torch_available()
							    else ()
							)
							_UpperCAmelCase   :  Union[str, Any]										=				(
							    {
							        '''feature-extraction''': BeitModel,
							        '''image-classification''': BeitForImageClassification,
							        '''image-segmentation''': BeitForSemanticSegmentation,
							    }
							    if is_torch_available()
							    else {}
							)

							_UpperCAmelCase   :  str										=				False
							_UpperCAmelCase   :  Tuple										=				False
							_UpperCAmelCase   :  List[str]										=				False
							def    lowerCAmelCase					(		self		:      Any):
								__lowerCamelCase    :    Dict 	=			BeitModelTester(self)
								__lowerCamelCase    :    Tuple 	=			ConfigTester(self       ,config_class=SCREAMING_SNAKE_CASE__       ,has_text_modality=SCREAMING_SNAKE_CASE__       ,hidden_size=3_7)
							def    lowerCAmelCase					(		self		:      Tuple):
								self.config_tester.run_common_tests()
							@unittest.skip(reason='BEiT does not use inputs_embeds')
							def    lowerCAmelCase					(		self		:      Any):
								pass
							@require_torch_multi_gpu
							@unittest.skip(reason='BEiT has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`')
							def    lowerCAmelCase					(		self		:      Any):
								pass
							def    lowerCAmelCase					(		self		:      Optional[int]):
								__lowerCamelCase	,			__lowerCamelCase    :    Optional[Any] 	=			self.model_tester.prepare_config_and_inputs_for_common()

								for model_class in self.all_model_classes:
									__lowerCamelCase    :    Optional[Any] 	=			model_class(SCREAMING_SNAKE_CASE__)
									self.assertIsInstance(model.get_input_embeddings()       ,(nn.Module))
									__lowerCamelCase    :    Optional[Any] 	=			model.get_output_embeddings()
									self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__       ,nn.Linear))
							def    lowerCAmelCase					(		self		:      Optional[Any]):
								__lowerCamelCase	,			__lowerCamelCase    :    Union[str, Any] 	=			self.model_tester.prepare_config_and_inputs_for_common()

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

									__lowerCamelCase    :    List[Any] 	=			['pixel_values']
									self.assertListEqual(arg_names[:1]       ,SCREAMING_SNAKE_CASE__)
							def    lowerCAmelCase					(		self		:      List[Any]):
								__lowerCamelCase    :    List[Any] 	=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__)
							def    lowerCAmelCase					(		self		:      str):
								__lowerCamelCase    :    Optional[int] 	=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE__)
							def    lowerCAmelCase					(		self		:      Optional[int]):
								__lowerCamelCase    :    str 	=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__)
							def    lowerCAmelCase					(		self		:      List[str]):
								__lowerCamelCase    :    Dict 	=			self.model_tester.prepare_config_and_inputs()
								self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE__)
							def    lowerCAmelCase					(		self		:      Optional[int]):
								if not self.model_tester.is_training:
									return

								__lowerCamelCase	,			__lowerCamelCase    :    str 	=			self.model_tester.prepare_config_and_inputs_for_common()
								__lowerCamelCase    :    int 	=			True

								for model_class in self.all_model_classes:
									# we don't test BeitForMaskedImageModeling
									if model_class in [*get_values(SCREAMING_SNAKE_CASE__), BeitForMaskedImageModeling]:
										continue

									__lowerCamelCase    :    List[str] 	=			model_class(SCREAMING_SNAKE_CASE__)
									model.to(SCREAMING_SNAKE_CASE__)
									model.train()
									__lowerCamelCase    :    Union[str, Any] 	=			self._prepare_for_class(SCREAMING_SNAKE_CASE__       ,SCREAMING_SNAKE_CASE__       ,return_labels=SCREAMING_SNAKE_CASE__)
									__lowerCamelCase    :    Optional[Any] 	=			model(**SCREAMING_SNAKE_CASE__).loss
									loss.backward()
							def    lowerCAmelCase					(		self		:      Dict):
								__lowerCamelCase	,			__lowerCamelCase    :    Optional[Any] 	=			self.model_tester.prepare_config_and_inputs_for_common()
								if not self.model_tester.is_training:
									return

								__lowerCamelCase    :    int 	=			False
								__lowerCamelCase    :    int 	=			True

								for model_class in self.all_model_classes:
									# we don't test BeitForMaskedImageModeling
									if (
									    model_class in [*get_values(SCREAMING_SNAKE_CASE__), BeitForMaskedImageModeling]
									    or not model_class.supports_gradient_checkpointing
									):
										continue

									__lowerCamelCase    :    Union[str, Any] 	=			model_class(SCREAMING_SNAKE_CASE__)
									model.gradient_checkpointing_enable()
									model.to(SCREAMING_SNAKE_CASE__)
									model.train()
									__lowerCamelCase    :    List[str] 	=			self._prepare_for_class(SCREAMING_SNAKE_CASE__       ,SCREAMING_SNAKE_CASE__       ,return_labels=SCREAMING_SNAKE_CASE__)
									__lowerCamelCase    :    List[str] 	=			model(**SCREAMING_SNAKE_CASE__).loss
									loss.backward()
							def    lowerCAmelCase					(		self		:      List[str]):
								__lowerCamelCase	,			__lowerCamelCase    :    Tuple 	=			self.model_tester.prepare_config_and_inputs_for_common()

								__lowerCamelCase    :    Any 	=			_config_zero_init(SCREAMING_SNAKE_CASE__)
								for model_class in self.all_model_classes:
									__lowerCamelCase    :    List[Any] 	=			model_class(config=SCREAMING_SNAKE_CASE__)
									for name, param in model.named_parameters():
										# we skip lambda parameters as these require special initial values
										# determined by config.layer_scale_init_value
										if "lambda" in name:
											continue
										if param.requires_grad:
											self.assertIn(
											    ((param.data.mean() * 1E9).round() / 1E9).item()       ,[0.0, 1.0]       ,msg=F"Parameter {name} of model {model_class} seems not properly initialized"       ,)


							@slow
							def    lowerCAmelCase					(		self		:      Optional[int]):
								for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									__lowerCamelCase    :    Dict 	=			BeitModel.from_pretrained(SCREAMING_SNAKE_CASE__)
									self.assertIsNotNone(SCREAMING_SNAKE_CASE__)






def        SCREAMING_SNAKE_CASE__	(  )  ->					List[str]:
	__lowerCamelCase    :    str 	=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
	return image






@require_torch
@require_vision
class 	A_		(	unittest.TestCase    ):
							@cached_property
							def    lowerCAmelCase					(		self		:      Any):
								return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224') if is_vision_available() else None
							@slow
							def    lowerCAmelCase					(		self		:      str):
								__lowerCamelCase    :    Union[str, Any] 	=			BeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k').to(SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Tuple 	=			self.default_image_processor
								__lowerCamelCase    :    Union[str, Any] 	=			prepare_img()
								__lowerCamelCase    :    Dict 	=			image_processor(images=SCREAMING_SNAKE_CASE__       ,return_tensors='pt').pixel_values.to(SCREAMING_SNAKE_CASE__)

								# prepare bool_masked_pos
								__lowerCamelCase    :    int 	=			torch.ones((1, 1_9_6)       ,dtype=torch.bool).to(SCREAMING_SNAKE_CASE__)

								# forward pass
								with torch.no_grad():
									__lowerCamelCase    :    Tuple 	=			model(pixel_values=SCREAMING_SNAKE_CASE__       ,bool_masked_pos=SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Optional[int] 	=			outputs.logits

								# verify the logits
								__lowerCamelCase    :    str 	=			torch.Size((1, 1_9_6, 8_1_9_2))
								self.assertEqual(logits.shape       ,SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Tuple 	=			torch.tensor(
								    [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]]).to(SCREAMING_SNAKE_CASE__)

								self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3]       ,SCREAMING_SNAKE_CASE__       ,atol=1E-2))
							@slow
							def    lowerCAmelCase					(		self		:      str):
								__lowerCamelCase    :    Optional[int] 	=			BeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224').to(SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Tuple 	=			self.default_image_processor
								__lowerCamelCase    :    Union[str, Any] 	=			prepare_img()
								__lowerCamelCase    :    Optional[Any] 	=			image_processor(images=SCREAMING_SNAKE_CASE__       ,return_tensors='pt').to(SCREAMING_SNAKE_CASE__)

								# forward pass
								with torch.no_grad():
									__lowerCamelCase    :    Tuple 	=			model(**SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    List[Any] 	=			outputs.logits

								# verify the logits
								__lowerCamelCase    :    List[str] 	=			torch.Size((1, 1_0_0_0))
								self.assertEqual(logits.shape       ,SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    List[str] 	=			torch.tensor([-1.2385, -1.0987, -1.0108]).to(SCREAMING_SNAKE_CASE__)

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

								__lowerCamelCase    :    Optional[int] 	=			2_8_1
								self.assertEqual(logits.argmax(-1).item()       ,SCREAMING_SNAKE_CASE__)
							@slow
							def    lowerCAmelCase					(		self		:      str):
								__lowerCamelCase    :    Optional[Any] 	=			BeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k').to(
								    SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    str 	=			self.default_image_processor
								__lowerCamelCase    :    Optional[Any] 	=			prepare_img()
								__lowerCamelCase    :    Tuple 	=			image_processor(images=SCREAMING_SNAKE_CASE__       ,return_tensors='pt').to(SCREAMING_SNAKE_CASE__)

								# forward pass
								with torch.no_grad():
									__lowerCamelCase    :    Tuple 	=			model(**SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    List[Any] 	=			outputs.logits

								# verify the logits
								__lowerCamelCase    :    Tuple 	=			torch.Size((1, 2_1_8_4_1))
								self.assertEqual(logits.shape       ,SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Dict 	=			torch.tensor([1.6881, -0.2787, 0.5901]).to(SCREAMING_SNAKE_CASE__)

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

								__lowerCamelCase    :    List[Any] 	=			2_3_9_6
								self.assertEqual(logits.argmax(-1).item()       ,SCREAMING_SNAKE_CASE__)
							@slow
							def    lowerCAmelCase					(		self		:      Optional[int]):
								__lowerCamelCase    :    Union[str, Any] 	=			BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640')
								__lowerCamelCase    :    Dict 	=			model.to(SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Dict 	=			BeitImageProcessor(do_resize=SCREAMING_SNAKE_CASE__       ,size=6_4_0       ,do_center_crop=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Union[str, Any] 	=			load_dataset('hf-internal-testing/fixtures_ade20k'       ,split='test')
								__lowerCamelCase    :    Optional[int] 	=			Image.open(ds[0]['file'])
								__lowerCamelCase    :    int 	=			image_processor(images=SCREAMING_SNAKE_CASE__       ,return_tensors='pt').to(SCREAMING_SNAKE_CASE__)

								# forward pass
								with torch.no_grad():
									__lowerCamelCase    :    List[str] 	=			model(**SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    Any 	=			outputs.logits

								# verify the logits
								__lowerCamelCase    :    Tuple 	=			torch.Size((1, 1_5_0, 1_6_0, 1_6_0))
								self.assertEqual(logits.shape       ,SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Optional[Any] 	=			version.parse(PIL.__version__) < version.parse('9.0.0')

								if is_pillow_less_than_a:
									__lowerCamelCase    :    Tuple 	=			torch.tensor(
									    [
									        [[-4.9225, -2.3954, -3.0522], [-2.8822, -1.0046, -1.7561], [-2.9549, -1.3228, -2.1347]],
									        [[-5.8168, -3.4129, -4.0778], [-3.8651, -2.2214, -3.0277], [-3.8356, -2.4643, -3.3535]],
									        [[-0.0078, 3.9952, 4.0754], [2.9856, 4.6944, 5.0035], [3.2413, 4.7813, 4.9969]],
									    ]       ,device=SCREAMING_SNAKE_CASE__       ,)
								else:
									__lowerCamelCase    :    Optional[int] 	=			torch.tensor(
									    [
									        [[-4.8960, -2.3688, -3.0355], [-2.8478, -0.9836, -1.7418], [-2.9449, -1.3332, -2.1456]],
									        [[-5.8081, -3.4124, -4.1006], [-3.8561, -2.2081, -3.0323], [-3.8365, -2.4601, -3.3669]],
									        [[-0.0309, 3.9868, 4.0540], [2.9640, 4.6877, 4.9976], [3.2081, 4.7690, 4.9942]],
									    ]       ,device=SCREAMING_SNAKE_CASE__       ,)

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


							@slow
							def    lowerCAmelCase					(		self		:      Optional[Any]):
								__lowerCamelCase    :    str 	=			BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640')
								__lowerCamelCase    :    Optional[Any] 	=			model.to(SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Union[str, Any] 	=			BeitImageProcessor(do_resize=SCREAMING_SNAKE_CASE__       ,size=6_4_0       ,do_center_crop=SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Any 	=			load_dataset('hf-internal-testing/fixtures_ade20k'       ,split='test')
								__lowerCamelCase    :    str 	=			Image.open(ds[0]['file'])
								__lowerCamelCase    :    Optional[int] 	=			image_processor(images=SCREAMING_SNAKE_CASE__       ,return_tensors='pt').to(SCREAMING_SNAKE_CASE__)

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

								__lowerCamelCase    :    List[Any] 	=			outputs.logits.detach().cpu()

								__lowerCamelCase    :    List[Any] 	=			image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE__       ,target_sizes=[(5_0_0, 3_0_0)])
								__lowerCamelCase    :    Optional[Any] 	=			torch.Size((5_0_0, 3_0_0))
								self.assertEqual(segmentation[0].shape       ,SCREAMING_SNAKE_CASE__)

								__lowerCamelCase    :    Dict 	=			image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    List[str] 	=			torch.Size((1_6_0, 1_6_0))
								self.assertEqual(segmentation[0].shape       ,SCREAMING_SNAKE_CASE__)







from __future__ import annotations

from collections.abc import Callable
from typing import Generic, TypeVar

a		=TypeVar("""T""")
a		=TypeVar("""U""")






class 	A_		(	Generic[T, U]    ):
							def __init__(		self		:      Tuple       ,SCREAMING_SNAKE_CASE__		:      T | None       ,SCREAMING_SNAKE_CASE__		:      U | None):
								__lowerCamelCase    :    Optional[Any] 	=			key
								__lowerCamelCase    :    Tuple 	=			val
								__lowerCamelCase    :    DoubleLinkedListNode[T, U] | None 	=			None
								__lowerCamelCase    :    DoubleLinkedListNode[T, U] | None 	=			None


							def __repr__(		self		:      Optional[int]):
								return (
								    F"Node: key: {self.key}, val: {self.val}, "
								    F"has next: {bool(self.next)}, has prev: {bool(self.prev)}"
								)






class 	A_		(	Generic[T, U]    ):
							def __init__(		self		:      List[Any]):
								__lowerCamelCase    :    DoubleLinkedListNode[T, U] 	=			DoubleLinkedListNode(SCREAMING_SNAKE_CASE__       ,SCREAMING_SNAKE_CASE__)
								__lowerCamelCase    :    DoubleLinkedListNode[T, U] 	=			DoubleLinkedListNode(SCREAMING_SNAKE_CASE__       ,SCREAMING_SNAKE_CASE__)
								__lowerCamelCase	,			__lowerCamelCase    :    List[Any] 	=			self.rear, self.head
							def __repr__(		self		:      Optional[int]):
								__lowerCamelCase    :    int 	=			['DoubleLinkedList']
								__lowerCamelCase    :    Tuple 	=			self.head
								while node.next is not None:
									rep.append(str(SCREAMING_SNAKE_CASE__))
									__lowerCamelCase    :    Union[str, Any] 	=			node.next
								rep.append(str(self.rear))
								return ",\n    ".join(SCREAMING_SNAKE_CASE__)
							def    lowerCAmelCase					(		self		:      Optional[Any]       ,SCREAMING_SNAKE_CASE__		:      DoubleLinkedListNode[T, U]):
								__lowerCamelCase    :    str 	=			self.rear.prev

								# All nodes other than self.head are guaranteed to have non-None previous
								assert previous is not None

								__lowerCamelCase    :    Any 	=			node
								__lowerCamelCase    :    str 	=			previous
								__lowerCamelCase    :    str 	=			node
								__lowerCamelCase    :    List[str] 	=			self.rear


							def    lowerCAmelCase					(		self		:      int       ,SCREAMING_SNAKE_CASE__		:      DoubleLinkedListNode[T, U]):

								if node.prev is None or node.next is None:
									return None

								__lowerCamelCase    :    Union[str, Any] 	=			node.next
								__lowerCamelCase    :    Dict 	=			node.prev
								__lowerCamelCase    :    Optional[int] 	=			None
								__lowerCamelCase    :    List[str] 	=			None
								return node






class 	A_		(	Generic[T, U]    ):
							_UpperCAmelCase   :  dict[Callable[[T], U], LRUCache[T, U]]										=				{}
							def __init__(		self		:      str       ,SCREAMING_SNAKE_CASE__		:      int):
								__lowerCamelCase    :    DoubleLinkedList[T, U] 	=			DoubleLinkedList()
								__lowerCamelCase    :    List[Any] 	=			capacity
								__lowerCamelCase    :    Optional[int] 	=			0
								__lowerCamelCase    :    int 	=			0
								__lowerCamelCase    :    Optional[Any] 	=			0
								__lowerCamelCase    :    dict[T, DoubleLinkedListNode[T, U]] 	=			{}
							def __repr__(		self		:      Optional[Any]):
								return (
								    F"CacheInfo(hits={self.hits}, misses={self.miss}, "
								    F"capacity={self.capacity}, current size={self.num_keys})"
								)
							def __contains__(		self		:      List[str]       ,SCREAMING_SNAKE_CASE__		:      T):
								return key in self.cache
							def    lowerCAmelCase					(		self		:      Union[str, Any]       ,SCREAMING_SNAKE_CASE__		:      T):
								# Note: pythonic interface would throw KeyError rather than return None

								if key in self.cache:
									self.hits += 1
									__lowerCamelCase    :    DoubleLinkedListNode[T, U] 	=			self.cache[key]
									__lowerCamelCase    :    List[str] 	=			self.list.remove(self.cache[key])
									assert node == value_node

									# node is guaranteed not None because it is in self.cache
									assert node is not None
									self.list.add(SCREAMING_SNAKE_CASE__)
									return node.val
								self.miss += 1
								return None
							def    lowerCAmelCase					(		self		:      Dict       ,SCREAMING_SNAKE_CASE__		:      T       ,SCREAMING_SNAKE_CASE__		:      U):

								if key not in self.cache:
									if self.num_keys >= self.capacity:
										# delete first node (oldest) when over capacity
										__lowerCamelCase    :    Optional[Any] 	=			self.list.head.next

										# guaranteed to have a non-None first node when num_keys > 0
										# explain to type checker via assertions
										assert first_node is not None
										assert first_node.key is not None
										assert (
										    self.list.remove(SCREAMING_SNAKE_CASE__) is not None
										)  # node guaranteed to be in list assert node.key is not None

										del self.cache[first_node.key]
										self.num_keys -= 1
									__lowerCamelCase    :    List[Any] 	=			DoubleLinkedListNode(SCREAMING_SNAKE_CASE__       ,SCREAMING_SNAKE_CASE__)
									self.list.add(self.cache[key])
									self.num_keys += 1

								else:
									# bump node to the end of the list, update value
									__lowerCamelCase    :    List[str] 	=			self.list.remove(self.cache[key])
									assert node is not None  # node guaranteed to be in list
									__lowerCamelCase    :    List[Any] 	=			value
									self.list.add(SCREAMING_SNAKE_CASE__)


							@classmethod
							def    lowerCAmelCase					(		cls		:      Optional[int]       ,SCREAMING_SNAKE_CASE__		:      int = 1_2_8):

								def cache_decorator_inner(SCREAMING_SNAKE_CASE__		:      Callable[[T], U]) -> Callable[..., U]:
									def cache_decorator_wrapper(*SCREAMING_SNAKE_CASE__		:      T) -> U:
										if func not in cls.decorator_function_to_instance_map:
											__lowerCamelCase    :    str 	=			LRUCache(SCREAMING_SNAKE_CASE__)

										__lowerCamelCase    :    Dict 	=			cls.decorator_function_to_instance_map[func].get(args[0])
										if result is None:
											__lowerCamelCase    :    str 	=			func(*SCREAMING_SNAKE_CASE__)
											cls.decorator_function_to_instance_map[func].put(args[0]       ,SCREAMING_SNAKE_CASE__)
										return result

									def cache_info() -> LRUCache[T, U]:
										return cls.decorator_function_to_instance_map[func]

									setattr(SCREAMING_SNAKE_CASE__       ,'cache_info'       ,SCREAMING_SNAKE_CASE__)  # noqa: B010

									return cache_decorator_wrapper

								return cache_decorator_inner


if __name__ == "__main__":
					import doctest

					doctest.testmod()




