


"""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      A:

		"""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.0_2					,				SCREAMING_SNAKE_CASE__=3					,				SCREAMING_SNAKE_CASE__=None					,				SCREAMING_SNAKE_CASE__=[0, 1, 2, 3]					,				)      ->	Tuple:

					"""simple docstring"""



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

					# in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
					_UpperCamelCase					:Dict					     =	(image_size // patch_size) ** 2
					_UpperCamelCase					:Tuple					     =	num_patches + 1
		def   _UpperCamelCase( self   )      ->	Union[str, Any]:

					"""simple docstring"""



					_UpperCamelCase					:Any					     =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

					_UpperCamelCase					:List[Any]					     =	self.get_config()

					return config, pixel_values, labels, pixel_labels
		def   _UpperCamelCase( self   )      ->	int:

					"""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   _UpperCamelCase( self					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__   )      ->	List[str]:

					"""simple docstring"""



					_UpperCamelCase					:Dict					     =	BeitModel(config=SCREAMING_SNAKE_CASE__   )
					model.to(SCREAMING_SNAKE_CASE__   )
					model.eval()
					_UpperCamelCase					:str					     =	model(SCREAMING_SNAKE_CASE__   )
					self.parent.assertEqual(result.last_hidden_state.shape					,				(self.batch_size, self.seq_length, self.hidden_size)   )
		def   _UpperCamelCase( self					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__   )      ->	str:

					"""simple docstring"""



					_UpperCamelCase					:List[str]					     =	BeitForMaskedImageModeling(config=SCREAMING_SNAKE_CASE__   )
					model.to(SCREAMING_SNAKE_CASE__   )
					model.eval()
					_UpperCamelCase					:int					     =	model(SCREAMING_SNAKE_CASE__   )
					self.parent.assertEqual(result.logits.shape					,				(self.batch_size, self.seq_length - 1, self.vocab_size)   )
		def   _UpperCamelCase( self					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__   )      ->	Optional[Any]:

					"""simple docstring"""



					_UpperCamelCase					:Tuple					     =	self.type_sequence_label_size
					_UpperCamelCase					:List[str]					     =	BeitForImageClassification(SCREAMING_SNAKE_CASE__   )
					model.to(SCREAMING_SNAKE_CASE__   )
					model.eval()
					_UpperCamelCase					: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
					_UpperCamelCase					:Dict					     =	1
					_UpperCamelCase					:Optional[Any]					     =	BeitForImageClassification(SCREAMING_SNAKE_CASE__   )
					model.to(SCREAMING_SNAKE_CASE__   )
					model.eval()

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

					"""simple docstring"""



					_UpperCamelCase					:Any					     =	self.num_labels
					_UpperCamelCase					:int					     =	BeitForSemanticSegmentation(SCREAMING_SNAKE_CASE__   )
					model.to(SCREAMING_SNAKE_CASE__   )
					model.eval()
					_UpperCamelCase					: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)   )
					_UpperCamelCase					:Optional[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   _UpperCamelCase( self   )      ->	Union[str, Any]:

					"""simple docstring"""



					_UpperCamelCase					:int					     =	self.prepare_config_and_inputs()
					_UpperCamelCase     ,      _UpperCamelCase     ,      _UpperCamelCase     ,      _UpperCamelCase					:List[str]					     =	config_and_inputs
					_UpperCamelCase					:str					     =	{'''pixel_values''': pixel_values}
					return config, inputs_dict






@require_torch
class      A(  lowerCamelCase__				,							lowerCamelCase__				,							unittest.TestCase		):

		"""simple docstring"""





		A    =							(
		    (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
		    if is_torch_available()
		    else ()
		)
		A    =							(
		    {
		        "feature-extraction": BeitModel,
		        "image-classification": BeitForImageClassification,
		        "image-segmentation": BeitForSemanticSegmentation,
		    }
		    if is_torch_available()
		    else {}
		)

		A    =							False
		A    =							False
		A    =							False
		def   _UpperCamelCase( self   )      ->	Optional[Any]:

					"""simple docstring"""



					_UpperCamelCase					:int					     =	BeitModelTester(self   )
					_UpperCamelCase					:Tuple					     =	ConfigTester(self					,				config_class=SCREAMING_SNAKE_CASE__					,				has_text_modality=SCREAMING_SNAKE_CASE__					,				hidden_size=37   )
		def   _UpperCamelCase( self   )      ->	str:

					"""simple docstring"""



					self.config_tester.run_common_tests()
		@unittest.skip(reason='''BEiT does not use inputs_embeds'''   )
		def   _UpperCamelCase( self   )      ->	int:

					"""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   _UpperCamelCase( self   )      ->	Union[str, Any]:

					"""simple docstring"""



					pass
		def   _UpperCamelCase( self   )      ->	Optional[Any]:

					"""simple docstring"""



					_UpperCamelCase     ,      _UpperCamelCase					:List[str]					     =	self.model_tester.prepare_config_and_inputs_for_common()

					for model_class in self.all_model_classes:
								_UpperCamelCase					:Any					     =	model_class(SCREAMING_SNAKE_CASE__   )
								self.assertIsInstance(model.get_input_embeddings()					,				(nn.Module)   )
								_UpperCamelCase					:Optional[int]					     =	model.get_output_embeddings()
								self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__					,				nn.Linear   )   )
		def   _UpperCamelCase( self   )      ->	Dict:

					"""simple docstring"""



					_UpperCamelCase     ,      _UpperCamelCase					:str					     =	self.model_tester.prepare_config_and_inputs_for_common()

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

								_UpperCamelCase					:int					     =	['''pixel_values''']
								self.assertListEqual(arg_names[:1]					,				SCREAMING_SNAKE_CASE__   )
		def   _UpperCamelCase( self   )      ->	List[str]:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__   )
		def   _UpperCamelCase( self   )      ->	Optional[int]:

					"""simple docstring"""



					_UpperCamelCase					:Optional[int]					     =	self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_masked_lm(*SCREAMING_SNAKE_CASE__   )
		def   _UpperCamelCase( self   )      ->	str:

					"""simple docstring"""



					_UpperCamelCase					:Optional[Any]					     =	self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__   )
		def   _UpperCamelCase( self   )      ->	Optional[Any]:

					"""simple docstring"""



					_UpperCamelCase					:Optional[int]					     =	self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_semantic_segmentation(*SCREAMING_SNAKE_CASE__   )
		def   _UpperCamelCase( self   )      ->	Any:

					"""simple docstring"""



					if not self.model_tester.is_training:
								return

					_UpperCamelCase     ,      _UpperCamelCase					:str					     =	self.model_tester.prepare_config_and_inputs_for_common()
					_UpperCamelCase					: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]:
											continue

								_UpperCamelCase					:Any					     =	model_class(SCREAMING_SNAKE_CASE__   )
								model.to(SCREAMING_SNAKE_CASE__   )
								model.train()
								_UpperCamelCase					:Union[str, Any]					     =	self._prepare_for_class(SCREAMING_SNAKE_CASE__					,				SCREAMING_SNAKE_CASE__					,				return_labels=SCREAMING_SNAKE_CASE__   )
								_UpperCamelCase					:Any					     =	model(**SCREAMING_SNAKE_CASE__   ).loss
								loss.backward()
		def   _UpperCamelCase( self   )      ->	List[Any]:

					"""simple docstring"""



					_UpperCamelCase     ,      _UpperCamelCase					:Union[str, Any]					     =	self.model_tester.prepare_config_and_inputs_for_common()
					if not self.model_tester.is_training:
								return

					_UpperCamelCase					:Tuple					     =	False
					_UpperCamelCase					:Optional[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

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

					"""simple docstring"""



					_UpperCamelCase     ,      _UpperCamelCase					:List[str]					     =	self.model_tester.prepare_config_and_inputs_for_common()

					_UpperCamelCase					:Optional[int]					     =	_config_zero_init(SCREAMING_SNAKE_CASE__   )
					for model_class in self.all_model_classes:
								_UpperCamelCase					:List[str]					     =	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   _UpperCamelCase( self   )      ->	List[str]:

					"""simple docstring"""



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





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






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

		"""simple docstring"""





		@cached_property
		def   _UpperCamelCase( self   )      ->	List[Any]:

					"""simple docstring"""



					return BeitImageProcessor.from_pretrained('''microsoft/beit-base-patch16-224'''   ) if is_vision_available() else None
		@slow
		def   _UpperCamelCase( self   )      ->	Union[str, Any]:

					"""simple docstring"""



					_UpperCamelCase					:List[str]					     =	BeitForMaskedImageModeling.from_pretrained('''microsoft/beit-base-patch16-224-pt22k'''   ).to(SCREAMING_SNAKE_CASE__   )

					_UpperCamelCase					:Any					     =	self.default_image_processor
					_UpperCamelCase					:Any					     =	prepare_img()
					_UpperCamelCase					:Optional[int]					     =	image_processor(images=SCREAMING_SNAKE_CASE__					,				return_tensors='''pt'''   ).pixel_values.to(SCREAMING_SNAKE_CASE__   )

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

					# forward pass
					with torch.no_grad():
								_UpperCamelCase					:List[str]					     =	model(pixel_values=SCREAMING_SNAKE_CASE__					,				bool_masked_pos=SCREAMING_SNAKE_CASE__   )
					_UpperCamelCase					:List[str]					     =	outputs.logits

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

					_UpperCamelCase					:List[Any]					     =	torch.tensor(
					    [[-3.2_4_3_7, 0.5_0_7_2, -1_3.9_1_7_4], [-3.2_4_5_6, 0.4_9_4_8, -1_3.9_4_0_1], [-3.2_0_3_3, 0.5_1_2_1, -1_3.8_5_5_0]]   ).to(SCREAMING_SNAKE_CASE__   )

					self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3]					,				SCREAMING_SNAKE_CASE__					,				atol=1E-2   )   )
		@slow
		def   _UpperCamelCase( self   )      ->	Union[str, Any]:

					"""simple docstring"""



					_UpperCamelCase					:List[str]					     =	BeitForImageClassification.from_pretrained('''microsoft/beit-base-patch16-224'''   ).to(SCREAMING_SNAKE_CASE__   )

					_UpperCamelCase					:int					     =	self.default_image_processor
					_UpperCamelCase					:List[str]					     =	prepare_img()
					_UpperCamelCase					:Dict					     =	image_processor(images=SCREAMING_SNAKE_CASE__					,				return_tensors='''pt'''   ).to(SCREAMING_SNAKE_CASE__   )

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

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

					_UpperCamelCase					:Tuple					     =	torch.tensor([-1.2_3_8_5, -1.0_9_8_7, -1.0_1_0_8]   ).to(SCREAMING_SNAKE_CASE__   )

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

					_UpperCamelCase					:Optional[int]					     =	2_81
					self.assertEqual(logits.argmax(-1   ).item()					,				SCREAMING_SNAKE_CASE__   )
		@slow
		def   _UpperCamelCase( self   )      ->	str:

					"""simple docstring"""



					_UpperCamelCase					:Union[str, Any]					     =	BeitForImageClassification.from_pretrained('''microsoft/beit-large-patch16-224-pt22k-ft22k'''   ).to(
					    SCREAMING_SNAKE_CASE__   )

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

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

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

					_UpperCamelCase					:Optional[int]					     =	torch.tensor([1.6_8_8_1, -0.2_7_8_7, 0.5_9_0_1]   ).to(SCREAMING_SNAKE_CASE__   )

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

					_UpperCamelCase					:Optional[int]					     =	23_96
					self.assertEqual(logits.argmax(-1   ).item()					,				SCREAMING_SNAKE_CASE__   )
		@slow
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:Any					     =	BeitForSemanticSegmentation.from_pretrained('''microsoft/beit-base-finetuned-ade-640-640'''   )
					_UpperCamelCase					:int					     =	model.to(SCREAMING_SNAKE_CASE__   )

					_UpperCamelCase					:Tuple					     =	BeitImageProcessor(do_resize=SCREAMING_SNAKE_CASE__					,				size=6_40					,				do_center_crop=SCREAMING_SNAKE_CASE__   )

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

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

					# verify the logits
					_UpperCamelCase					:Optional[int]					     =	torch.Size((1, 1_50, 1_60, 1_60)   )
					self.assertEqual(logits.shape					,				SCREAMING_SNAKE_CASE__   )

					_UpperCamelCase					:Any					     =	version.parse(PIL.__version__   ) < version.parse('''9.0.0'''   )

					if is_pillow_less_than_a:
								_UpperCamelCase					:Any					     =	torch.tensor(
								    [
								        [[-4.9_2_2_5, -2.3_9_5_4, -3.0_5_2_2], [-2.8_8_2_2, -1.0_0_4_6, -1.7_5_6_1], [-2.9_5_4_9, -1.3_2_2_8, -2.1_3_4_7]],
								        [[-5.8_1_6_8, -3.4_1_2_9, -4.0_7_7_8], [-3.8_6_5_1, -2.2_2_1_4, -3.0_2_7_7], [-3.8_3_5_6, -2.4_6_4_3, -3.3_5_3_5]],
								        [[-0.0_0_7_8, 3.9_9_5_2, 4.0_7_5_4], [2.9_8_5_6, 4.6_9_4_4, 5.0_0_3_5], [3.2_4_1_3, 4.7_8_1_3, 4.9_9_6_9]],
								    ]					,				device=SCREAMING_SNAKE_CASE__					,				)
					else:
								_UpperCamelCase					:int					     =	torch.tensor(
								    [
								        [[-4.8_9_6_0, -2.3_6_8_8, -3.0_3_5_5], [-2.8_4_7_8, -0.9_8_3_6, -1.7_4_1_8], [-2.9_4_4_9, -1.3_3_3_2, -2.1_4_5_6]],
								        [[-5.8_0_8_1, -3.4_1_2_4, -4.1_0_0_6], [-3.8_5_6_1, -2.2_0_8_1, -3.0_3_2_3], [-3.8_3_6_5, -2.4_6_0_1, -3.3_6_6_9]],
								        [[-0.0_3_0_9, 3.9_8_6_8, 4.0_5_4_0], [2.9_6_4_0, 4.6_8_7_7, 4.9_9_7_6], [3.2_0_8_1, 4.7_6_9_0, 4.9_9_4_2]],
								    ]					,				device=SCREAMING_SNAKE_CASE__					,				)

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





		@slow
		def   _UpperCamelCase( self   )      ->	Dict:

					"""simple docstring"""



					_UpperCamelCase					:Any					     =	BeitForSemanticSegmentation.from_pretrained('''microsoft/beit-base-finetuned-ade-640-640'''   )
					_UpperCamelCase					:Any					     =	model.to(SCREAMING_SNAKE_CASE__   )

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

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

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

					_UpperCamelCase					:Union[str, Any]					     =	outputs.logits.detach().cpu()

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

					_UpperCamelCase					:Dict					     =	image_processor.post_process_semantic_segmentation(outputs=SCREAMING_SNAKE_CASE__   )
					_UpperCamelCase					:Tuple					     =	torch.Size((1_60, 1_60)   )
					self.assertEqual(segmentation[0].shape					,				SCREAMING_SNAKE_CASE__   )





"""simple docstring"""






import unittest

import numpy as np

from transformers.testing_utils import require_flax, require_tf, require_torch
from transformers.utils import (
    expand_dims,
    flatten_dict,
    is_flax_available,
    is_tf_available,
    is_torch_available,
    reshape,
    squeeze,
    transpose,
)


if is_flax_available():
					import jax.numpy as jnp

if is_tf_available():
					import tensorflow as tf

if is_torch_available():
					import torch






class      A(  unittest.TestCase		):

		"""simple docstring"""





		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:List[str]					     =	{
					    '''task_specific_params''': {
					        '''summarization''': {'''length_penalty''': 1.0, '''max_length''': 1_28, '''min_length''': 12, '''num_beams''': 4},
					        '''summarization_cnn''': {'''length_penalty''': 2.0, '''max_length''': 1_42, '''min_length''': 56, '''num_beams''': 4},
					        '''summarization_xsum''': {'''length_penalty''': 1.0, '''max_length''': 62, '''min_length''': 11, '''num_beams''': 6},
					    }
					}
					_UpperCamelCase					:Union[str, Any]					     =	{
					    '''task_specific_params.summarization.length_penalty''': 1.0,
					    '''task_specific_params.summarization.max_length''': 1_28,
					    '''task_specific_params.summarization.min_length''': 12,
					    '''task_specific_params.summarization.num_beams''': 4,
					    '''task_specific_params.summarization_cnn.length_penalty''': 2.0,
					    '''task_specific_params.summarization_cnn.max_length''': 1_42,
					    '''task_specific_params.summarization_cnn.min_length''': 56,
					    '''task_specific_params.summarization_cnn.num_beams''': 4,
					    '''task_specific_params.summarization_xsum.length_penalty''': 1.0,
					    '''task_specific_params.summarization_xsum.max_length''': 62,
					    '''task_specific_params.summarization_xsum.min_length''': 11,
					    '''task_specific_params.summarization_xsum.num_beams''': 6,
					}

					self.assertEqual(flatten_dict(SCREAMING_SNAKE_CASE__   )					,				SCREAMING_SNAKE_CASE__   )
		def   _UpperCamelCase( self   )      ->	Any:

					"""simple docstring"""



					_UpperCamelCase					:Optional[int]					     =	np.random.randn(3					,				4   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__   )					,				x.transpose()   )   )

					_UpperCamelCase					:Tuple					     =	np.random.randn(3					,				4					,				5   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   )					,				x.transpose((1, 2, 0)   )   )   )
		@require_torch
		def   _UpperCamelCase( self   )      ->	str:

					"""simple docstring"""



					_UpperCamelCase					:Union[str, Any]					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:Any					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__   )					,				transpose(SCREAMING_SNAKE_CASE__   ).numpy()   )   )

					_UpperCamelCase					:int					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:Any					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   )					,				transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   ).numpy()   )   )
		@require_tf
		def   _UpperCamelCase( self   )      ->	Dict:

					"""simple docstring"""



					_UpperCamelCase					:Dict					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:List[str]					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__   )					,				transpose(SCREAMING_SNAKE_CASE__   ).numpy()   )   )

					_UpperCamelCase					:int					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:Dict					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   )					,				transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   ).numpy()   )   )
		@require_flax
		def   _UpperCamelCase( self   )      ->	str:

					"""simple docstring"""



					_UpperCamelCase					:int					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:Optional[Any]					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__   )					,				np.asarray(transpose(SCREAMING_SNAKE_CASE__   )   )   )   )

					_UpperCamelCase					:Dict					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:Dict					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   )					,				np.asarray(transpose(SCREAMING_SNAKE_CASE__					,				axes=(1, 2, 0)   )   )   )   )
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:int					     =	np.random.randn(3					,				4   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )					,				np.reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )   )   )

					_UpperCamelCase					:Dict					     =	np.random.randn(3					,				4					,				5   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )					,				np.reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )   )   )
		@require_torch
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:Union[str, Any]					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:Optional[Any]					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )					,				reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   ).numpy()   )   )

					_UpperCamelCase					:str					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:str					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )					,				reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   ).numpy()   )   )
		@require_tf
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:Optional[int]					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:Dict					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )					,				reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   ).numpy()   )   )

					_UpperCamelCase					:Union[str, Any]					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:Optional[int]					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )					,				reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   ).numpy()   )   )
		@require_flax
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:List[str]					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:str					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )					,				np.asarray(reshape(SCREAMING_SNAKE_CASE__					,				(4, 3)   )   )   )   )

					_UpperCamelCase					:Dict					     =	np.random.randn(3					,				4					,				5   )
					_UpperCamelCase					:Union[str, Any]					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )					,				np.asarray(reshape(SCREAMING_SNAKE_CASE__					,				(12, 5)   )   )   )   )
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:Dict					     =	np.random.randn(1					,				3					,				4   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__   )					,				np.squeeze(SCREAMING_SNAKE_CASE__   )   )   )

					_UpperCamelCase					:List[Any]					     =	np.random.randn(1					,				4					,				1					,				5   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )					,				np.squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )   )   )
		@require_torch
		def   _UpperCamelCase( self   )      ->	Union[str, Any]:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	np.random.randn(1					,				3					,				4   )
					_UpperCamelCase					:Any					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__   )					,				squeeze(SCREAMING_SNAKE_CASE__   ).numpy()   )   )

					_UpperCamelCase					:List[str]					     =	np.random.randn(1					,				4					,				1					,				5   )
					_UpperCamelCase					:List[Any]					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )					,				squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   ).numpy()   )   )
		@require_tf
		def   _UpperCamelCase( self   )      ->	int:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	np.random.randn(1					,				3					,				4   )
					_UpperCamelCase					:str					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__   )					,				squeeze(SCREAMING_SNAKE_CASE__   ).numpy()   )   )

					_UpperCamelCase					:str					     =	np.random.randn(1					,				4					,				1					,				5   )
					_UpperCamelCase					:str					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )					,				squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   ).numpy()   )   )
		@require_flax
		def   _UpperCamelCase( self   )      ->	Optional[Any]:

					"""simple docstring"""



					_UpperCamelCase					:Union[str, Any]					     =	np.random.randn(1					,				3					,				4   )
					_UpperCamelCase					:Optional[Any]					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__   )					,				np.asarray(squeeze(SCREAMING_SNAKE_CASE__   )   )   )   )

					_UpperCamelCase					:Dict					     =	np.random.randn(1					,				4					,				1					,				5   )
					_UpperCamelCase					:int					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )					,				np.asarray(squeeze(SCREAMING_SNAKE_CASE__					,				axis=2   )   )   )   )
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:Dict					     =	np.random.randn(3					,				4   )
					self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )					,				np.expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )   )   )
		@require_torch
		def   _UpperCamelCase( self   )      ->	Tuple:

					"""simple docstring"""



					_UpperCamelCase					:List[str]					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:Union[str, Any]					     =	torch.tensor(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )					,				expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   ).numpy()   )   )
		@require_tf
		def   _UpperCamelCase( self   )      ->	Optional[int]:

					"""simple docstring"""



					_UpperCamelCase					:str					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:int					     =	tf.constant(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )					,				expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   ).numpy()   )   )





		@require_flax
		def   _UpperCamelCase( self   )      ->	List[Any]:

					"""simple docstring"""



					_UpperCamelCase					:Tuple					     =	np.random.randn(3					,				4   )
					_UpperCamelCase					:str					     =	jnp.array(SCREAMING_SNAKE_CASE__   )
					self.assertTrue(np.allclose(expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )					,				np.asarray(expand_dims(SCREAMING_SNAKE_CASE__					,				axis=1   )   )   )   )

