


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



		'''simple docstring'''







		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:
			__magic_name__ :					List[Any]  			=  parent
			__magic_name__ :					List[str]  			=  100
			__magic_name__ :					Any  			=  batch_size
			__magic_name__ :					Tuple  			=  image_size
			__magic_name__ :					str  			=  patch_size
			__magic_name__ :					Dict  			=  num_channels
			__magic_name__ :					Optional[int]  			=  is_training
			__magic_name__ :					Any  			=  use_labels
			__magic_name__ :					Union[str, Any]  			=  hidden_size
			__magic_name__ :					List[Any]  			=  num_hidden_layers
			__magic_name__ :					int  			=  num_attention_heads
			__magic_name__ :					Optional[int]  			=  intermediate_size
			__magic_name__ :					Optional[Any]  			=  hidden_act
			__magic_name__ :					List[str]  			=  hidden_dropout_prob
			__magic_name__ :					Tuple  			=  attention_probs_dropout_prob
			__magic_name__ :					List[Any]  			=  type_sequence_label_size
			__magic_name__ :					Optional[int]  			=  initializer_range
			__magic_name__ :					Union[str, Any]  			=  scope
			__magic_name__ :					Union[str, Any]  			=  out_indices
			__magic_name__ :					Union[str, Any]  			=  num_labels

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







		def      __lowerCAmelCase	(      self	:		Any    )						->				Any:
			__magic_name__ :					Optional[Any]  			=  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

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

			__magic_name__ :					Union[str, Any]  			=  self.get_config()

			return config, pixel_values, labels, pixel_labels







		def      __lowerCAmelCase	(      self	:		Tuple    )						->				Optional[int]:
			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      __lowerCAmelCase	(      self	:		Optional[Any]						,  _A	:		List[str]						,  _A	:		List[Any]						,  _A	:		List[str]						,  _A	:		int    )						->				List[str]:
			__magic_name__ :					List[Any]  			=  DataaVecVisionModel(config=_A    )
			model.to(_A    )
			model.eval()
			__magic_name__ :					List[str]  			=  model(_A    )
			# expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
			__magic_name__ :					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      __lowerCAmelCase	(      self	:		Tuple						,  _A	:		List[Any]						,  _A	:		int						,  _A	:		Any						,  _A	:		List[str]    )						->				str:
			__magic_name__ :					Any  			=  self.type_sequence_label_size
			__magic_name__ :					List[Any]  			=  DataaVecVisionForImageClassification(_A    )
			model.to(_A    )
			model.eval()
			__magic_name__ :					Tuple  			=  model(_A						,  labels=_A    )
			self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.type_sequence_label_size)    )







		def      __lowerCAmelCase	(      self	:		List[str]						,  _A	:		Optional[Any]						,  _A	:		Union[str, Any]						,  _A	:		List[Any]						,  _A	:		Optional[Any]    )						->				int:
			__magic_name__ :					Dict  			=  self.num_labels
			__magic_name__ :					int  			=  DataaVecVisionForSemanticSegmentation(_A    )
			model.to(_A    )
			model.eval()
			__magic_name__ :					str  			=  model(_A    )
			self.parent.assertEqual(
			    result.logits.shape						,  (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)    )
			__magic_name__ :					str  			=  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      __lowerCAmelCase	(      self	:		List[Any]    )						->				str:
			__magic_name__ :					Tuple  			=  self.prepare_config_and_inputs()
			__magic_name__			,       __magic_name__			,       __magic_name__			,       __magic_name__ :					Any  			=  config_and_inputs
			__magic_name__ :					Optional[Any]  			=  {'pixel_values': pixel_values}
			return config, inputs_dict







@require_torch
class _lowerCamelCase (		lowercase__	,  lowercase__	,  unittest.TestCase							):



		'''simple docstring'''







		A_			:    Dict   					=       (
		    (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
		    if is_torch_available()
		    else ()
		)
		A_			:    List[str]   					=       (
		    {
		        """feature-extraction""": DataaVecVisionModel,
		        """image-classification""": DataaVecVisionForImageClassification,
		        """image-segmentation""": DataaVecVisionForSemanticSegmentation,
		    }
		    if is_torch_available()
		    else {}
		)

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







		def      __lowerCAmelCase	(      self	:		int    )						->				List[str]:
			__magic_name__ :					Any  			=  DataaVecVisionModelTester(self    )
			__magic_name__ :					List[Any]  			=  ConfigTester(
			    self						,  config_class=_A						,  has_text_modality=_A						,  hidden_size=37    )







		def      __lowerCAmelCase	(      self	:		Any    )						->				List[str]:
			self.config_tester.run_common_tests()







		def      __lowerCAmelCase	(      self	:		Dict    )						->				int:
			# Data2VecVision does not use inputs_embeds
			pass







		@require_torch_multi_gpu
		@unittest.skip(
		    reason='Data2VecVision has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'    )
		def      __lowerCAmelCase	(      self	:		int    )						->				Union[str, Any]:
			pass







		def      __lowerCAmelCase	(      self	:		List[Any]    )						->				str:
			__magic_name__			,       __magic_name__ :					Any  			=  self.model_tester.prepare_config_and_inputs_for_common()

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







		def      __lowerCAmelCase	(      self	:		Union[str, Any]    )						->				List[str]:
			__magic_name__			,       __magic_name__ :					Optional[Any]  			=  self.model_tester.prepare_config_and_inputs_for_common()

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

				__magic_name__ :					Union[str, Any]  			=  ['pixel_values']
				self.assertListEqual(arg_names[:1]						,  _A    )







		def      __lowerCAmelCase	(      self	:		List[str]    )						->				str:
			__magic_name__ :					Tuple  			=  self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_model(*_A    )







		def      __lowerCAmelCase	(      self	:		Optional[int]    )						->				Tuple:
			__magic_name__ :					Dict  			=  self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_image_segmentation(*_A    )







		def      __lowerCAmelCase	(      self	:		List[str]    )						->				str:
			if not self.model_tester.is_training:
				return

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

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

				__magic_name__ :					List[Any]  			=  model_class(_A    )
				model.to(_A    )
				model.train()
				__magic_name__ :					List[str]  			=  self._prepare_for_class(_A						,  _A						,  return_labels=_A    )
				__magic_name__ :					Dict  			=  model(**_A    ).loss
				loss.backward()







		def      __lowerCAmelCase	(      self	:		Dict    )						->				List[Any]:
			__magic_name__			,       __magic_name__ :					List[str]  			=  self.model_tester.prepare_config_and_inputs_for_common()
			if not self.model_tester.is_training:
				return

			__magic_name__ :					Optional[int]  			=  False
			__magic_name__ :					List[Any]  			=  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":
					__magic_name__			,       __magic_name__			,       __magic_name__			,       __magic_name__ :					Any  			=  inputs_dict['pixel_values'].shape
					__magic_name__ :					str  			=  torch.zeros(
					    [self.model_tester.batch_size, height, width]						,  device=_A    ).long()
				__magic_name__ :					List[str]  			=  model_class(_A    )
				model.gradient_checkpointing_enable()
				model.to(_A    )
				model.train()
				__magic_name__ :					Tuple  			=  self._prepare_for_class(_A						,  _A						,  return_labels=_A    )
				__magic_name__ :					List[str]  			=  model(**_A    ).loss
				loss.backward()







		def      __lowerCAmelCase	(      self	:		Union[str, Any]    )						->				str:
			__magic_name__			,       __magic_name__ :					List[Any]  			=  self.model_tester.prepare_config_and_inputs_for_common()

			__magic_name__ :					Any  			=  _config_zero_init(_A    )
			for model_class in self.all_model_classes:
				__magic_name__ :					str  			=  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      __lowerCAmelCase	(      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]:
			# We override with a slightly higher tol value, as semseg models tend to diverge a bit more
			super().check_pt_tf_outputs(_A						,  _A						,  _A						,  _A						,  _A						,  _A    )







		def      __lowerCAmelCase	(      self	:		Tuple    )						->				Dict:
			__magic_name__ :					List[str]  			=  self.model_tester.prepare_config_and_inputs()
			self.model_tester.create_and_check_for_image_classification(*_A    )







		@slow
		def      __lowerCAmelCase	(      self	:		List[Any]    )						->				Optional[int]:
			for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
				__magic_name__ :					List[Any]  			=  DataaVecVisionModel.from_pretrained(_A    )
				self.assertIsNotNone(_A    )







def lowerCamelCase    (    ):





	"""simple docstring"""







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





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



		'''simple docstring'''







		@cached_property
		def      __lowerCAmelCase	(      self	:		List[Any]    )						->				str:
			return (
			    BeitImageProcessor.from_pretrained('facebook/data2vec-vision-base-ft1k'    ) if is_vision_available() else None
			)







		@slow
		def      __lowerCAmelCase	(      self	:		str    )						->				Union[str, Any]:
			__magic_name__ :					Any  			=  DataaVecVisionForImageClassification.from_pretrained('facebook/data2vec-vision-base-ft1k'    ).to(
			    _A    )

			__magic_name__ :					Dict  			=  self.default_image_processor
			__magic_name__ :					Optional[int]  			=  prepare_img()
			__magic_name__ :					Optional[Any]  			=  image_processor(images=_A						,  return_tensors='pt'    ).to(_A    )

			# forward pass
			with torch.no_grad():
				__magic_name__ :					int  			=  model(**_A    )
			__magic_name__ :					List[Any]  			=  outputs.logits

			# verify the logits
			__magic_name__ :					int  			=  torch.Size((1, 1000)    )
			self.assertEqual(logits.shape						,  _A    )

			__magic_name__ :					Union[str, Any]  			=  torch.tensor([0.3277, -0.1395, 0.0911]    ).to(_A    )

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

			__magic_name__ :					Any  			=  [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'''

import math





def lowerCamelCase    (    lowerCAmelCase       :			int	):





	"""simple docstring"""







	if not isinstance(lowerCAmelCase	,	lowerCAmelCase	):
		__magic_name__ :					str  			=  f'Input value of [number={number}] must be an integer'
		raise TypeError(lowerCAmelCase	)
	if number < 1:
		__magic_name__ :					Tuple  			=  f'Input value of [number={number}] must be a positive integer'
		raise ValueError(lowerCAmelCase	)
	__magic_name__ :					Tuple  			=  [number]
	while number != 1:
		if number % 2 == 0:
			__magic_name__ :					Optional[int]  			=  math.floor(math.sqrt(lowerCAmelCase	)	)
		else:
			__magic_name__ :					Union[str, Any]  			=  math.floor(
			    math.sqrt(lowerCAmelCase	) * math.sqrt(lowerCAmelCase	) * math.sqrt(lowerCAmelCase	)	)
		sequence.append(lowerCAmelCase	)
	return sequence


if __name__ == "__main__":
							import doctest

							doctest.testmod()