



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




							def __init__(			self	:			List[Any]							,							A_	:			Dict							,							A_	:			List[Any]=1_0_0							,							A_	:			Tuple=1_3							,							A_	:			Optional[int]=3_0							,							A_	:			str=2							,							A_	:			List[Any]=3							,							A_	:			str=True							,							A_	:			Optional[Any]=True							,							A_	:			int=3_2							,							A_	:			List[Any]=4							,							A_	:			Dict=4							,							A_	:			Optional[Any]=3_7							,							A_	:			str="gelu"							,							A_	:			List[Any]=0.1							,							A_	:			Union[str, Any]=0.1							,							A_	:			Any=1_0							,							A_	:			Tuple=0.02							,							A_	:			Any=3							,							A_	:			List[str]=None							,							A_	:			Tuple=[0, 1, 2, 3]							,							):
									lowerCAmelCase_     :	Optional[int]							   =					parent
									lowerCAmelCase_     :	Union[str, Any]							   =					1_0_0
									lowerCAmelCase_     :	List[str]							   =					batch_size
									lowerCAmelCase_     :	List[Any]							   =					image_size
									lowerCAmelCase_     :	List[Any]							   =					patch_size
									lowerCAmelCase_     :	int							   =					num_channels
									lowerCAmelCase_     :	Optional[Any]							   =					is_training
									lowerCAmelCase_     :	Optional[int]							   =					use_labels
									lowerCAmelCase_     :	Union[str, Any]							   =					hidden_size
									lowerCAmelCase_     :	List[Any]							   =					num_hidden_layers
									lowerCAmelCase_     :	List[str]							   =					num_attention_heads
									lowerCAmelCase_     :	Tuple							   =					intermediate_size
									lowerCAmelCase_     :	Optional[Any]							   =					hidden_act
									lowerCAmelCase_     :	int							   =					hidden_dropout_prob
									lowerCAmelCase_     :	str							   =					attention_probs_dropout_prob
									lowerCAmelCase_     :	Union[str, Any]							   =					type_sequence_label_size
									lowerCAmelCase_     :	Union[str, Any]							   =					initializer_range
									lowerCAmelCase_     :	Optional[int]							   =					scope
									lowerCAmelCase_     :	List[Any]							   =					out_indices
									lowerCAmelCase_     :	Optional[Any]							   =					num_labels

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




							def   UpperCAmelCase__     (			self	:			Optional[Any]):
									lowerCAmelCase_     :	Optional[int]							   =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size])

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

									lowerCAmelCase_     :	str							   =					self.get_config()

									return config, pixel_values, labels, pixel_labels




							def   UpperCAmelCase__     (			self	:			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=A_							,							initializer_range=self.initializer_range							,							out_indices=self.out_indices							,							)




							def   UpperCAmelCase__     (			self	:			Union[str, Any]							,							A_	:			Any							,							A_	:			Optional[int]							,							A_	:			str							,							A_	:			Tuple):
									lowerCAmelCase_     :	Optional[int]							   =					BeitModel(config=A_)
									model.to(A_)
									model.eval()
									lowerCAmelCase_     :	int							   =					model(A_)
									self.parent.assertEqual(result.last_hidden_state.shape							,							(self.batch_size, self.seq_length, self.hidden_size))




							def   UpperCAmelCase__     (			self	:			Dict							,							A_	:			Tuple							,							A_	:			int							,							A_	:			List[str]							,							A_	:			Dict):
									lowerCAmelCase_     :	Tuple							   =					BeitForMaskedImageModeling(config=A_)
									model.to(A_)
									model.eval()
									lowerCAmelCase_     :	Optional[int]							   =					model(A_)
									self.parent.assertEqual(result.logits.shape							,							(self.batch_size, self.seq_length - 1, self.vocab_size))




							def   UpperCAmelCase__     (			self	:			Optional[int]							,							A_	:			Any							,							A_	:			Tuple							,							A_	:			int							,							A_	:			Dict):
									lowerCAmelCase_     :	List[str]							   =					self.type_sequence_label_size
									lowerCAmelCase_     :	List[str]							   =					BeitForImageClassification(A_)
									model.to(A_)
									model.eval()
									lowerCAmelCase_     :	int							   =					model(A_							,							labels=A_)
									self.parent.assertEqual(result.logits.shape							,							(self.batch_size, self.type_sequence_label_size))

									# test greyscale images
									lowerCAmelCase_     :	Union[str, Any]							   =					1
									lowerCAmelCase_     :	str							   =					BeitForImageClassification(A_)
									model.to(A_)
									model.eval()

									lowerCAmelCase_     :	str							   =					floats_tensor([self.batch_size, 1, self.image_size, self.image_size])
									lowerCAmelCase_     :	Dict							   =					model(A_							,							labels=A_)
									self.parent.assertEqual(result.logits.shape							,							(self.batch_size, self.type_sequence_label_size))




							def   UpperCAmelCase__     (			self	:			int							,							A_	:			List[str]							,							A_	:			Optional[Any]							,							A_	:			int							,							A_	:			Union[str, Any]):
									lowerCAmelCase_     :	Optional[Any]							   =					self.num_labels
									lowerCAmelCase_     :	Union[str, Any]							   =					BeitForSemanticSegmentation(A_)
									model.to(A_)
									model.eval()
									lowerCAmelCase_     :	str							   =					model(A_)
									self.parent.assertEqual(
									    result.logits.shape							,							(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2))
									lowerCAmelCase_     :	Optional[int]							   =					model(A_							,							labels=A_)
									self.parent.assertEqual(
									    result.logits.shape							,							(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2))







							def   UpperCAmelCase__     (			self	:			List[str]):
									lowerCAmelCase_     :	Union[str, Any]							   =					self.prepare_config_and_inputs()
									lowerCAmelCase_   ,    lowerCAmelCase_   ,    lowerCAmelCase_   ,    lowerCAmelCase_     :	str							   =					config_and_inputs
									lowerCAmelCase_     :	str							   =					{'''pixel_values''': pixel_values}
									return config, inputs_dict





@require_torch
class 							__snake_case		(	snake_case_		,snake_case_		,unittest.TestCase		):
							_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	:			str):
									lowerCAmelCase_     :	Tuple							   =					BeitModelTester(self)
									lowerCAmelCase_     :	int							   =					ConfigTester(self							,							config_class=A_							,							has_text_modality=A_							,							hidden_size=3_7)




							def   UpperCAmelCase__     (			self	:			Union[str, Any]):
									self.config_tester.run_common_tests()




							@unittest.skip(reason='''BEiT does not use inputs_embeds''')
							def   UpperCAmelCase__     (			self	:			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   UpperCAmelCase__     (			self	:			Dict):
									pass




							def   UpperCAmelCase__     (			self	:			Union[str, Any]):
									lowerCAmelCase_   ,    lowerCAmelCase_     :	Optional[Any]							   =					self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
											lowerCAmelCase_     :	Optional[int]							   =					model_class(A_)
											self.assertIsInstance(model.get_input_embeddings()							,							(nn.Module))
											lowerCAmelCase_     :	Dict							   =					model.get_output_embeddings()
											self.assertTrue(x is None or isinstance(A_							,							nn.Linear))




							def   UpperCAmelCase__     (			self	:			List[Any]):
									lowerCAmelCase_   ,    lowerCAmelCase_     :	str							   =					self.model_tester.prepare_config_and_inputs_for_common()

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

											lowerCAmelCase_     :	str							   =					['''pixel_values''']
											self.assertListEqual(arg_names[:1]							,							A_)




							def   UpperCAmelCase__     (			self	:			int):
									lowerCAmelCase_     :	Dict							   =					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*A_)




							def   UpperCAmelCase__     (			self	:			Optional[int]):
									lowerCAmelCase_     :	Any							   =					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_masked_lm(*A_)




							def   UpperCAmelCase__     (			self	:			Dict):
									lowerCAmelCase_     :	List[str]							   =					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*A_)




							def   UpperCAmelCase__     (			self	:			List[Any]):
									lowerCAmelCase_     :	str							   =					self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_semantic_segmentation(*A_)




							def   UpperCAmelCase__     (			self	:			Union[str, Any]):






									if not self.model_tester.is_training:
											return

									lowerCAmelCase_   ,    lowerCAmelCase_     :	Optional[int]							   =					self.model_tester.prepare_config_and_inputs_for_common()
									lowerCAmelCase_     :	str							   =					True

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

											lowerCAmelCase_     :	Optional[Any]							   =					model_class(A_)
											model.to(A_)
											model.train()
											lowerCAmelCase_     :	int							   =					self._prepare_for_class(A_							,							A_							,							return_labels=A_)
											lowerCAmelCase_     :	Tuple							   =					model(**A_).loss
											loss.backward()




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

									lowerCAmelCase_     :	Tuple							   =					False
									lowerCAmelCase_     :	Union[str, Any]							   =					True

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

											lowerCAmelCase_     :	str							   =					model_class(A_)
											model.gradient_checkpointing_enable()
											model.to(A_)
											model.train()
											lowerCAmelCase_     :	Any							   =					self._prepare_for_class(A_							,							A_							,							return_labels=A_)
											lowerCAmelCase_     :	Dict							   =					model(**A_).loss
											loss.backward()




							def   UpperCAmelCase__     (			self	:			Any):
									lowerCAmelCase_   ,    lowerCAmelCase_     :	Optional[int]							   =					self.model_tester.prepare_config_and_inputs_for_common()

									lowerCAmelCase_     :	Dict							   =					_config_zero_init(A_)
									for model_class in self.all_model_classes:
											lowerCAmelCase_     :	Union[str, Any]							   =					model_class(config=A_)
											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	:			Dict):






									for model_name in BEIT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
											lowerCAmelCase_     :	List[str]							   =					BeitModel.from_pretrained(A_)
											self.assertIsNotNone(A_)





def      UpperCamelCase(    ):
		lowerCAmelCase_     :	Tuple							   =					Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''					)
		return image





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




							@cached_property
							def   UpperCAmelCase__     (			self	:			Tuple):
									return BeitImageProcessor.from_pretrained('''microsoft/beit-base-patch16-224''') if is_vision_available() else None




							@slow
							def   UpperCAmelCase__     (			self	:			Optional[int]):
									lowerCAmelCase_     :	List[Any]							   =					BeitForMaskedImageModeling.from_pretrained('''microsoft/beit-base-patch16-224-pt22k''').to(A_)

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

									# prepare bool_masked_pos
									lowerCAmelCase_     :	Optional[int]							   =					torch.ones((1, 1_9_6)							,							dtype=torch.bool).to(A_)

									# forward pass
									with torch.no_grad():
											lowerCAmelCase_     :	List[str]							   =					model(pixel_values=A_							,							bool_masked_pos=A_)
									lowerCAmelCase_     :	Union[str, Any]							   =					outputs.logits

									# verify the logits
									lowerCAmelCase_     :	str							   =					torch.Size((1, 1_9_6, 8_1_9_2))
									self.assertEqual(logits.shape							,							A_)

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

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




							@slow
							def   UpperCAmelCase__     (			self	:			int):
									lowerCAmelCase_     :	Optional[Any]							   =					BeitForImageClassification.from_pretrained('''microsoft/beit-base-patch16-224''').to(A_)

									lowerCAmelCase_     :	Dict							   =					self.default_image_processor
									lowerCAmelCase_     :	str							   =					prepare_img()
									lowerCAmelCase_     :	Dict							   =					image_processor(images=A_							,							return_tensors='''pt''').to(A_)

									# forward pass
									with torch.no_grad():
											lowerCAmelCase_     :	List[str]							   =					model(**A_)
									lowerCAmelCase_     :	Optional[int]							   =					outputs.logits

									# verify the logits
									lowerCAmelCase_     :	Union[str, Any]							   =					torch.Size((1, 1_0_0_0))
									self.assertEqual(logits.shape							,							A_)

									lowerCAmelCase_     :	Optional[Any]							   =					torch.tensor([-1.2385, -1.0987, -1.0108]).to(A_)

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

									lowerCAmelCase_     :	Optional[Any]							   =					2_8_1
									self.assertEqual(logits.argmax(-1).item()							,							A_)




							@slow
							def   UpperCAmelCase__     (			self	:			Optional[Any]):
									lowerCAmelCase_     :	Union[str, Any]							   =					BeitForImageClassification.from_pretrained('''microsoft/beit-large-patch16-224-pt22k-ft22k''').to(
									    A_)

									lowerCAmelCase_     :	Tuple							   =					self.default_image_processor
									lowerCAmelCase_     :	Optional[Any]							   =					prepare_img()
									lowerCAmelCase_     :	Optional[int]							   =					image_processor(images=A_							,							return_tensors='''pt''').to(A_)

									# forward pass
									with torch.no_grad():
											lowerCAmelCase_     :	int							   =					model(**A_)
									lowerCAmelCase_     :	Dict							   =					outputs.logits

									# verify the logits
									lowerCAmelCase_     :	List[str]							   =					torch.Size((1, 2_1_8_4_1))
									self.assertEqual(logits.shape							,							A_)

									lowerCAmelCase_     :	Tuple							   =					torch.tensor([1.6881, -0.2787, 0.5901]).to(A_)

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

									lowerCAmelCase_     :	Union[str, Any]							   =					2_3_9_6
									self.assertEqual(logits.argmax(-1).item()							,							A_)




							@slow
							def   UpperCAmelCase__     (			self	:			Optional[Any]):
									lowerCAmelCase_     :	Any							   =					BeitForSemanticSegmentation.from_pretrained('''microsoft/beit-base-finetuned-ade-640-640''')
									lowerCAmelCase_     :	Optional[int]							   =					model.to(A_)

									lowerCAmelCase_     :	str							   =					BeitImageProcessor(do_resize=A_							,							size=6_4_0							,							do_center_crop=A_)

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

									# forward pass
									with torch.no_grad():
											lowerCAmelCase_     :	Any							   =					model(**A_)
									lowerCAmelCase_     :	List[Any]							   =					outputs.logits

									# verify the logits
									lowerCAmelCase_     :	str							   =					torch.Size((1, 1_5_0, 1_6_0, 1_6_0))
									self.assertEqual(logits.shape							,							A_)

									lowerCAmelCase_     :	Union[str, Any]							   =					version.parse(PIL.__version__) < version.parse('''9.0.0''')

									if is_pillow_less_than_a:
											lowerCAmelCase_     :	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=A_							,							)
									else:
											lowerCAmelCase_     :	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=A_							,							)

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







							@slow
							def   UpperCAmelCase__     (			self	:			Any):
									lowerCAmelCase_     :	List[str]							   =					BeitForSemanticSegmentation.from_pretrained('''microsoft/beit-base-finetuned-ade-640-640''')
									lowerCAmelCase_     :	Optional[int]							   =					model.to(A_)

									lowerCAmelCase_     :	List[Any]							   =					BeitImageProcessor(do_resize=A_							,							size=6_4_0							,							do_center_crop=A_)

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

									# forward pass
									with torch.no_grad():
											lowerCAmelCase_     :	Tuple							   =					model(**A_)

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

									lowerCAmelCase_     :	List[str]							   =					image_processor.post_process_semantic_segmentation(outputs=A_							,							target_sizes=[(5_0_0, 3_0_0)])
									lowerCAmelCase_     :	Optional[Any]							   =					torch.Size((5_0_0, 3_0_0))
									self.assertEqual(segmentation[0].shape							,							A_)

									lowerCAmelCase_     :	Optional[Any]							   =					image_processor.post_process_semantic_segmentation(outputs=A_)
									lowerCAmelCase_     :	int							   =					torch.Size((1_6_0, 1_6_0))
									self.assertEqual(segmentation[0].shape							,							A_)







'''simple docstring'''
def 		A_(     A						:		list[int]):
							UpperCamelCase   			=     []
							if len(A) == 1:
														return [nums.copy()]
							for _ in range(len(A)):
														UpperCamelCase   			=     nums.pop(0)
														UpperCamelCase   			=     permute(A)
														for perm in permutations:
																					perm.append(A)
														result.extend(A)
														nums.append(A)
							return result







def 		A_(     A						:		str):

							def backtrack(A						:		str):
														if start == len(A) - 1:
																					output.append(nums[:])
														else:
																					for i in range(A		,     len(A)):
																												UpperCamelCase			,	UpperCamelCase   			=     nums[i], nums[start]
																												backtrack(start + 1)
																												UpperCamelCase			,	UpperCamelCase   			=     nums[i], nums[start]  # backtrack

							UpperCamelCase   			=     []
							backtrack(0)
							return output


if __name__ == "__main__":
						import doctest

						# use res to print the data in permute2 function
						lowerCAmelCase					:    Dict           = permutea([1, 2, 3])
						print(res)
						doctest.testmod()




