



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







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


						'''simple docstring'''







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

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







		def 					a_  (    self  :   str					)       ->		str:


						'''simple docstring'''







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

						_UpperCAmelCase						:  int     					=	None
						_UpperCAmelCase						:  Optional[int]     					=	None
						if self.use_labels:
										_UpperCAmelCase						:  Union[str, Any]     					=	ids_tensor([self.batch_size]       ,		self.type_sequence_label_size					)
										_UpperCAmelCase						:  Tuple     					=	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 					a_  (    self  :   str					)       ->		Dict:


						'''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=UpperCAmelCase_       ,		initializer_range=self.initializer_range       ,		out_indices=self.out_indices       ,		)







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


						'''simple docstring'''







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


						'''simple docstring'''







						_UpperCAmelCase						:  str     					=	self.type_sequence_label_size
						_UpperCAmelCase						:  Dict     					=	DataaVecVisionForImageClassification(UpperCAmelCase_					)
						model.to(UpperCAmelCase_					)
						model.eval()
						_UpperCAmelCase						:  Union[str, Any]     					=	model(UpperCAmelCase_       ,		labels=UpperCAmelCase_					)
						self.parent.assertEqual(result.logits.shape       ,		(self.batch_size, self.type_sequence_label_size)					)







		def 					a_  (    self  :   Dict       ,		UpperCAmelCase_  :   Union[str, Any]       ,		UpperCAmelCase_  :   Optional[int]       ,		UpperCAmelCase_  :   Tuple       ,		UpperCAmelCase_  :   Any					)       ->		Dict:


						'''simple docstring'''







						_UpperCAmelCase						:  Optional[Any]     					=	self.num_labels
						_UpperCAmelCase						:  str     					=	DataaVecVisionForSemanticSegmentation(UpperCAmelCase_					)
						model.to(UpperCAmelCase_					)
						model.eval()
						_UpperCAmelCase						:  Optional[Any]     					=	model(UpperCAmelCase_					)
						self.parent.assertEqual(
						    result.logits.shape       ,		(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)					)
						_UpperCAmelCase						:  Tuple     					=	model(UpperCAmelCase_       ,		labels=UpperCAmelCase_					)
						self.parent.assertEqual(
						    result.logits.shape       ,		(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)					)







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


						'''simple docstring'''







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





@require_torch
class 							lowerCAmelCase_		(		lowercase_							,		lowercase_							,		unittest.TestCase     ):
		SCREAMING_SNAKE_CASE_       :			Tuple					       =	(
		    (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
		    if is_torch_available()
		    else ()
		)
		SCREAMING_SNAKE_CASE_       :			Optional[Any]					       =	(
		    {
		        """feature-extraction""": DataaVecVisionModel,
		        """image-classification""": DataaVecVisionForImageClassification,
		        """image-segmentation""": DataaVecVisionForSemanticSegmentation,
		    }
		    if is_torch_available()
		    else {}
		)

		SCREAMING_SNAKE_CASE_       :			Tuple					       =	False
		SCREAMING_SNAKE_CASE_       :			Any					       =	False
		SCREAMING_SNAKE_CASE_       :			Union[str, Any]					       =	False







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


						'''simple docstring'''







						_UpperCAmelCase						:  Any     					=	DataaVecVisionModelTester(self					)
						_UpperCAmelCase						:  Tuple     					=	ConfigTester(
						    self       ,		config_class=UpperCAmelCase_       ,		has_text_modality=UpperCAmelCase_       ,		hidden_size=37					)







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


						'''simple docstring'''







						self.config_tester.run_common_tests()







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


						'''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 					a_  (    self  :   Dict					)       ->		Optional[Any]:


						'''simple docstring'''







						pass







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


						'''simple docstring'''







						_UpperCAmelCase					, _UpperCAmelCase						:  int     					=	self.model_tester.prepare_config_and_inputs_for_common()

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







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


						'''simple docstring'''







						_UpperCAmelCase					, _UpperCAmelCase						:  List[Any]     					=	self.model_tester.prepare_config_and_inputs_for_common()

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

										_UpperCAmelCase						:  Any     					=	['''pixel_values''']
										self.assertListEqual(arg_names[:1]       ,		UpperCAmelCase_					)







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


						'''simple docstring'''







						_UpperCAmelCase						:  Dict     					=	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*UpperCAmelCase_					)







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


						'''simple docstring'''







						_UpperCAmelCase						:  Tuple     					=	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_segmentation(*UpperCAmelCase_					)







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


						'''simple docstring'''







						if not self.model_tester.is_training:
										return

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

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

										_UpperCAmelCase						:  Optional[Any]     					=	model_class(UpperCAmelCase_					)
										model.to(UpperCAmelCase_					)
										model.train()
										_UpperCAmelCase						:  List[Any]     					=	self._prepare_for_class(UpperCAmelCase_       ,		UpperCAmelCase_       ,		return_labels=UpperCAmelCase_					)
										_UpperCAmelCase						:  Dict     					=	model(**UpperCAmelCase_					).loss
										loss.backward()







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


						'''simple docstring'''







						_UpperCAmelCase					, _UpperCAmelCase						:  Optional[Any]     					=	self.model_tester.prepare_config_and_inputs_for_common()
						if not self.model_tester.is_training:
										return

						_UpperCAmelCase						:  str     					=	False
						_UpperCAmelCase						:  Tuple     					=	True

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







		def 					a_  (    self  :   int					)       ->		Any:


						'''simple docstring'''







						_UpperCAmelCase					, _UpperCAmelCase						:  Dict     					=	self.model_tester.prepare_config_and_inputs_for_common()

						_UpperCAmelCase						:  List[str]     					=	_config_zero_init(UpperCAmelCase_					)
						for model_class in self.all_model_classes:
										_UpperCAmelCase						:  str     					=	model_class(config=UpperCAmelCase_					)
										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 					a_  (    self  :   Optional[Any]       ,		UpperCAmelCase_  :   List[Any]       ,		UpperCAmelCase_  :   Optional[int]       ,		UpperCAmelCase_  :   Optional[int]       ,		UpperCAmelCase_  :   int=2E-4       ,		UpperCAmelCase_  :   Optional[Any]="outputs"       ,		UpperCAmelCase_  :   Any=None					)       ->		int:


						'''simple docstring'''







						super().check_pt_tf_outputs(UpperCAmelCase_       ,		UpperCAmelCase_       ,		UpperCAmelCase_       ,		UpperCAmelCase_       ,		UpperCAmelCase_       ,		UpperCAmelCase_					)







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


						'''simple docstring'''







						_UpperCAmelCase						:  Dict     					=	self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_					)







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


						'''simple docstring'''







						for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										_UpperCAmelCase						:  Any     					=	DataaVecVisionModel.from_pretrained(UpperCAmelCase_					)
										self.assertIsNotNone(UpperCAmelCase_					)


def 	_A	(   ):
				_UpperCAmelCase						:  int     					=	Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''			)
				return image






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







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


						'''simple docstring'''







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







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


						'''simple docstring'''







						_UpperCAmelCase						:  Dict     					=	DataaVecVisionForImageClassification.from_pretrained('''facebook/data2vec-vision-base-ft1k'''					).to(
						    UpperCAmelCase_					)

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

						# forward pass
						with torch.no_grad():
										_UpperCAmelCase						:  Tuple     					=	model(**UpperCAmelCase_					)
						_UpperCAmelCase						:  Any     					=	outputs.logits

						# verify the logits
						_UpperCAmelCase						:  Tuple     					=	torch.Size((1, 1000)					)
						self.assertEqual(logits.shape       ,		UpperCAmelCase_					)

						_UpperCAmelCase						:  List[Any]     					=	torch.tensor([0.3_277, -0.1_395, 0.0_911]					).to(UpperCAmelCase_					)

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

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





def 	_A	(   _UpperCamelCase			):
				if not isinstance(_UpperCamelCase      ,					_UpperCamelCase			):
								_UpperCAmelCase						:  List[Any]     					=	(
								    '''operation can not be conducted on a object of type '''
								    F'''{type(_UpperCamelCase			).__name__}'''
								)
								raise TypeError(_UpperCamelCase			)
				_UpperCAmelCase						:  List[str]     					=	''''''
				for _ in range(0      ,					32			):
								bit_string += str(number % 2			)
								_UpperCAmelCase						:  Union[str, Any]     					=	number >> 1
				return bit_string


def 	_A	(   _UpperCamelCase			):
				if number < 0:
								raise ValueError('''the value of input must be positive'''			)
				elif isinstance(_UpperCamelCase      ,					_UpperCamelCase			):
								raise TypeError('''Input value must be a \'int\' type'''			)
				elif isinstance(_UpperCamelCase      ,					_UpperCamelCase			):
								raise TypeError('''\'<\' not supported between instances of \'str\' and \'int\''''			)
				_UpperCAmelCase						:  Tuple     					=	0
				# iterator over [1 to 32],since we are dealing with 32 bit integer
				for _ in range(1      ,					33			):
								# left shift the bits by unity
								_UpperCAmelCase						:  List[str]     					=	result << 1
								# get the end bit
								_UpperCAmelCase						:  List[Any]     					=	number % 2
								# right shift the bits by unity
								_UpperCAmelCase						:  Optional[int]     					=	number >> 1
								# add that bit to our ans
								_UpperCAmelCase						:  Any     					=	result | end_bit
				return get_reverse_bit_string(_UpperCamelCase			)


if __name__ == "__main__":
					import doctest

					doctest.testmod()
