





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







					"""simple docstring"""






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

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






			def        a_	(      self       :   Optional[int]       )     ->     Optional[Any]:







					"""simple docstring"""






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

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

					A__  				=       self.get_config()

					return config, pixel_values, labels, pixel_labels






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







					"""simple docstring"""






					return BeitConfig(
					    vocab_size=self.vocab_size							,     image_size=self.image_size							,     patch_size=self.patch_size							,     num_channels=self.num_channels							,     hidden_size=self.hidden_size							,     num_hidden_layers=self.num_hidden_layers							,     num_attention_heads=self.num_attention_heads							,     intermediate_size=self.intermediate_size							,     hidden_act=self.hidden_act							,     hidden_dropout_prob=self.hidden_dropout_prob							,     attention_probs_dropout_prob=self.attention_probs_dropout_prob							,     is_decoder=__lowerCAmelCase							,     initializer_range=self.initializer_range							,     out_indices=self.out_indices							,     )






			def        a_	(      self       :   Any							,     __lowerCAmelCase       :   str							,     __lowerCAmelCase       :   List[Any]							,     __lowerCAmelCase       :   List[Any]							,     __lowerCAmelCase       :   Dict       )     ->     List[str]:







					"""simple docstring"""






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






			def        a_	(      self       :   Optional[int]							,     __lowerCAmelCase       :   Optional[Any]							,     __lowerCAmelCase       :   Optional[int]							,     __lowerCAmelCase       :   List[str]							,     __lowerCAmelCase       :   List[str]       )     ->     Dict:







					"""simple docstring"""






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






			def        a_	(      self       :   int							,     __lowerCAmelCase       :   str							,     __lowerCAmelCase       :   List[str]							,     __lowerCAmelCase       :   int							,     __lowerCAmelCase       :   Any       )     ->     str:







					"""simple docstring"""






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

					# test greyscale images
					A__  				=       1
					A__  				=       BeitForImageClassification(__lowerCAmelCase       )
					model.to(__lowerCAmelCase       )
					model.eval()

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






			def        a_	(      self       :   Optional[int]							,     __lowerCAmelCase       :   List[str]							,     __lowerCAmelCase       :   Union[str, Any]							,     __lowerCAmelCase       :   List[Any]							,     __lowerCAmelCase       :   List[Any]       )     ->     Optional[Any]:







					"""simple docstring"""






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







			def        a_	(      self       :   str       )     ->     Dict:







					"""simple docstring"""






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


@require_torch
class   A      (SCREAMING_SNAKE_CASE       ,					SCREAMING_SNAKE_CASE       ,					unittest.TestCase   ):
			'''simple docstring'''




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

			__lowerCamelCase     :	int          =   False
			__lowerCamelCase     :	int          =   False
			__lowerCamelCase     :	Dict          =   False






			def        a_	(      self       :   Optional[int]       )     ->     str:







					"""simple docstring"""






					A__  				=       BeitModelTester(self       )
					A__  				=       ConfigTester(self							,     config_class=__lowerCAmelCase							,     has_text_modality=__lowerCAmelCase							,     hidden_size=37       )






			def        a_	(      self       :   int       )     ->     str:







					"""simple docstring"""






					self.config_tester.run_common_tests()






			@unittest.skip(reason="""BEiT does not use inputs_embeds"""       )
			def        a_	(      self       :   Union[str, Any]       )     ->     Tuple:







					"""simple docstring"""






					pass






			@require_torch_multi_gpu
			@unittest.skip(reason="""BEiT has some layers using `add_module` which doesn't work well with `nn.DataParallel`"""       )
			def        a_	(      self       :   List[str]       )     ->     Tuple:







					"""simple docstring"""






					pass






			def        a_	(      self       :   Dict       )     ->     Dict:







					"""simple docstring"""






					A__				,      A__  				=       self.model_tester.prepare_config_and_inputs_for_common()

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






			def        a_	(      self       :   Optional[int]       )     ->     Tuple:







					"""simple docstring"""






					A__				,      A__  				=       self.model_tester.prepare_config_and_inputs_for_common()

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

							A__  				=       ["""pixel_values"""]
							self.assertListEqual(arg_names[:1]							,     __lowerCAmelCase       )






			def        a_	(      self       :   Optional[Any]       )     ->     Optional[int]:







					"""simple docstring"""






					A__  				=       self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*__lowerCAmelCase       )






			def        a_	(      self       :   int       )     ->     Optional[Any]:







					"""simple docstring"""






					A__  				=       self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_masked_lm(*__lowerCAmelCase       )






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







					"""simple docstring"""






					A__  				=       self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase       )






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







					"""simple docstring"""






					A__  				=       self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_semantic_segmentation(*__lowerCAmelCase       )






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







					"""simple docstring"""






					if not self.model_tester.is_training:
							return

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

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

							A__  				=       model_class(__lowerCAmelCase       )
							model.to(__lowerCAmelCase       )
							model.train()
							A__  				=       self._prepare_for_class(__lowerCAmelCase							,     __lowerCAmelCase							,     return_labels=__lowerCAmelCase       )
							A__  				=       model(**__lowerCAmelCase       ).loss
							loss.backward()






			def        a_	(      self       :   List[str]       )     ->     int:







					"""simple docstring"""






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

					A__  				=       False
					A__  				=       True

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

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






			def        a_	(      self       :   Optional[int]       )     ->     List[str]:







					"""simple docstring"""






					A__				,      A__  				=       self.model_tester.prepare_config_and_inputs_for_common()

					A__  				=       _config_zero_init(__lowerCAmelCase       )
					for model_class in self.all_model_classes:
							A__  				=       model_class(config=__lowerCAmelCase       )
							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        a_	(      self       :   Optional[Any]       )     ->     Tuple:







					"""simple docstring"""






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







def        __lowerCamelCase (							)		->    int:






		"""simple docstring"""

		A__  				=       Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""   )
		return image






@require_torch
@require_vision
class   A      (unittest.TestCase   ):
			'''simple docstring'''




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







					"""simple docstring"""






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






			@slow
			def        a_	(      self       :   List[Any]       )     ->     Dict:







					"""simple docstring"""






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

					A__  				=       self.default_image_processor
					A__  				=       prepare_img()
					A__  				=       image_processor(images=__lowerCAmelCase							,     return_tensors="""pt"""       ).pixel_values.to(__lowerCAmelCase       )

					# prepare bool_masked_pos
					A__  				=       torch.ones((1, 1_96)							,     dtype=torch.bool       ).to(__lowerCAmelCase       )

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

					# verify the logits
					A__  				=       torch.Size((1, 1_96, 81_92)       )
					self.assertEqual(logits.shape							,     __lowerCAmelCase       )

					A__  				=       torch.tensor(
					    [[-3.2_4_3_7, 0.5_0_7_2, -13.91_74], [-3.2_4_5_6, 0.4_9_4_8, -13.94_01], [-3.2_0_3_3, 0.5_1_2_1, -13.85_50]]       ).to(__lowerCAmelCase       )

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






			@slow
			def        a_	(      self       :   Any       )     ->     Tuple:







					"""simple docstring"""






					A__  				=       BeitForImageClassification.from_pretrained("""microsoft/beit-base-patch16-224"""       ).to(__lowerCAmelCase       )

					A__  				=       self.default_image_processor
					A__  				=       prepare_img()
					A__  				=       image_processor(images=__lowerCAmelCase							,     return_tensors="""pt"""       ).to(__lowerCAmelCase       )

					# forward pass
					with torch.no_grad():
							A__  				=       model(**__lowerCAmelCase       )
					A__  				=       outputs.logits

					# verify the logits
					A__  				=       torch.Size((1, 10_00)       )
					self.assertEqual(logits.shape							,     __lowerCAmelCase       )

					A__  				=       torch.tensor([-1.2_3_8_5, -1.0_9_8_7, -1.0_1_0_8]       ).to(__lowerCAmelCase       )

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

					A__  				=       2_81
					self.assertEqual(logits.argmax(-1       ).item()							,     __lowerCAmelCase       )






			@slow
			def        a_	(      self       :   Dict       )     ->     Tuple:







					"""simple docstring"""






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

					A__  				=       self.default_image_processor
					A__  				=       prepare_img()
					A__  				=       image_processor(images=__lowerCAmelCase							,     return_tensors="""pt"""       ).to(__lowerCAmelCase       )

					# forward pass
					with torch.no_grad():
							A__  				=       model(**__lowerCAmelCase       )
					A__  				=       outputs.logits

					# verify the logits
					A__  				=       torch.Size((1, 2_18_41)       )
					self.assertEqual(logits.shape							,     __lowerCAmelCase       )

					A__  				=       torch.tensor([1.6_8_8_1, -0.2_7_8_7, 0.5_9_0_1]       ).to(__lowerCAmelCase       )

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

					A__  				=       23_96
					self.assertEqual(logits.argmax(-1       ).item()							,     __lowerCAmelCase       )






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







					"""simple docstring"""






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

					A__  				=       BeitImageProcessor(do_resize=__lowerCAmelCase							,     size=6_40							,     do_center_crop=__lowerCAmelCase       )

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

					# forward pass
					with torch.no_grad():
							A__  				=       model(**__lowerCAmelCase       )
					A__  				=       outputs.logits

					# verify the logits
					A__  				=       torch.Size((1, 1_50, 1_60, 1_60)       )
					self.assertEqual(logits.shape							,     __lowerCAmelCase       )

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

					if is_pillow_less_than_a:
							A__  				=       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=__lowerCAmelCase							,     )
					else:
							A__  				=       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=__lowerCAmelCase							,     )

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







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







					"""simple docstring"""






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

					A__  				=       BeitImageProcessor(do_resize=__lowerCAmelCase							,     size=6_40							,     do_center_crop=__lowerCAmelCase       )

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

					# forward pass
					with torch.no_grad():
							A__  				=       model(**__lowerCAmelCase       )

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

					A__  				=       image_processor.post_process_semantic_segmentation(outputs=__lowerCAmelCase							,     target_sizes=[(5_00, 3_00)]       )
					A__  				=       torch.Size((5_00, 3_00)       )
					self.assertEqual(segmentation[0].shape							,     __lowerCAmelCase       )

					A__  				=       image_processor.post_process_semantic_segmentation(outputs=__lowerCAmelCase       )
					A__  				=       torch.Size((1_60, 1_60)       )
					self.assertEqual(segmentation[0].shape							,     __lowerCAmelCase       )










from typing import TYPE_CHECKING

from ...utils import _LazyModule


A   : Optional[Any]			=				{'''processing_wav2vec2_with_lm''': ['''Wav2Vec2ProcessorWithLM''']}


if TYPE_CHECKING:
					from .processing_wavaveca_with_lm import WavaVecaProcessorWithLM
else:
					import sys

					A   : List[str]			=				_LazyModule(__name__, globals()['''__file__'''], _import_structure, module_spec=__spec__)



