



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	:       Dict			,     lowercase	:       List[Any]			,     lowercase	:       Dict=100			,     lowercase	:       Dict=13			,     lowercase	:       int=30			,     lowercase	:       List[str]=2			,     lowercase	:       Any=3			,     lowercase	:       List[str]=True			,     lowercase	:       List[str]=True			,     lowercase	:       Optional[int]=32			,     lowercase	:       Optional[int]=4			,     lowercase	:       Tuple=4			,     lowercase	:       str=37			,     lowercase	:       int="gelu"			,     lowercase	:       Union[str, Any]=0.1			,     lowercase	:       Dict=0.1			,     lowercase	:       Tuple=10			,     lowercase	:       int=0.02			,     lowercase	:       int=3			,     lowercase	:       int=None			,     lowercase	:       Optional[Any]=[0, 1, 2, 3]			,     )						->					str:
									"""simple docstring"""







									__lowercase					=				parent
									__lowercase					=				100
									__lowercase					=				batch_size
									__lowercase					=				image_size
									__lowercase					=				patch_size
									__lowercase					=				num_channels
									__lowercase					=				is_training
									__lowercase					=				use_labels
									__lowercase					=				hidden_size
									__lowercase					=				num_hidden_layers
									__lowercase					=				num_attention_heads
									__lowercase					=				intermediate_size
									__lowercase					=				hidden_act
									__lowercase					=				hidden_dropout_prob
									__lowercase					=				attention_probs_dropout_prob
									__lowercase					=				type_sequence_label_size
									__lowercase					=				initializer_range
									__lowercase					=				scope
									__lowercase					=				out_indices
									__lowercase					=				num_labels

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





			def 		snake_case__			(				self	:       Any   )						->					Optional[Any]:
									"""simple docstring"""







									__lowercase					=				floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

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

									__lowercase					=				self.get_config()

									return config, pixel_values, labels, pixel_labels





			def 		snake_case__			(				self	:       Optional[int]   )						->					Optional[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=lowercase			,     initializer_range=self.initializer_range			,     out_indices=self.out_indices			,     )





			def 		snake_case__			(				self	:       Any			,     lowercase	:       int			,     lowercase	:       str			,     lowercase	:       Optional[int]			,     lowercase	:       Dict   )						->					Union[str, Any]:
									"""simple docstring"""







									__lowercase					=				BeitModel(config=lowercase   )
									model.to(lowercase   )
									model.eval()
									__lowercase					=				model(lowercase   )
									self.parent.assertEqual(result.last_hidden_state.shape			,     (self.batch_size, self.seq_length, self.hidden_size)   )





			def 		snake_case__			(				self	:       int			,     lowercase	:       Dict			,     lowercase	:       Union[str, Any]			,     lowercase	:       Optional[Any]			,     lowercase	:       Optional[Any]   )						->					Union[str, Any]:
									"""simple docstring"""







									__lowercase					=				BeitForMaskedImageModeling(config=lowercase   )
									model.to(lowercase   )
									model.eval()
									__lowercase					=				model(lowercase   )
									self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.seq_length - 1, self.vocab_size)   )





			def 		snake_case__			(				self	:       List[Any]			,     lowercase	:       Union[str, Any]			,     lowercase	:       Any			,     lowercase	:       List[str]			,     lowercase	:       Any   )						->					Any:
									"""simple docstring"""







									__lowercase					=				self.type_sequence_label_size
									__lowercase					=				BeitForImageClassification(lowercase   )
									model.to(lowercase   )
									model.eval()
									__lowercase					=				model(lowercase			,     labels=lowercase   )
									self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.type_sequence_label_size)   )

									# test greyscale images
									__lowercase					=				1
									__lowercase					=				BeitForImageClassification(lowercase   )
									model.to(lowercase   )
									model.eval()

									__lowercase					=				floats_tensor([self.batch_size, 1, self.image_size, self.image_size]   )
									__lowercase					=				model(lowercase			,     labels=lowercase   )
									self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.type_sequence_label_size)   )





			def 		snake_case__			(				self	:       List[str]			,     lowercase	:       List[str]			,     lowercase	:       Optional[int]			,     lowercase	:       Tuple			,     lowercase	:       List[str]   )						->					str:
									"""simple docstring"""







									__lowercase					=				self.num_labels
									__lowercase					=				BeitForSemanticSegmentation(lowercase   )
									model.to(lowercase   )
									model.eval()
									__lowercase					=				model(lowercase   )
									self.parent.assertEqual(
									    result.logits.shape			,     (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)   )
									__lowercase					=				model(lowercase			,     labels=lowercase   )
									self.parent.assertEqual(
									    result.logits.shape			,     (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)   )







			def 		snake_case__			(				self	:       Optional[Any]   )						->					Union[str, Any]:
									"""simple docstring"""







									__lowercase					=				self.prepare_config_and_inputs()
									__lowercase	,			__lowercase	,			__lowercase	,			__lowercase					=				config_and_inputs
									__lowercase					=				{"""pixel_values""": pixel_values}
									return config, inputs_dict





@require_torch
class 			_lowerCAmelCase   ( _UpperCAmelCase    ,					_UpperCAmelCase    ,					unittest.TestCase			):






			"""simple docstring"""





			lowercase__      :  List[Any]      =			(
			    (BeitModel, BeitForImageClassification, BeitForMaskedImageModeling, BeitForSemanticSegmentation)
			    if is_torch_available()
			    else ()
			)
			lowercase__      :  int      =			(
			    {
			        """feature-extraction""": BeitModel,
			        """image-classification""": BeitForImageClassification,
			        """image-segmentation""": BeitForSemanticSegmentation,
			    }
			    if is_torch_available()
			    else {}
			)

			lowercase__      :  Dict      =			False
			lowercase__      :  Union[str, Any]      =			False
			lowercase__      :  List[str]      =			False





			def 		snake_case__			(				self	:       Union[str, Any]   )						->					Optional[Any]:
									"""simple docstring"""







									__lowercase					=				BeitModelTester(self   )
									__lowercase					=				ConfigTester(self			,     config_class=lowercase			,     has_text_modality=lowercase			,     hidden_size=37   )





			def 		snake_case__			(				self	:       List[Any]   )						->					str:
									"""simple docstring"""







									self.config_tester.run_common_tests()





			@unittest.skip(reason="""BEiT does not use inputs_embeds"""   )
			def 		snake_case__			(				self	:       Optional[int]   )						->					List[str]:
									"""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 		snake_case__			(				self	:       Any   )						->					List[Any]:
									"""simple docstring"""







									pass





			def 		snake_case__			(				self	:       Union[str, Any]   )						->					Dict:
									"""simple docstring"""







									__lowercase	,			__lowercase					=				self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
															__lowercase					=				model_class(lowercase   )
															self.assertIsInstance(model.get_input_embeddings()			,     (nn.Module)   )
															__lowercase					=				model.get_output_embeddings()
															self.assertTrue(x is None or isinstance(lowercase			,     nn.Linear   )   )





			def 		snake_case__			(				self	:       Optional[int]   )						->					int:
									"""simple docstring"""







									__lowercase	,			__lowercase					=				self.model_tester.prepare_config_and_inputs_for_common()

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

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





			def 		snake_case__			(				self	:       Dict   )						->					int:
									"""simple docstring"""







									__lowercase					=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowercase   )





			def 		snake_case__			(				self	:       Union[str, Any]   )						->					int:
									"""simple docstring"""







									__lowercase					=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_masked_lm(*lowercase   )





			def 		snake_case__			(				self	:       Dict   )						->					str:
									"""simple docstring"""







									__lowercase					=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*lowercase   )





			def 		snake_case__			(				self	:       Tuple   )						->					List[str]:
									"""simple docstring"""







									__lowercase					=				self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_semantic_segmentation(*lowercase   )





			def 		snake_case__			(				self	:       Any   )						->					Dict:
									"""simple docstring"""







									if not self.model_tester.is_training:
															return

									__lowercase	,			__lowercase					=				self.model_tester.prepare_config_and_inputs_for_common()
									__lowercase					=				True

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

															__lowercase					=				model_class(lowercase   )
															model.to(lowercase   )
															model.train()
															__lowercase					=				self._prepare_for_class(lowercase			,     lowercase			,     return_labels=lowercase   )
															__lowercase					=				model(**lowercase   ).loss
															loss.backward()





			def 		snake_case__			(				self	:       List[Any]   )						->					int:
									"""simple docstring"""







									__lowercase	,			__lowercase					=				self.model_tester.prepare_config_and_inputs_for_common()
									if not self.model_tester.is_training:
															return

									__lowercase					=				False
									__lowercase					=				True

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

															__lowercase					=				model_class(lowercase   )
															model.gradient_checkpointing_enable()
															model.to(lowercase   )
															model.train()
															__lowercase					=				self._prepare_for_class(lowercase			,     lowercase			,     return_labels=lowercase   )
															__lowercase					=				model(**lowercase   ).loss
															loss.backward()





			def 		snake_case__			(				self	:       Optional[Any]   )						->					List[str]:
									"""simple docstring"""







									__lowercase	,			__lowercase					=				self.model_tester.prepare_config_and_inputs_for_common()

									__lowercase					=				_config_zero_init(lowercase   )
									for model_class in self.all_model_classes:
															__lowercase					=				model_class(config=lowercase   )
															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 		snake_case__			(				self	:       str   )						->					str:
									"""simple docstring"""







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






def  UpperCAmelCase__    (    ) ->      int:
						__lowercase					=				Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   )
						return image







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






			"""simple docstring"""





			@cached_property
			def 		snake_case__			(				self	:       List[str]   )						->					int:
									"""simple docstring"""







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





			@slow
			def 		snake_case__			(				self	:       int   )						->					Optional[int]:
									"""simple docstring"""







									__lowercase					=				BeitForMaskedImageModeling.from_pretrained("""microsoft/beit-base-patch16-224-pt22k"""   ).to(lowercase   )

									__lowercase					=				self.default_image_processor
									__lowercase					=				prepare_img()
									__lowercase					=				image_processor(images=lowercase			,     return_tensors="""pt"""   ).pixel_values.to(lowercase   )

									# prepare bool_masked_pos
									__lowercase					=				torch.ones((1, 196)			,     dtype=torch.bool   ).to(lowercase   )

									# forward pass
									with torch.no_grad():
															__lowercase					=				model(pixel_values=lowercase			,     bool_masked_pos=lowercase   )
									__lowercase					=				outputs.logits

									# verify the logits
									__lowercase					=				torch.Size((1, 196, 8_192)   )
									self.assertEqual(logits.shape			,     lowercase   )

									__lowercase					=				torch.tensor(
									    [[-3.2437, 0.5072, -13.9174], [-3.2456, 0.4948, -13.9401], [-3.2033, 0.5121, -13.8550]]   ).to(lowercase   )

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





			@slow
			def 		snake_case__			(				self	:       List[str]   )						->					Optional[Any]:
									"""simple docstring"""







									__lowercase					=				BeitForImageClassification.from_pretrained("""microsoft/beit-base-patch16-224"""   ).to(lowercase   )

									__lowercase					=				self.default_image_processor
									__lowercase					=				prepare_img()
									__lowercase					=				image_processor(images=lowercase			,     return_tensors="""pt"""   ).to(lowercase   )

									# forward pass
									with torch.no_grad():
															__lowercase					=				model(**lowercase   )
									__lowercase					=				outputs.logits

									# verify the logits
									__lowercase					=				torch.Size((1, 1_000)   )
									self.assertEqual(logits.shape			,     lowercase   )

									__lowercase					=				torch.tensor([-1.2385, -1.0987, -1.0108]   ).to(lowercase   )

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

									__lowercase					=				281
									self.assertEqual(logits.argmax(-1   ).item()			,     lowercase   )





			@slow
			def 		snake_case__			(				self	:       List[Any]   )						->					List[str]:
									"""simple docstring"""







									__lowercase					=				BeitForImageClassification.from_pretrained("""microsoft/beit-large-patch16-224-pt22k-ft22k"""   ).to(
									    lowercase   )

									__lowercase					=				self.default_image_processor
									__lowercase					=				prepare_img()
									__lowercase					=				image_processor(images=lowercase			,     return_tensors="""pt"""   ).to(lowercase   )

									# forward pass
									with torch.no_grad():
															__lowercase					=				model(**lowercase   )
									__lowercase					=				outputs.logits

									# verify the logits
									__lowercase					=				torch.Size((1, 21_841)   )
									self.assertEqual(logits.shape			,     lowercase   )

									__lowercase					=				torch.tensor([1.6881, -0.2787, 0.5901]   ).to(lowercase   )

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

									__lowercase					=				2_396
									self.assertEqual(logits.argmax(-1   ).item()			,     lowercase   )





			@slow
			def 		snake_case__			(				self	:       Tuple   )						->					List[Any]:
									"""simple docstring"""







									__lowercase					=				BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640"""   )
									__lowercase					=				model.to(lowercase   )

									__lowercase					=				BeitImageProcessor(do_resize=lowercase			,     size=640			,     do_center_crop=lowercase   )

									__lowercase					=				load_dataset("""hf-internal-testing/fixtures_ade20k"""			,     split="""test"""   )
									__lowercase					=				Image.open(ds[0]["""file"""]   )
									__lowercase					=				image_processor(images=lowercase			,     return_tensors="""pt"""   ).to(lowercase   )

									# forward pass
									with torch.no_grad():
															__lowercase					=				model(**lowercase   )
									__lowercase					=				outputs.logits

									# verify the logits
									__lowercase					=				torch.Size((1, 150, 160, 160)   )
									self.assertEqual(logits.shape			,     lowercase   )

									__lowercase					=				version.parse(PIL.__version__   ) < version.parse("""9.0.0"""   )

									if is_pillow_less_than_a:
															__lowercase					=				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=lowercase			,     )
									else:
															__lowercase					=				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=lowercase			,     )

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







			@slow
			def 		snake_case__			(				self	:       Dict   )						->					Union[str, Any]:
									"""simple docstring"""







									__lowercase					=				BeitForSemanticSegmentation.from_pretrained("""microsoft/beit-base-finetuned-ade-640-640"""   )
									__lowercase					=				model.to(lowercase   )

									__lowercase					=				BeitImageProcessor(do_resize=lowercase			,     size=640			,     do_center_crop=lowercase   )

									__lowercase					=				load_dataset("""hf-internal-testing/fixtures_ade20k"""			,     split="""test"""   )
									__lowercase					=				Image.open(ds[0]["""file"""]   )
									__lowercase					=				image_processor(images=lowercase			,     return_tensors="""pt"""   ).to(lowercase   )

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

									__lowercase					=				outputs.logits.detach().cpu()

									__lowercase					=				image_processor.post_process_semantic_segmentation(outputs=lowercase			,     target_sizes=[(500, 300)]   )
									__lowercase					=				torch.Size((500, 300)   )
									self.assertEqual(segmentation[0].shape			,     lowercase   )

									__lowercase					=				image_processor.post_process_semantic_segmentation(outputs=lowercase   )
									__lowercase					=				torch.Size((160, 160)   )
									self.assertEqual(segmentation[0].shape			,     lowercase   )










import unittest

import numpy as np






def  UpperCAmelCase__    (    lowercase__						,       lowercase__						,       lowercase__						,       lowercase__ = None						,       ) ->      np.ndarray:
						__lowercase					=				np.shape(lowercase__   )
						__lowercase					=				np.shape(lowercase__   )
						__lowercase					=				np.shape(lowercase__   )

						if shape_a[0] != shape_b[0]:
												__lowercase					=				(
												    """Expected the same number of rows for A and B. """
												    F"Instead found A of size {shape_a} and B of size {shape_b}"
												)
												raise ValueError(lowercase__   )

						if shape_b[1] != shape_c[1]:
												__lowercase					=				(
												    """Expected the same number of columns for B and C. """
												    F"Instead found B of size {shape_b} and C of size {shape_c}"
												)
												raise ValueError(lowercase__   )

						__lowercase					=				pseudo_inv
						if a_inv is None:
												try:
																		__lowercase					=				np.linalg.inv(lowercase__   )
												except np.linalg.LinAlgError:
																		raise ValueError(
																		    """Input matrix A is not invertible. Cannot compute Schur complement."""   )

						return mat_c - mat_b.T @ a_inv @ mat_b
class 			_lowerCAmelCase   ( unittest.TestCase			):






			"""simple docstring"""





			def 		snake_case__			(				self	:       Dict   )						->					None:
									"""simple docstring"""







									__lowercase					=				np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]   )
									__lowercase					=				np.array([[0, 3], [3, 0], [2, 3]]   )
									__lowercase					=				np.array([[2, 1], [6, 3]]   )

									__lowercase					=				schur_complement(lowercase			,     lowercase			,     lowercase   )

									__lowercase					=				np.block([[a, b], [b.T, c]]   )

									__lowercase					=				np.linalg.det(lowercase   )
									__lowercase					=				np.linalg.det(lowercase   )
									__lowercase					=				np.linalg.det(lowercase   )

									self.assertAlmostEqual(lowercase			,     det_a * det_s   )





			def 		snake_case__			(				self	:       Tuple   )						->					None:
									"""simple docstring"""







									__lowercase					=				np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]   )
									__lowercase					=				np.array([[0, 3], [3, 0], [2, 3]]   )
									__lowercase					=				np.array([[2, 1], [6, 3]]   )

									with self.assertRaises(lowercase   ):
															schur_complement(lowercase			,     lowercase			,     lowercase   )







			def 		snake_case__			(				self	:       Tuple   )						->					None:
									"""simple docstring"""







									__lowercase					=				np.array([[1, 2, 1], [2, 1, 2], [3, 2, 4]]   )
									__lowercase					=				np.array([[0, 3], [3, 0], [2, 3]]   )
									__lowercase					=				np.array([[2, 1, 3], [6, 3, 5]]   )

									with self.assertRaises(lowercase   ):
															schur_complement(lowercase			,     lowercase			,     lowercase   )


if __name__ == "__main__":
			import doctest

			doctest.testmod()
			unittest.main()





