
"""simple docstring"""




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 			lowerCAmelCase_		:


				"""simple docstring"""



				def __init__(self     , SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__=1_00     , SCREAMING_SNAKE_CASE__=13     , SCREAMING_SNAKE_CASE__=30     , SCREAMING_SNAKE_CASE__=2     , SCREAMING_SNAKE_CASE__=3     , SCREAMING_SNAKE_CASE__=True     , SCREAMING_SNAKE_CASE__=True     , SCREAMING_SNAKE_CASE__=32     , SCREAMING_SNAKE_CASE__=4     , SCREAMING_SNAKE_CASE__=4     , SCREAMING_SNAKE_CASE__=37     , SCREAMING_SNAKE_CASE__="gelu"     , SCREAMING_SNAKE_CASE__=0.1     , SCREAMING_SNAKE_CASE__=0.1     , SCREAMING_SNAKE_CASE__=10     , SCREAMING_SNAKE_CASE__=0.02     , SCREAMING_SNAKE_CASE__=3     , SCREAMING_SNAKE_CASE__=None     , SCREAMING_SNAKE_CASE__=[0, 1, 2, 3]     , )      ->	Any:



											"""simple docstring"""




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

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



				def 			__magic_name__					(self					)      ->	Union[str, Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Dict     =     floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]					)

											SCREAMING_SNAKE_CASE__		: Dict     =     None
											SCREAMING_SNAKE_CASE__		: Dict     =     None
											if self.use_labels:
																		SCREAMING_SNAKE_CASE__		: Dict     =     ids_tensor([self.batch_size]     , self.type_sequence_label_size					)
																		SCREAMING_SNAKE_CASE__		: int     =     ids_tensor([self.batch_size, self.image_size, self.image_size]     , self.num_labels					)

											SCREAMING_SNAKE_CASE__		: Dict     =     self.get_config()

											return config, pixel_values, labels, pixel_labels



				def 			__magic_name__					(self					)      ->	Any:



											"""simple docstring"""




											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 			__magic_name__					(self     , SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__					)      ->	Optional[Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Dict     =     BeitModel(config=SCREAMING_SNAKE_CASE__					)
											model.to(SCREAMING_SNAKE_CASE__					)
											model.eval()
											SCREAMING_SNAKE_CASE__		: Optional[int]     =     model(SCREAMING_SNAKE_CASE__					)
											self.parent.assertEqual(result.last_hidden_state.shape     , (self.batch_size, self.seq_length, self.hidden_size)					)



				def 			__magic_name__					(self     , SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__					)      ->	List[Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Any     =     BeitForMaskedImageModeling(config=SCREAMING_SNAKE_CASE__					)
											model.to(SCREAMING_SNAKE_CASE__					)
											model.eval()
											SCREAMING_SNAKE_CASE__		: Dict     =     model(SCREAMING_SNAKE_CASE__					)
											self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.seq_length - 1, self.vocab_size)					)



				def 			__magic_name__					(self     , SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__					)      ->	Optional[int]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Dict     =     self.type_sequence_label_size
											SCREAMING_SNAKE_CASE__		: int     =     BeitForImageClassification(SCREAMING_SNAKE_CASE__					)
											model.to(SCREAMING_SNAKE_CASE__					)
											model.eval()
											SCREAMING_SNAKE_CASE__		: Any     =     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
											SCREAMING_SNAKE_CASE__		: str     =     1
											SCREAMING_SNAKE_CASE__		: str     =     BeitForImageClassification(SCREAMING_SNAKE_CASE__					)
											model.to(SCREAMING_SNAKE_CASE__					)
											model.eval()

											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     floats_tensor([self.batch_size, 1, self.image_size, self.image_size]					)
											SCREAMING_SNAKE_CASE__		: str     =     model(SCREAMING_SNAKE_CASE__     , labels=SCREAMING_SNAKE_CASE__					)
											self.parent.assertEqual(result.logits.shape     , (self.batch_size, self.type_sequence_label_size)					)



				def 			__magic_name__					(self     , SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__					)      ->	Union[str, Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Optional[int]     =     self.num_labels
											SCREAMING_SNAKE_CASE__		: List[Any]     =     BeitForSemanticSegmentation(SCREAMING_SNAKE_CASE__					)
											model.to(SCREAMING_SNAKE_CASE__					)
											model.eval()
											SCREAMING_SNAKE_CASE__		: Dict     =     model(SCREAMING_SNAKE_CASE__					)
											self.parent.assertEqual(
											    result.logits.shape     , (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)					)
											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     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 			__magic_name__					(self					)      ->	Union[str, Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: int     =     self.prepare_config_and_inputs()
											SCREAMING_SNAKE_CASE__   ,   SCREAMING_SNAKE_CASE__   ,   SCREAMING_SNAKE_CASE__   ,   SCREAMING_SNAKE_CASE__		: int     =     config_and_inputs
											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     {"""pixel_values""": pixel_values}
											return config, inputs_dict






@require_torch
class 			lowerCAmelCase_		(a__				,      a__				,      unittest.TestCase						):


				"""simple docstring"""



				__UpperCamelCase   :		Dict       =     (
				    (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
				    if is_torch_available()
				    else ()
				)
				__UpperCamelCase   :		Optional[Any]       =     (
				    {
				        '''feature-extraction''': BeitModel,
				        '''image-classification''': BeitForImageClassification,
				        '''image-segmentation''': BeitForSemanticSegmentation,
				    }
				    if is_torch_available()
				    else {}
				)

				__UpperCamelCase   :		Union[str, Any]       =     False
				__UpperCamelCase   :		Optional[int]       =     False
				__UpperCamelCase   :		Dict       =     False



				def 			__magic_name__					(self					)      ->	str:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Optional[int]     =     BeitModelTester(self					)
											SCREAMING_SNAKE_CASE__		: List[Any]     =     ConfigTester(self     , config_class=SCREAMING_SNAKE_CASE__     , has_text_modality=SCREAMING_SNAKE_CASE__     , hidden_size=37					)



				def 			__magic_name__					(self					)      ->	Any:



											"""simple docstring"""




											self.config_tester.run_common_tests()



				@unittest.skip(reason="""BEiT does not use inputs_embeds"""					)
				def 			__magic_name__					(self					)      ->	Tuple:



											"""simple docstring"""




											pass



				@require_torch_multi_gpu
				@unittest.skip(reason="""BEiT has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""					)
				def 			__magic_name__					(self					)      ->	Any:



											"""simple docstring"""




											pass



				def 			__magic_name__					(self					)      ->	List[Any]:



											"""simple docstring"""




											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__		: Tuple     =     model_class(SCREAMING_SNAKE_CASE__					)
																		self.assertIsInstance(model.get_input_embeddings()     , (nn.Module)					)
																		SCREAMING_SNAKE_CASE__		: Any     =     model.get_output_embeddings()
																		self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__     , nn.Linear					)					)



				def 			__magic_name__					(self					)      ->	Any:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__   ,   SCREAMING_SNAKE_CASE__		: Tuple     =     self.model_tester.prepare_config_and_inputs_for_common()

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

																		SCREAMING_SNAKE_CASE__		: List[str]     =     ["""pixel_values"""]
																		self.assertListEqual(arg_names[:1]     , SCREAMING_SNAKE_CASE__					)



				def 			__magic_name__					(self					)      ->	List[Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Optional[int]     =     self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__					)



				def 			__magic_name__					(self					)      ->	int:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE__					)



				def 			__magic_name__					(self					)      ->	List[Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Tuple     =     self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__					)



				def 			__magic_name__					(self					)      ->	Union[str, Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: str     =     self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE__					)



				def 			__magic_name__					(self					)      ->	int:



											"""simple docstring"""




											if not self.model_tester.is_training:
																		return

											SCREAMING_SNAKE_CASE__   ,   SCREAMING_SNAKE_CASE__		: int     =     self.model_tester.prepare_config_and_inputs_for_common()
											SCREAMING_SNAKE_CASE__		: Tuple     =     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

																		SCREAMING_SNAKE_CASE__		: Tuple     =     model_class(SCREAMING_SNAKE_CASE__					)
																		model.to(SCREAMING_SNAKE_CASE__					)
																		model.train()
																		SCREAMING_SNAKE_CASE__		: str     =     self._prepare_for_class(SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__     , return_labels=SCREAMING_SNAKE_CASE__					)
																		SCREAMING_SNAKE_CASE__		: List[str]     =     model(**SCREAMING_SNAKE_CASE__					).loss
																		loss.backward()



				def 			__magic_name__					(self					)      ->	Optional[Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__   ,   SCREAMING_SNAKE_CASE__		: Optional[Any]     =     self.model_tester.prepare_config_and_inputs_for_common()
											if not self.model_tester.is_training:
																		return

											SCREAMING_SNAKE_CASE__		: Dict     =     False
											SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     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

																		SCREAMING_SNAKE_CASE__		: int     =     model_class(SCREAMING_SNAKE_CASE__					)
																		model.gradient_checkpointing_enable()
																		model.to(SCREAMING_SNAKE_CASE__					)
																		model.train()
																		SCREAMING_SNAKE_CASE__		: List[Any]     =     self._prepare_for_class(SCREAMING_SNAKE_CASE__     , SCREAMING_SNAKE_CASE__     , return_labels=SCREAMING_SNAKE_CASE__					)
																		SCREAMING_SNAKE_CASE__		: List[str]     =     model(**SCREAMING_SNAKE_CASE__					).loss
																		loss.backward()



				def 			__magic_name__					(self					)      ->	List[str]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__   ,   SCREAMING_SNAKE_CASE__		: int     =     self.model_tester.prepare_config_and_inputs_for_common()

											SCREAMING_SNAKE_CASE__		: int     =     _config_zero_init(SCREAMING_SNAKE_CASE__					)
											for model_class in self.all_model_classes:
																		SCREAMING_SNAKE_CASE__		: Optional[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 			__magic_name__					(self					)      ->	Any:



											"""simple docstring"""




											for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																		SCREAMING_SNAKE_CASE__		: Dict     =     BeitModel.from_pretrained(SCREAMING_SNAKE_CASE__					)
																		self.assertIsNotNone(SCREAMING_SNAKE_CASE__					)






def lowercase_						(     ):
							SCREAMING_SNAKE_CASE__		: List[str]     =     Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""		)
							return image



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


				"""simple docstring"""



				@cached_property
				def 			__magic_name__					(self					)      ->	Union[str, Any]:



											"""simple docstring"""




											return BeitImageProcessor.from_pretrained("""microsoft/beit-base-patch16-224"""					) if is_vision_available() else None



				@slow
				def 			__magic_name__					(self					)      ->	List[str]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     BeitForMaskedImageModeling.from_pretrained("""microsoft/beit-base-patch16-224-pt22k"""					).to(SCREAMING_SNAKE_CASE__					)

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

											# prepare bool_masked_pos
											SCREAMING_SNAKE_CASE__		: str     =     torch.ones((1, 1_96)     , dtype=torch.bool					).to(SCREAMING_SNAKE_CASE__					)

											# forward pass
											with torch.no_grad():
																		SCREAMING_SNAKE_CASE__		: str     =     model(pixel_values=SCREAMING_SNAKE_CASE__     , bool_masked_pos=SCREAMING_SNAKE_CASE__					)
											SCREAMING_SNAKE_CASE__		: int     =     outputs.logits

											# verify the logits
											SCREAMING_SNAKE_CASE__		: List[Any]     =     torch.Size((1, 1_96, 81_92)					)
											self.assertEqual(logits.shape     , SCREAMING_SNAKE_CASE__					)

											SCREAMING_SNAKE_CASE__		: Optional[int]     =     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 			__magic_name__					(self					)      ->	Union[str, Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     BeitForImageClassification.from_pretrained("""microsoft/beit-base-patch16-224"""					).to(SCREAMING_SNAKE_CASE__					)

											SCREAMING_SNAKE_CASE__		: str     =     self.default_image_processor
											SCREAMING_SNAKE_CASE__		: str     =     prepare_img()
											SCREAMING_SNAKE_CASE__		: Any     =     image_processor(images=SCREAMING_SNAKE_CASE__     , return_tensors="""pt"""					).to(SCREAMING_SNAKE_CASE__					)

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

											# verify the logits
											SCREAMING_SNAKE_CASE__		: str     =     torch.Size((1, 10_00)					)
											self.assertEqual(logits.shape     , SCREAMING_SNAKE_CASE__					)

											SCREAMING_SNAKE_CASE__		: List[Any]     =     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					)					)

											SCREAMING_SNAKE_CASE__		: List[str]     =     2_81
											self.assertEqual(logits.argmax(-1					).item()     , SCREAMING_SNAKE_CASE__					)



				@slow
				def 			__magic_name__					(self					)      ->	Union[str, Any]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: str     =     BeitForImageClassification.from_pretrained("""microsoft/beit-large-patch16-224-pt22k-ft22k"""					).to(
											    SCREAMING_SNAKE_CASE__					)

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

											# forward pass
											with torch.no_grad():
																		SCREAMING_SNAKE_CASE__		: Optional[Any]     =     model(**SCREAMING_SNAKE_CASE__					)
											SCREAMING_SNAKE_CASE__		: Dict     =     outputs.logits

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

											SCREAMING_SNAKE_CASE__		: 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					)					)

											SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     23_96
											self.assertEqual(logits.argmax(-1					).item()     , SCREAMING_SNAKE_CASE__					)



				@slow
				def 			__magic_name__					(self					)      ->	Optional[int]:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Optional[int]     =     BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640"""					)
											SCREAMING_SNAKE_CASE__		: Dict     =     model.to(SCREAMING_SNAKE_CASE__					)

											SCREAMING_SNAKE_CASE__		: List[str]     =     BeitImageProcessor(do_resize=SCREAMING_SNAKE_CASE__     , size=6_40     , do_center_crop=SCREAMING_SNAKE_CASE__					)

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

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

											# verify the logits
											SCREAMING_SNAKE_CASE__		: Dict     =     torch.Size((1, 1_50, 1_60, 1_60)					)
											self.assertEqual(logits.shape     , SCREAMING_SNAKE_CASE__					)

											SCREAMING_SNAKE_CASE__		: Tuple     =     version.parse(PIL.__version__					) < version.parse("""9.0.0"""					)

											if is_pillow_less_than_a:
																		SCREAMING_SNAKE_CASE__		: 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:
																		SCREAMING_SNAKE_CASE__		: List[Any]     =     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 			__magic_name__					(self					)      ->	Any:



											"""simple docstring"""




											SCREAMING_SNAKE_CASE__		: Optional[Any]     =     BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640"""					)
											SCREAMING_SNAKE_CASE__		: Any     =     model.to(SCREAMING_SNAKE_CASE__					)

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

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

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

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

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

											SCREAMING_SNAKE_CASE__		: int     =     image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE__					)
											SCREAMING_SNAKE_CASE__		: List[Any]     =     torch.Size((1_60, 1_60)					)
											self.assertEqual(segmentation[0].shape     , SCREAMING_SNAKE_CASE__					)






"""simple docstring"""




import math
import os
import sys

def lowercase_						(     _snake_case		):
							SCREAMING_SNAKE_CASE__		: List[str]     =     """"""
							try:
														with open(_snake_case     ,"""rb"""		) as binary_file:
																					SCREAMING_SNAKE_CASE__		: str     =     binary_file.read()
														for dat in data:
																					SCREAMING_SNAKE_CASE__		: int     =     f'''{dat:08b}'''
																					result += curr_byte
														return result
							except OSError:
														print("""File not accessible"""		)
														sys.exit()

def lowercase_						(     _snake_case     ,_snake_case     ,_snake_case     ,_snake_case		):
							lexicon.pop(_snake_case		)
							SCREAMING_SNAKE_CASE__		: Optional[int]     =     last_match_id

							if math.loga(_snake_case		).is_integer():
														for curr_key in lexicon:
																					SCREAMING_SNAKE_CASE__		: Optional[int]     =     """0""" + lexicon[curr_key]

							SCREAMING_SNAKE_CASE__		: Tuple     =     bin(_snake_case		)[2:]

def lowercase_						(     _snake_case		):
							SCREAMING_SNAKE_CASE__		: List[str]     =     {"""0""": """0""", """1""": """1"""}
							SCREAMING_SNAKE_CASE__   ,   SCREAMING_SNAKE_CASE__		: str     =     """""", """"""
							SCREAMING_SNAKE_CASE__		: int     =     len(_snake_case		)

							for i in range(len(_snake_case		)		):
														curr_string += data_bits[i]
														if curr_string not in lexicon:
																					continue

														SCREAMING_SNAKE_CASE__		: Dict     =     lexicon[curr_string]
														result += last_match_id
														add_key_to_lexicon(_snake_case     ,_snake_case     ,_snake_case     ,_snake_case		)
														index += 1
														SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     """"""

							while curr_string != "" and curr_string not in lexicon:
														curr_string += "0"

							if curr_string != "":
														SCREAMING_SNAKE_CASE__		: Optional[int]     =     lexicon[curr_string]
														result += last_match_id

							return result

def lowercase_						(     _snake_case     ,_snake_case		):
							SCREAMING_SNAKE_CASE__		: str     =     os.path.getsize(_snake_case		)
							SCREAMING_SNAKE_CASE__		: Any     =     bin(_snake_case		)[2:]
							SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     len(_snake_case		)

							return "0" * (length_length - 1) + file_length_binary + compressed

def lowercase_						(     _snake_case     ,_snake_case		):
							SCREAMING_SNAKE_CASE__		: Tuple     =     8
							try:
														with open(_snake_case     ,"""wb"""		) as opened_file:
																					SCREAMING_SNAKE_CASE__		: Optional[int]     =     [
																					    to_write[i : i + byte_length]
																					    for i in range(0     ,len(_snake_case		)     ,_snake_case		)
																					]

																					if len(result_byte_array[-1]		) % byte_length == 0:
																												result_byte_array.append("""10000000"""		)
																					else:
																												result_byte_array[-1] += "1" + "0" * (
																												    byte_length - len(result_byte_array[-1]		) - 1
																												)

																					for elem in result_byte_array:
																												opened_file.write(int(_snake_case     ,2		).to_bytes(1     ,byteorder="""big"""		)		)
							except OSError:
														print("""File not accessible"""		)
														sys.exit()

def lowercase_						(     _snake_case     ,_snake_case		):
							SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     read_file_binary(_snake_case		)
							SCREAMING_SNAKE_CASE__		: List[str]     =     compress_data(_snake_case		)
							SCREAMING_SNAKE_CASE__		: Union[str, Any]     =     add_file_length(_snake_case     ,_snake_case		)
							write_file_binary(_snake_case     ,_snake_case		)


if __name__ == "__main__":
					compress(sys.argv[1], sys.argv[2])




