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




						def __init__(    self :       List[Any]							,							UpperCamelCase_ :       Optional[int]							,							UpperCamelCase_ :       Optional[int]=1_00							,							UpperCamelCase_ :       Tuple=13							,							UpperCamelCase_ :       Dict=30							,							UpperCamelCase_ :       str=2							,							UpperCamelCase_ :       int=3							,							UpperCamelCase_ :       Any=True							,							UpperCamelCase_ :       Any=True							,							UpperCamelCase_ :       Union[str, Any]=32							,							UpperCamelCase_ :       str=4							,							UpperCamelCase_ :       Tuple=4							,							UpperCamelCase_ :       str=37							,							UpperCamelCase_ :       List[str]="gelu"							,							UpperCamelCase_ :       Optional[Any]=0.1							,							UpperCamelCase_ :       List[str]=0.1							,							UpperCamelCase_ :       Union[str, Any]=10							,							UpperCamelCase_ :       int=0.02							,							UpperCamelCase_ :       List[str]=3							,							UpperCamelCase_ :       int=None							,							UpperCamelCase_ :       Union[str, Any]=[0, 1, 2, 3]							,							)     ->				str:
													SCREAMING_SNAKE_CASE__     :List[str]						    = parent
													SCREAMING_SNAKE_CASE__     :int						    = 1_00
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = batch_size
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = image_size
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = patch_size
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = num_channels
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = is_training
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = use_labels
													SCREAMING_SNAKE_CASE__     :int						    = hidden_size
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = num_hidden_layers
													SCREAMING_SNAKE_CASE__     :List[str]						    = num_attention_heads
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = intermediate_size
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = hidden_act
													SCREAMING_SNAKE_CASE__     :Dict						    = hidden_dropout_prob
													SCREAMING_SNAKE_CASE__     :List[Any]						    = attention_probs_dropout_prob
													SCREAMING_SNAKE_CASE__     :List[str]						    = type_sequence_label_size
													SCREAMING_SNAKE_CASE__     :List[str]						    = initializer_range
													SCREAMING_SNAKE_CASE__     :int						    = scope
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = out_indices
													SCREAMING_SNAKE_CASE__     :Tuple						    = num_labels

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




						def      __lowerCamelCase       (    self :       Dict      )     ->				List[Any]:
													SCREAMING_SNAKE_CASE__     :int						    = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

													SCREAMING_SNAKE_CASE__     :List[str]						    = None
													SCREAMING_SNAKE_CASE__     :Any						    = None
													if self.use_labels:
																				SCREAMING_SNAKE_CASE__     :Optional[int]						    = ids_tensor([self.batch_size]							,							self.type_sequence_label_size      )
																				SCREAMING_SNAKE_CASE__     :Optional[int]						    = ids_tensor([self.batch_size, self.image_size, self.image_size]							,							self.num_labels      )

													SCREAMING_SNAKE_CASE__     :Tuple						    = self.get_config()

													return config, pixel_values, labels, pixel_labels




						def      __lowerCamelCase       (    self :       Tuple      )     ->				List[Any]:
													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=_UpperCAmelCase							,							initializer_range=self.initializer_range							,							out_indices=self.out_indices							,							)




						def      __lowerCamelCase       (    self :       str							,							UpperCamelCase_ :       Dict							,							UpperCamelCase_ :       Optional[Any]							,							UpperCamelCase_ :       Tuple							,							UpperCamelCase_ :       List[Any]      )     ->				List[Any]:
													SCREAMING_SNAKE_CASE__     :Any						    = BeitModel(config=_UpperCAmelCase      )
													model.to(_UpperCAmelCase      )
													model.eval()
													SCREAMING_SNAKE_CASE__     :Dict						    = model(_UpperCAmelCase      )
													self.parent.assertEqual(result.last_hidden_state.shape							,							(self.batch_size, self.seq_length, self.hidden_size)      )




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




						def      __lowerCamelCase       (    self :       Optional[int]							,							UpperCamelCase_ :       Dict							,							UpperCamelCase_ :       Dict							,							UpperCamelCase_ :       Any							,							UpperCamelCase_ :       Any      )     ->				Optional[int]:
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = self.type_sequence_label_size
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = BeitForImageClassification(_UpperCAmelCase      )
													model.to(_UpperCAmelCase      )
													model.eval()
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = model(_UpperCAmelCase							,							labels=_UpperCAmelCase      )
													self.parent.assertEqual(result.logits.shape							,							(self.batch_size, self.type_sequence_label_size)      )

													# test greyscale images
													SCREAMING_SNAKE_CASE__     :List[str]						    = 1
													SCREAMING_SNAKE_CASE__     :Dict						    = BeitForImageClassification(_UpperCAmelCase      )
													model.to(_UpperCAmelCase      )
													model.eval()

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




						def      __lowerCamelCase       (    self :       List[Any]							,							UpperCamelCase_ :       Optional[Any]							,							UpperCamelCase_ :       Optional[int]							,							UpperCamelCase_ :       Optional[Any]							,							UpperCamelCase_ :       Dict      )     ->				Dict:
													SCREAMING_SNAKE_CASE__     :List[Any]						    = self.num_labels
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = BeitForSemanticSegmentation(_UpperCAmelCase      )
													model.to(_UpperCAmelCase      )
													model.eval()
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = model(_UpperCAmelCase      )
													self.parent.assertEqual(
													    result.logits.shape							,							(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)      )
													SCREAMING_SNAKE_CASE__     :str						    = model(_UpperCAmelCase							,							labels=_UpperCAmelCase      )
													self.parent.assertEqual(
													    result.logits.shape							,							(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)      )




						def      __lowerCamelCase       (    self :       Tuple      )     ->				Any:
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = self.prepare_config_and_inputs()
													SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :Tuple						    = config_and_inputs
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = {'pixel_values': pixel_values}
													return config, inputs_dict




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

						A_			:							Any     		= False
						A_			:							Any     		= False
						A_			:							List[str]     		= False




						def      __lowerCamelCase       (    self :       List[str]      )     ->				str:
													SCREAMING_SNAKE_CASE__     :Tuple						    = BeitModelTester(self      )
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = ConfigTester(self							,							config_class=_UpperCAmelCase							,							has_text_modality=_UpperCAmelCase							,							hidden_size=37      )




						def      __lowerCamelCase       (    self :       Any      )     ->				List[str]:
													self.config_tester.run_common_tests()




						@unittest.skip(reason='BEiT does not use inputs_embeds'      )
						def      __lowerCamelCase       (    self :       str      )     ->				Optional[int]:
													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 :       Dict      )     ->				List[str]:
													pass




						def      __lowerCamelCase       (    self :       List[str]      )     ->				List[str]:
													SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :Optional[int]						    = self.model_tester.prepare_config_and_inputs_for_common()

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




						def      __lowerCamelCase       (    self :       Optional[Any]      )     ->				List[Any]:
													SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :Dict						    = self.model_tester.prepare_config_and_inputs_for_common()

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

																				SCREAMING_SNAKE_CASE__     :str						    = ['pixel_values']
																				self.assertListEqual(arg_names[:1]							,							_UpperCAmelCase      )




						def      __lowerCamelCase       (    self :       List[str]      )     ->				List[str]:
													SCREAMING_SNAKE_CASE__     :Any						    = self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*_UpperCAmelCase      )




						def      __lowerCamelCase       (    self :       Any      )     ->				int:
													SCREAMING_SNAKE_CASE__     :Dict						    = self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_masked_lm(*_UpperCAmelCase      )




						def      __lowerCamelCase       (    self :       Optional[Any]      )     ->				Union[str, Any]:
													SCREAMING_SNAKE_CASE__     :int						    = self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_classification(*_UpperCAmelCase      )




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




						def      __lowerCamelCase       (    self :       Any      )     ->				List[str]:
													if not self.model_tester.is_training:
																				return

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

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

																				SCREAMING_SNAKE_CASE__     :Any						    = model_class(_UpperCAmelCase      )
																				model.to(_UpperCAmelCase      )
																				model.train()
																				SCREAMING_SNAKE_CASE__     :Dict						    = self._prepare_for_class(_UpperCAmelCase							,							_UpperCAmelCase							,							return_labels=_UpperCAmelCase      )
																				SCREAMING_SNAKE_CASE__     :Any						    = model(**_UpperCAmelCase      ).loss
																				loss.backward()




						def      __lowerCamelCase       (    self :       Optional[int]      )     ->				List[Any]:
													SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :Dict						    = self.model_tester.prepare_config_and_inputs_for_common()
													if not self.model_tester.is_training:
																				return

													SCREAMING_SNAKE_CASE__     :List[Any]						    = False
													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = True

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

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




						def      __lowerCamelCase       (    self :       Any      )     ->				List[str]:
													SCREAMING_SNAKE_CASE__    ,      SCREAMING_SNAKE_CASE__     :Optional[int]						    = self.model_tester.prepare_config_and_inputs_for_common()

													SCREAMING_SNAKE_CASE__     :Any						    = _config_zero_init(_UpperCAmelCase      )
													for model_class in self.all_model_classes:
																				SCREAMING_SNAKE_CASE__     :Optional[Any]						    = model_class(config=_UpperCAmelCase      )
																				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[Any]      )     ->				str:
													for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				SCREAMING_SNAKE_CASE__     :int						    = BeitModel.from_pretrained(_UpperCAmelCase      )
																				self.assertIsNotNone(_UpperCAmelCase      )


def    lowerCamelCase       (			)			->	int:


							'''simple docstring'''






							SCREAMING_SNAKE_CASE__     :Optional[Any]						    = Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'		)
							return image





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




						@cached_property
						def      __lowerCamelCase       (    self :       Optional[Any]      )     ->				str:
													return BeitImageProcessor.from_pretrained('microsoft/beit-base-patch16-224'      ) if is_vision_available() else None




						@slow
						def      __lowerCamelCase       (    self :       Any      )     ->				Tuple:
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = BeitForMaskedImageModeling.from_pretrained('microsoft/beit-base-patch16-224-pt22k'      ).to(_UpperCAmelCase      )

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

													# prepare bool_masked_pos
													SCREAMING_SNAKE_CASE__     :Optional[int]						    = torch.ones((1, 1_96)							,							dtype=torch.bool      ).to(_UpperCAmelCase      )

													# forward pass
													with torch.no_grad():
																				SCREAMING_SNAKE_CASE__     :Dict						    = model(pixel_values=_UpperCAmelCase							,							bool_masked_pos=_UpperCAmelCase      )
													SCREAMING_SNAKE_CASE__     :Any						    = outputs.logits

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

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

													self.assertTrue(torch.allclose(logits[bool_masked_pos][:3, :3]							,							_UpperCAmelCase							,							atol=1e-2      )      )




						@slow
						def      __lowerCamelCase       (    self :       Optional[Any]      )     ->				Any:
													SCREAMING_SNAKE_CASE__     :Tuple						    = BeitForImageClassification.from_pretrained('microsoft/beit-base-patch16-224'      ).to(_UpperCAmelCase      )

													SCREAMING_SNAKE_CASE__     :Any						    = self.default_image_processor
													SCREAMING_SNAKE_CASE__     :Dict						    = prepare_img()
													SCREAMING_SNAKE_CASE__     :int						    = image_processor(images=_UpperCAmelCase							,							return_tensors='pt'      ).to(_UpperCAmelCase      )

													# forward pass
													with torch.no_grad():
																				SCREAMING_SNAKE_CASE__     :int						    = model(**_UpperCAmelCase      )
													SCREAMING_SNAKE_CASE__     :Tuple						    = outputs.logits

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

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

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

													SCREAMING_SNAKE_CASE__     :Optional[Any]						    = 2_81
													self.assertEqual(logits.argmax(-1      ).item()							,							_UpperCAmelCase      )




						@slow
						def      __lowerCamelCase       (    self :       Dict      )     ->				Any:
													SCREAMING_SNAKE_CASE__     :List[Any]						    = BeitForImageClassification.from_pretrained('microsoft/beit-large-patch16-224-pt22k-ft22k'      ).to(
													    _UpperCAmelCase      )

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

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

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

													SCREAMING_SNAKE_CASE__     :List[Any]						    = torch.tensor([1.6881, -0.2787, 0.5901]      ).to(_UpperCAmelCase      )

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

													SCREAMING_SNAKE_CASE__     :Any						    = 23_96
													self.assertEqual(logits.argmax(-1      ).item()							,							_UpperCAmelCase      )




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

													SCREAMING_SNAKE_CASE__     :str						    = BeitImageProcessor(do_resize=_UpperCAmelCase							,							size=6_40							,							do_center_crop=_UpperCAmelCase      )

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

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

													# verify the logits
													SCREAMING_SNAKE_CASE__     :Union[str, Any]						    = torch.Size((1, 1_50, 1_60, 1_60)      )
													self.assertEqual(logits.shape							,							_UpperCAmelCase      )

													SCREAMING_SNAKE_CASE__     :Optional[int]						    = version.parse(PIL.__version__      ) < version.parse('9.0.0'      )

													if is_pillow_less_than_a:
																				SCREAMING_SNAKE_CASE__     :Optional[int]						    = 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=_UpperCAmelCase							,							)
													else:
																				SCREAMING_SNAKE_CASE__     :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=_UpperCAmelCase							,							)

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




						@slow
						def      __lowerCamelCase       (    self :       List[Any]      )     ->				Union[str, Any]:
													SCREAMING_SNAKE_CASE__     :int						    = BeitForSemanticSegmentation.from_pretrained('microsoft/beit-base-finetuned-ade-640-640'      )
													SCREAMING_SNAKE_CASE__     :str						    = model.to(_UpperCAmelCase      )

													SCREAMING_SNAKE_CASE__     :Optional[int]						    = BeitImageProcessor(do_resize=_UpperCAmelCase							,							size=6_40							,							do_center_crop=_UpperCAmelCase      )

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

													# forward pass
													with torch.no_grad():
																				SCREAMING_SNAKE_CASE__     :Dict						    = model(**_UpperCAmelCase      )

													SCREAMING_SNAKE_CASE__     :str						    = outputs.logits.detach().cpu()

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

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












"""simple docstring"""

import argparse
from collections import OrderedDict
from pathlib import Path

import torch

from transformers import (
    VisualBertConfig,
    VisualBertForMultipleChoice,
    VisualBertForPreTraining,
    VisualBertForQuestionAnswering,
    VisualBertForVisualReasoning,
)
from transformers.utils import logging


logging.set_verbosity_info()
a							      =     logging.get_logger(__name__)

a							      =     [
    ('''bert.bert''', '''visual_bert'''),
    ('''bert.cls''', '''cls'''),
    ('''bert.classifier''', '''cls'''),
    ('''token_type_embeddings_visual''', '''visual_token_type_embeddings'''),
    ('''position_embeddings_visual''', '''visual_position_embeddings'''),
    ('''projection''', '''visual_projection'''),
]

a							      =     [
    '''nlvr2_coco_pre_trained.th''',
    '''nlvr2_fine_tuned.th''',
    '''nlvr2_pre_trained.th''',
    '''vcr_coco_pre_train.th''',
    '''vcr_fine_tune.th''',
    '''vcr_pre_train.th''',
    '''vqa_coco_pre_trained.th''',
    '''vqa_fine_tuned.th''',
    '''vqa_pre_trained.th''',
]






def 		_snake_case	(   _snake_case				:   Optional[Any]				)       ->   str:






      '''simple docstring'''


      _A     =  torch.load(_snake_case							,    map_location='cpu'				)
      return sd






def 		_snake_case	(   _snake_case				:   Union[str, Any]							,    _snake_case				:   str							,    _snake_case				:   Tuple=rename_keys_prefix				)       ->   List[str]:






      '''simple docstring'''


      _A     =  OrderedDict()
      _A     =  torch.arange(config.max_position_embeddings				).expand((1, -1)				)
      # detector_d = OrderedDict()
      for key in d:
            if "detector" in key:
                  # detector_d[key.replace('detector.','')] = d[key]
                  continue
            _A     =  key
            for name_pair in rename_keys_prefix:
                  _A     =  new_key.replace(name_pair[0]							,    name_pair[1]				)
            _A     =  d[key]
            if key == "bert.cls.predictions.decoder.weight":
                  # Old bert code didn't have `decoder.bias`, but was added separately
                  _A     =  new_d['cls.predictions.bias']
      return new_d






@torch.no_grad()
def 		_snake_case	(   _snake_case				:   List[str]							,    _snake_case				:   Dict				)       ->   Dict:






      '''simple docstring'''


      assert (
          checkpoint_path.split('/'				)[-1] in ACCEPTABLE_CHECKPOINTS
      ), F'''The checkpoint provided must be in {ACCEPTABLE_CHECKPOINTS}.'''

      # Get Config
      if "pre" in checkpoint_path:
            _A     =  'pretraining'
            if "vcr" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 5_12}
            elif "vqa_advanced" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 20_48}
            elif "vqa" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 20_48}
            elif "nlvr" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 10_24}
            else:
                  raise NotImplementedError(F'''No implementation found for `{checkpoint_path}`.'''				)
      else:
            if "vcr" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 5_12}
                  _A     =  'multichoice'
            elif "vqa_advanced" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 20_48}
                  _A     =  'vqa_advanced'
            elif "vqa" in checkpoint_path:
                  _A     =  {'visual_embedding_dim': 20_48, 'num_labels': 31_29}
                  _A     =  'vqa'
            elif "nlvr" in checkpoint_path:
                  _A     =  {
                      'visual_embedding_dim': 10_24,
                      'num_labels': 2,
                  }
                  _A     =  'nlvr'

      _A     =  VisualBertConfig(**_snake_case				)

      # Load State Dict
      _A     =  load_state_dict(_snake_case				)

      _A     =  get_new_dict(_snake_case							,    _snake_case				)

      if model_type == "pretraining":
            _A     =  VisualBertForPreTraining(_snake_case				)
      elif model_type == "vqa":
            _A     =  VisualBertForQuestionAnswering(_snake_case				)
      elif model_type == "nlvr":
            _A     =  VisualBertForVisualReasoning(_snake_case				)
      elif model_type == "multichoice":
            _A     =  VisualBertForMultipleChoice(_snake_case				)

      model.load_state_dict(_snake_case				)
      # Save Checkpoints
      Path(_snake_case				).mkdir(exist_ok=_snake_case				)
      model.save_pretrained(_snake_case				)


if __name__ == "__main__":
       a							      =     argparse.ArgumentParser()
       # Required parameters
       parser.add_argument('''orig_checkpoint_path''', type=str, help='''A path to .th on local filesystem.''')
       parser.add_argument('''pytorch_dump_folder_path''', type=str, help='''Path to the output PyTorch model.''')
       a							      =     parser.parse_args()
       convert_visual_bert_checkpoint(args.orig_checkpoint_path, args.pytorch_dump_folder_path)

