






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





				"""simple docstring"""







				def __init__(					self				,    lowerCamelCase__				,    lowerCamelCase__=100				,    lowerCamelCase__=13				,    lowerCamelCase__=30				,    lowerCamelCase__=2				,    lowerCamelCase__=3				,    lowerCamelCase__=True				,    lowerCamelCase__=True				,    lowerCamelCase__=32				,    lowerCamelCase__=4				,    lowerCamelCase__=4				,    lowerCamelCase__=37				,    lowerCamelCase__="gelu"				,    lowerCamelCase__=0.1				,    lowerCamelCase__=0.1				,    lowerCamelCase__=10				,    lowerCamelCase__=0.02				,    lowerCamelCase__=3				,    lowerCamelCase__=None				,    lowerCamelCase__=[0, 1, 2, 3]				,    ):




									"""simple docstring"""

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

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


				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   int									=floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

									__UpperCamelCase :   str									=self.get_config()

									return config, pixel_values, labels, pixel_labels


				def  __lowercase				(					self       ):




									"""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=lowerCamelCase__				,    initializer_range=self.initializer_range				,    out_indices=self.out_indices				,    )


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									__UpperCamelCase :   str									=DataaVecVisionModel(config=lowerCamelCase__       )
									model.to(lowerCamelCase__       )
									model.eval()
									__UpperCamelCase :   Optional[int]									=model(lowerCamelCase__       )
									# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
									__UpperCamelCase :   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  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									__UpperCamelCase :   Tuple									=self.type_sequence_label_size
									__UpperCamelCase :   Tuple									=DataaVecVisionForImageClassification(lowerCamelCase__       )
									model.to(lowerCamelCase__       )
									model.eval()
									__UpperCamelCase :   Optional[int]									=model(lowerCamelCase__				,    labels=lowerCamelCase__       )
									self.parent.assertEqual(result.logits.shape				,    (self.batch_size, self.type_sequence_label_size)       )


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									__UpperCamelCase :   Any									=self.num_labels
									__UpperCamelCase :   List[str]									=DataaVecVisionForSemanticSegmentation(lowerCamelCase__       )
									model.to(lowerCamelCase__       )
									model.eval()
									__UpperCamelCase :   Dict									=model(lowerCamelCase__       )
									self.parent.assertEqual(
									    result.logits.shape				,    (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)       )
									__UpperCamelCase :   Optional[int]									=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  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   List[str]									=self.prepare_config_and_inputs()
									__UpperCamelCase						,							__UpperCamelCase						,							__UpperCamelCase						,							__UpperCamelCase :   Optional[Any]									=config_and_inputs
									__UpperCamelCase :   Optional[Any]									={'pixel_values': pixel_values}
									return config, inputs_dict




@require_torch
class 							__A	(     a ,	a ,	unittest.TestCase					):





				"""simple docstring"""







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

				UpperCamelCase__					: str     					=False
				UpperCamelCase__					: Optional[int]     					=False
				UpperCamelCase__					: Dict     					=False


				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   int									=DataaVecVisionModelTester(self       )
									__UpperCamelCase :   str									=ConfigTester(
									    self				,    config_class=lowerCamelCase__				,    has_text_modality=lowerCamelCase__				,    hidden_size=37       )


				def  __lowercase				(					self       ):




									"""simple docstring"""

									self.config_tester.run_common_tests()


				def  __lowercase				(					self       ):




									"""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  __lowercase				(					self       ):




									"""simple docstring"""

									pass


				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase						,							__UpperCamelCase :   List[str]									=self.model_tester.prepare_config_and_inputs_for_common()

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


				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase						,							__UpperCamelCase :   str									=self.model_tester.prepare_config_and_inputs_for_common()

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

														__UpperCamelCase :   Optional[int]									=['pixel_values']
														self.assertListEqual(arg_names[:1]				,    lowerCamelCase__       )


				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   List[str]									=self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*lowerCamelCase__       )


				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   List[Any]									=self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_segmentation(*lowerCamelCase__       )


				def  __lowercase				(					self       ):




									"""simple docstring"""

									if not self.model_tester.is_training:
														return

									__UpperCamelCase						,							__UpperCamelCase :   Dict									=self.model_tester.prepare_config_and_inputs_for_common()
									__UpperCamelCase :   Tuple									=True

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

														__UpperCamelCase :   Dict									=model_class(lowerCamelCase__       )
														model.to(lowerCamelCase__       )
														model.train()
														__UpperCamelCase :   Tuple									=self._prepare_for_class(lowerCamelCase__				,    lowerCamelCase__				,    return_labels=lowerCamelCase__       )
														__UpperCamelCase :   Union[str, Any]									=model(**lowerCamelCase__       ).loss
														loss.backward()


				def  __lowercase				(					self       ):




									"""simple docstring"""

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

									__UpperCamelCase :   str									=False
									__UpperCamelCase :   int									=True

									for model_class in self.all_model_classes:
														if model_class in [*get_values(lowerCamelCase__       )] 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":
																			__UpperCamelCase						,							__UpperCamelCase						,							__UpperCamelCase						,							__UpperCamelCase :   Tuple									=inputs_dict['pixel_values'].shape
																			__UpperCamelCase :   int									=torch.zeros(
																			    [self.model_tester.batch_size, height, width]				,    device=lowerCamelCase__       ).long()
														__UpperCamelCase :   Tuple									=model_class(lowerCamelCase__       )
														model.gradient_checkpointing_enable()
														model.to(lowerCamelCase__       )
														model.train()
														__UpperCamelCase :   str									=self._prepare_for_class(lowerCamelCase__				,    lowerCamelCase__				,    return_labels=lowerCamelCase__       )
														__UpperCamelCase :   Union[str, Any]									=model(**lowerCamelCase__       ).loss
														loss.backward()


				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase						,							__UpperCamelCase :   str									=self.model_tester.prepare_config_and_inputs_for_common()

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


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__=2E-4				,    lowerCamelCase__="outputs"				,    lowerCamelCase__=None       ):




									"""simple docstring"""

									super().check_pt_tf_outputs(lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       )


				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   int									=self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_for_image_classification(*lowerCamelCase__       )







				@slow
				def  __lowercase				(					self       ):




									"""simple docstring"""

									for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
														__UpperCamelCase :   Union[str, Any]									=DataaVecVisionModel.from_pretrained(lowerCamelCase__       )
														self.assertIsNotNone(lowerCamelCase__       )






def 				A	(			)	->		Any:
					__UpperCamelCase :   Union[str, Any]									=Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'   )
					return image




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





				"""simple docstring"""







				@cached_property
				def  __lowercase				(					self       ):




									"""simple docstring"""

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







				@slow
				def  __lowercase				(					self       ):




									"""simple docstring"""

									__UpperCamelCase :   Union[str, Any]									=DataaVecVisionForImageClassification.from_pretrained('facebook/data2vec-vision-base-ft1k'       ).to(
									    lowerCamelCase__       )

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

									# forward pass
									with torch.no_grad():
														__UpperCamelCase :   int									=model(**lowerCamelCase__       )
									__UpperCamelCase :   Optional[int]									=outputs.logits

									# verify the logits
									__UpperCamelCase :   List[Any]									=torch.Size((1, 1000)       )
									self.assertEqual(logits.shape				,    lowerCamelCase__       )

									__UpperCamelCase :   int									=torch.tensor([0.3_277, -0.1_395, 0.0_911]       ).to(lowerCamelCase__       )

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

									__UpperCamelCase :   int									=[model.config.labelaid[i] for i in ['remote control, remote', 'tabby, tabby cat']]
									self.assertEqual(logits[0].topk(2       ).indices.cpu().tolist()				,    lowerCamelCase__       )









from __future__ import annotations






def 				A	(			a_				,a_   )	->		list[int]:
					__UpperCamelCase :   dict[int, int]									={}
					for index, val in enumerate(a_   ):
										__UpperCamelCase :   Union[str, Any]									=target - val
										if compl in chk_map:
															return [chk_map[compl], index]
										__UpperCamelCase :   List[Any]									=index
					return []


if __name__ == "__main__":
							import doctest

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

