



'''simple docstring'''





import inspect
import unittest

from transformers import DataaVecVisionConfig
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,
		    DataaVecVisionForImageClassification,
		    DataaVecVisionForSemanticSegmentation,
		    DataaVecVisionModel,
		)
		from transformers.models.dataavec.modeling_dataavec_vision import DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
		from PIL import Image

		from transformers import BeitImageProcessor

class      snake_case__       :







						"""simple docstring"""




						def __init__(     self      ,     __lowercase      ,     __lowercase=1_0_0      ,     __lowercase=1_3      ,     __lowercase=3_0      ,     __lowercase=2      ,     __lowercase=3      ,     __lowercase=True      ,     __lowercase=True      ,     __lowercase=3_2      ,     __lowercase=4      ,     __lowercase=4      ,     __lowercase=3_7      ,     __lowercase="gelu"      ,     __lowercase=0.1      ,     __lowercase=0.1      ,     __lowercase=1_0      ,     __lowercase=0.0_2      ,     __lowercase=3      ,     __lowercase=None      ,     __lowercase=[0, 1, 2, 3]      ,     )      ->   str:
									"""simple docstring"""




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

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

						def 							SCREAMING_SNAKE_CASE__(     self						)      ->   Dict:
									"""simple docstring"""




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

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

									a__     :		Tuple		 =						self.get_config()

									return config, pixel_values, labels, pixel_labels

						def 							SCREAMING_SNAKE_CASE__(     self						)      ->   int:
									"""simple docstring"""




									return DataaVecVisionConfig(
									    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 							SCREAMING_SNAKE_CASE__(     self      ,     __lowercase      ,     __lowercase      ,     __lowercase      ,     __lowercase						)      ->   List[Any]:
									"""simple docstring"""




									a__     :		Dict		 =						DataaVecVisionModel(config=__lowercase						)
									model.to(__lowercase						)
									model.eval()
									a__     :		Optional[Any]		 =						model(__lowercase						)
									# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
									a__     :		Dict		 =						(self.image_size // self.patch_size) ** 2
									self.parent.assertEqual(result.last_hidden_state.shape      ,     (self.batch_size, num_patches + 1, self.hidden_size)						)

						def 							SCREAMING_SNAKE_CASE__(     self      ,     __lowercase      ,     __lowercase      ,     __lowercase      ,     __lowercase						)      ->   List[Any]:
									"""simple docstring"""




									a__     :		Union[str, Any]		 =						self.type_sequence_label_size
									a__     :		List[Any]		 =						DataaVecVisionForImageClassification(__lowercase						)
									model.to(__lowercase						)
									model.eval()
									a__     :		Optional[int]		 =						model(__lowercase      ,     labels=__lowercase						)
									self.parent.assertEqual(result.logits.shape      ,     (self.batch_size, self.type_sequence_label_size)						)

						def 							SCREAMING_SNAKE_CASE__(     self      ,     __lowercase      ,     __lowercase      ,     __lowercase      ,     __lowercase						)      ->   str:
									"""simple docstring"""




									a__     :		Dict		 =						self.num_labels
									a__     :		Optional[Any]		 =						DataaVecVisionForSemanticSegmentation(__lowercase						)
									model.to(__lowercase						)
									model.eval()
									a__     :		Tuple		 =						model(__lowercase						)
									self.parent.assertEqual(
									    result.logits.shape      ,     (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)						)
									a__     :		Tuple		 =						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 							SCREAMING_SNAKE_CASE__(     self						)      ->   Optional[Any]:
									"""simple docstring"""




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




@require_torch
class      snake_case__       (lowercase_      ,			lowercase_      ,			unittest.TestCase	):







						"""simple docstring"""




						__lowerCAmelCase  :str			      =  (
						    (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
						    if is_torch_available()
						    else ()
						)
						__lowerCAmelCase  :Union[str, Any]			      =  (
						    {
						        """feature-extraction""": DataaVecVisionModel,
						        """image-classification""": DataaVecVisionForImageClassification,
						        """image-segmentation""": DataaVecVisionForSemanticSegmentation,
						    }
						    if is_torch_available()
						    else {}
						)

						__lowerCAmelCase  :Tuple			      =  False
						__lowerCAmelCase  :Union[str, Any]			      =  False
						__lowerCAmelCase  :Dict			      =  False

						def 							SCREAMING_SNAKE_CASE__(     self						)      ->   Dict:
									"""simple docstring"""




									a__     :		int		 =						DataaVecVisionModelTester(self						)
									a__     :		int		 =						ConfigTester(
									    self      ,     config_class=__lowercase      ,     has_text_modality=__lowercase      ,     hidden_size=3_7						)

						def 							SCREAMING_SNAKE_CASE__(     self						)      ->   str:
									"""simple docstring"""




									self.config_tester.run_common_tests()

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




									pass

						@require_torch_multi_gpu
						@unittest.skip(
						    reason="""Data2VecVision has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`"""						)
						def 							SCREAMING_SNAKE_CASE__(     self						)      ->   int:
									"""simple docstring"""




									pass

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




									a__ ,		a__     :		Tuple		 =						self.model_tester.prepare_config_and_inputs_for_common()

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

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




									a__ ,		a__     :		Optional[int]		 =						self.model_tester.prepare_config_and_inputs_for_common()

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

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

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




									a__     :		Optional[Any]		 =						self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*__lowercase						)

						def 							SCREAMING_SNAKE_CASE__(     self						)      ->   Any:
									"""simple docstring"""




									a__     :		Dict		 =						self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_segmentation(*__lowercase						)

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




									if not self.model_tester.is_training:
												return

									a__ ,		a__     :		List[Any]		 =						self.model_tester.prepare_config_and_inputs_for_common()
									a__     :		Dict		 =						True

									for model_class in self.all_model_classes:
												if model_class in [*get_values(__lowercase						)]:
															continue

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

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




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

									a__     :		Optional[int]		 =						False
									a__     :		Optional[Any]		 =						True

									for model_class in self.all_model_classes:
												if model_class in [*get_values(__lowercase						)] or not model_class.supports_gradient_checkpointing:
															continue
												# TODO: remove the following 3 lines once we have a MODEL_FOR_SEMANTIC_SEGMENTATION_MAPPING
												# this can then be incorporated into _prepare_for_class in test_modeling_common.py
												elif model_class.__name__ == "Data2VecVisionForSemanticSegmentation":
															a__ ,		a__ ,		a__ ,		a__     :		Union[str, Any]		 =						inputs_dict["""pixel_values"""].shape
															a__     :		List[str]		 =						torch.zeros(
															    [self.model_tester.batch_size, height, width]      ,     device=__lowercase						).long()
												a__     :		Dict		 =						model_class(__lowercase						)
												model.gradient_checkpointing_enable()
												model.to(__lowercase						)
												model.train()
												a__     :		Any		 =						self._prepare_for_class(__lowercase      ,     __lowercase      ,     return_labels=__lowercase						)
												a__     :		List[Any]		 =						model(**__lowercase						).loss
												loss.backward()

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




									a__ ,		a__     :		Any		 =						self.model_tester.prepare_config_and_inputs_for_common()

									a__     :		Optional[int]		 =						_config_zero_init(__lowercase						)
									for model_class in self.all_model_classes:
												a__     :		Optional[Any]		 =						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'''      ,     )

						def 							SCREAMING_SNAKE_CASE__(     self      ,     __lowercase      ,     __lowercase      ,     __lowercase      ,     __lowercase=2E-4      ,     __lowercase="outputs"      ,     __lowercase=None						)      ->   Dict:
									"""simple docstring"""




									super().check_pt_tf_outputs(__lowercase      ,     __lowercase      ,     __lowercase      ,     __lowercase      ,     __lowercase      ,     __lowercase						)

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




									a__     :		Optional[Any]		 =						self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*__lowercase						)

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




									for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												a__     :		List[Any]		 =						DataaVecVisionModel.from_pretrained(__lowercase						)
												self.assertIsNotNone(__lowercase						)




def 			lowerCAmelCase_  (						)							-> Dict:







			"""simple docstring"""
			a__     :		Union[str, Any]		 =						Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""")
			return image





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







						"""simple docstring"""




						@cached_property
						def 							SCREAMING_SNAKE_CASE__(     self						)      ->   str:
									"""simple docstring"""




									return (
									    BeitImageProcessor.from_pretrained("""facebook/data2vec-vision-base-ft1k"""						) if is_vision_available() else None
									)

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




									a__     :		Tuple		 =						DataaVecVisionForImageClassification.from_pretrained("""facebook/data2vec-vision-base-ft1k"""						).to(
									    __lowercase						)

									a__     :		Tuple		 =						self.default_image_processor
									a__     :		List[Any]		 =						prepare_img()
									a__     :		Union[str, Any]		 =						image_processor(images=__lowercase      ,     return_tensors="""pt"""						).to(__lowercase						)

									# forward pass
									with torch.no_grad():
												a__     :		List[str]		 =						model(**__lowercase						)
									a__     :		Union[str, Any]		 =						outputs.logits

									# verify the logits
									a__     :		Optional[Any]		 =						torch.Size((1, 1_0_0_0)						)
									self.assertEqual(logits.shape      ,     __lowercase						)

									a__     :		Optional[int]		 =						torch.tensor([0.3_2_7_7, -0.1_3_9_5, 0.0_9_1_1]						).to(__lowercase						)

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

									a__     :		str		 =						[model.config.labelaid[i] for i in ["""remote control, remote""", """tabby, tabby cat"""]]
									self.assertEqual(logits[0].topk(2						).indices.cpu().tolist()      ,     __lowercase						)









from __future__ import annotations

def 			lowerCAmelCase_  (						_lowercase       :     list[int]		,     _lowercase       :     int)							-> list[int]:







			"""simple docstring"""
			a__     :		dict[int, int]		 =						{}
			for index, val in enumerate(_lowercase):
						a__     :		str		 =						target - val
						if compl in chk_map:
									return [chk_map[compl], index]
						a__     :		str		 =						index
			return []


if __name__ == "__main__":
		import doctest

		doctest.testmod()
		print(f'{two_sum([2, 7, 11, 15], 9) = }')




