
'''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  UpperCamelCase__  :






	def __init__(			self  :Optional[int]	,				_A  :Optional[Any]	,				_A  :Optional[int]=100	,				_A  :int=13	,				_A  :Dict=30	,				_A  :Tuple=2	,				_A  :List[str]=3	,				_A  :List[Any]=True	,				_A  :Dict=True	,				_A  :Union[str, Any]=32	,				_A  :str=4	,				_A  :Any=4	,				_A  :List[str]=37	,				_A  :Union[str, Any]="gelu"	,				_A  :Any=0.1	,				_A  :Tuple=0.1	,				_A  :int=10	,				_A  :Any=0.02	,				_A  :Optional[int]=3	,				_A  :Optional[Any]=None	,				_A  :int=[0, 1, 2, 3]	,				)				->			Dict:







							'''simple docstring'''



							__A       	=			parent
							__A       	=			100
							__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 	lowercase_						(			self  :Any			)				->			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 	lowercase_						(			self  :Tuple			)				->			Optional[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=_A	,				initializer_range=self.initializer_range	,				out_indices=self.out_indices	,				)






	def 	lowercase_						(			self  :Optional[Any]	,				_A  :List[str]	,				_A  :List[Any]	,				_A  :List[str]	,				_A  :int			)				->			List[str]:







							'''simple docstring'''



							__A       	=			DataaVecVisionModel(config=_A			)
							model.to(_A			)
							model.eval()
							__A       	=			model(_A			)
							# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
							__A       	=			(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  :Tuple	,				_A  :List[Any]	,				_A  :int	,				_A  :Any	,				_A  :List[str]			)				->			str:







							'''simple docstring'''



							__A       	=			self.type_sequence_label_size
							__A       	=			DataaVecVisionForImageClassification(_A			)
							model.to(_A			)
							model.eval()
							__A       	=			model(_A	,				labels=_A			)
							self.parent.assertEqual(result.logits.shape	,				(self.batch_size, self.type_sequence_label_size)			)






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







							'''simple docstring'''



							__A       	=			self.num_labels
							__A       	=			DataaVecVisionForSemanticSegmentation(_A			)
							model.to(_A			)
							model.eval()
							__A       	=			model(_A			)
							self.parent.assertEqual(
							    result.logits.shape	,				(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)			)
							__A       	=			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 	lowercase_						(			self  :List[Any]			)				->			str:







							'''simple docstring'''



							__A       	=			self.prepare_config_and_inputs()
							__A       	=			config_and_inputs
							__A       	=			{'pixel_values': pixel_values}
							return config, inputs_dict


@require_torch
class  UpperCamelCase__  (    lowercase__      ,     lowercase__      ,     unittest.TestCase):
	UpperCAmelCase__    :    Dict										=					(
	    (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
	    if is_torch_available()
	    else ()
	)
	UpperCAmelCase__    :    List[str]										=					(
	    {
	        """feature-extraction""": DataaVecVisionModel,
	        """image-classification""": DataaVecVisionForImageClassification,
	        """image-segmentation""": DataaVecVisionForSemanticSegmentation,
	    }
	    if is_torch_available()
	    else {}
	)

	UpperCAmelCase__    :    Dict										=					False
	UpperCAmelCase__    :    Dict										=					False
	UpperCAmelCase__    :    List[Any]										=					False






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







							'''simple docstring'''



							__A       	=			DataaVecVisionModelTester(self			)
							__A       	=			ConfigTester(
							    self	,				config_class=_A	,				has_text_modality=_A	,				hidden_size=37			)






	def 	lowercase_						(			self  :Any			)				->			List[str]:







							'''simple docstring'''



							self.config_tester.run_common_tests()






	def 	lowercase_						(			self  :Dict			)				->			int:







							'''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  :int			)				->			Union[str, Any]:







							'''simple docstring'''



							pass






	def 	lowercase_						(			self  :List[Any]			)				->			str:







							'''simple docstring'''



							__A       	=			self.model_tester.prepare_config_and_inputs_for_common()

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






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







							'''simple docstring'''



							__A       	=			self.model_tester.prepare_config_and_inputs_for_common()

							for model_class in self.all_model_classes:
													__A       	=			model_class(_A			)
													__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]	,				_A			)






	def 	lowercase_						(			self  :List[str]			)				->			str:







							'''simple docstring'''



							__A       	=			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*_A			)






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







							'''simple docstring'''



							__A       	=			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_segmentation(*_A			)






	def 	lowercase_						(			self  :List[str]			)				->			str:







							'''simple docstring'''



							if not self.model_tester.is_training:
													return

							__A       	=			self.model_tester.prepare_config_and_inputs_for_common()
							__A       	=			True

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

													__A       	=			model_class(_A			)
													model.to(_A			)
													model.train()
													__A       	=			self._prepare_for_class(_A	,				_A	,				return_labels=_A			)
													__A       	=			model(**_A			).loss
													loss.backward()






	def 	lowercase_						(			self  :Dict			)				->			List[Any]:







							'''simple docstring'''



							__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:
													if model_class in [*get_values(_A			)] 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       	=			inputs_dict['pixel_values'].shape
																			__A       	=			torch.zeros(
																			    [self.model_tester.batch_size, height, width]	,				device=_A			).long()
													__A       	=			model_class(_A			)
													model.gradient_checkpointing_enable()
													model.to(_A			)
													model.train()
													__A       	=			self._prepare_for_class(_A	,				_A	,				return_labels=_A			)
													__A       	=			model(**_A			).loss
													loss.backward()






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







							'''simple docstring'''



							__A       	=			self.model_tester.prepare_config_and_inputs_for_common()

							__A       	=			_config_zero_init(_A			)
							for model_class in self.all_model_classes:
													__A       	=			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'	,				)






	def 	lowercase_						(			self  :Optional[int]	,				_A  :int	,				_A  :Optional[Any]	,				_A  :Union[str, Any]	,				_A  :Optional[Any]=2E-4	,				_A  :List[Any]="outputs"	,				_A  :int=None			)				->			List[Any]:







							'''simple docstring'''



							super().check_pt_tf_outputs(_A	,				_A	,				_A	,				_A	,				_A	,				_A			)






	def 	lowercase_						(			self  :Tuple			)				->			Dict:







							'''simple docstring'''



							__A       	=			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*_A			)






	@slow
	def 	lowercase_						(			self  :List[Any]			)				->			Optional[int]:







							'''simple docstring'''



							for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
													__A       	=			DataaVecVisionModel.from_pretrained(_A			)
													self.assertIsNotNone(_A			)





def        snake_case							(		)->			str:







						"""simple docstring"""
						__A       	=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
						return image


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






	@cached_property
	def 	lowercase_						(			self  :List[Any]			)				->			str:







							'''simple docstring'''



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






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







							'''simple docstring'''



							__A       	=			DataaVecVisionForImageClassification.from_pretrained('facebook/data2vec-vision-base-ft1k'			).to(
							    _A			)

							__A       	=			self.default_image_processor
							__A       	=			prepare_img()
							__A       	=			image_processor(images=_A	,				return_tensors='pt'			).to(_A			)

							# forward pass
							with torch.no_grad():
													__A       	=			model(**_A			)
							__A       	=			outputs.logits

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

							__A       	=			torch.tensor([0.3_277, -0.1_395, 0.0_911]			).to(_A			)

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

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








'''simple docstring'''





from .hash_table import HashTable
from .number_theory.prime_numbers import is_prime, next_prime


class  UpperCamelCase__  (    SCREAMING_SNAKE_CASE):






 def __init__(			self  :Union[str, Any]	,				*_A  :int	,				**_A  :Optional[Any]			)				->			Union[str, Any]:







       '''simple docstring'''



       super().__init__(*_A	,				**_A			)






 def 	lowercase_						(			self  :Dict	,				_A  :Union[str, Any]	,				_A  :Dict			)				->			Dict:







       '''simple docstring'''



       __A       	=			(
           next_prime(value % self.size_table			)
           if not is_prime(value % self.size_table			)
           else value % self.size_table
       )  # gt = bigger than
       return next_prime_gt - (data % next_prime_gt)






 def 	lowercase_						(			self  :List[Any]	,				_A  :int	,				_A  :Tuple	,				_A  :Union[str, Any]			)				->			List[Any]:







       '''simple docstring'''



       return (increment * self.__hash_function_a(_A	,				_A			)) % self.size_table






 def 	lowercase_						(			self  :List[Any]	,				_A  :List[str]	,				_A  :str=None			)				->			List[Any]:







       '''simple docstring'''



       __A       	=			1
       __A       	=			self.hash_function(_A			)

       while self.values[new_key] is not None and self.values[new_key] != key:
             __A       	=			(
                 self.__hash_double_function(_A	,				_A	,				_A			)
                 if self.balanced_factor() >= self.lim_charge
                 else None
             )
             if new_key is None:
                   break
             else:
                   i += 1

       return new_key






