






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		,	lowercase		,	lowercase=100		,	lowercase=13		,	lowercase=30		,	lowercase=2		,	lowercase=3		,	lowercase=True		,	lowercase=True		,	lowercase=32		,	lowercase=4		,	lowercase=4		,	lowercase=37		,	lowercase="gelu"		,	lowercase=0.1		,	lowercase=0.1		,	lowercase=10		,	lowercase=0.02		,	lowercase=3		,	lowercase=None		,	lowercase=[0, 1, 2, 3]		,	)			->						List[str]:
													_a  :    List[Any]			=						parent
													_a  :    Union[str, Any]			=						100
													_a  :    str			=						batch_size
													_a  :    int			=						image_size
													_a  :    Optional[Any]			=						patch_size
													_a  :    str			=						num_channels
													_a  :    Tuple			=						is_training
													_a  :    Union[str, Any]			=						use_labels
													_a  :    List[Any]			=						hidden_size
													_a  :    Any			=						num_hidden_layers
													_a  :    Optional[int]			=						num_attention_heads
													_a  :    str			=						intermediate_size
													_a  :    Dict			=						hidden_act
													_a  :    Any			=						hidden_dropout_prob
													_a  :    str			=						attention_probs_dropout_prob
													_a  :    Tuple			=						type_sequence_label_size
													_a  :    str			=						initializer_range
													_a  :    Tuple			=						scope
													_a  :    Any			=						out_indices
													_a  :    Dict			=						num_labels

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




						def      snake_case__(    self       )			->						List[str]:
													_a  :    List[Any]			=						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

													_a  :    str			=						None
													_a  :    Any			=						None
													if self.use_labels:
																				_a  :    str			=						ids_tensor([self.batch_size]		,	self.type_sequence_label_size       )
																				_a  :    Optional[Any]			=						ids_tensor([self.batch_size, self.image_size, self.image_size]		,	self.num_labels       )

													_a  :    List[str]			=						self.get_config()

													return config, pixel_values, labels, pixel_labels




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




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

@require_torch
class      UpperCamelCase_							(				UpperCamelCase ,       UpperCamelCase ,       unittest.TestCase       ):
						lowercase									=  (
						    (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
						    if is_torch_available()
						    else ()
						)
						lowercase									=  (
						    {
						        '''feature-extraction''': DataaVecVisionModel,
						        '''image-classification''': DataaVecVisionForImageClassification,
						        '''image-segmentation''': DataaVecVisionForSemanticSegmentation,
						    }
						    if is_torch_available()
						    else {}
						)

						lowercase									=  False
						lowercase									=  False
						lowercase									=  False




						def      snake_case__(    self       )			->						Optional[Any]:
													_a  :    Optional[Any]			=						DataaVecVisionModelTester(self       )
													_a  :    Optional[int]			=						ConfigTester(
													    self		,	config_class=lowercase		,	has_text_modality=lowercase		,	hidden_size=37       )




						def      snake_case__(    self       )			->						Any:
													self.config_tester.run_common_tests()




						def      snake_case__(    self       )			->						Union[str, Any]:
													# 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      snake_case__(    self       )			->						Dict:
													pass




						def      snake_case__(    self       )			->						List[str]:
													_a		,					_a  :    Optional[Any]			=						self.model_tester.prepare_config_and_inputs_for_common()

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




						def      snake_case__(    self       )			->						int:
													_a		,					_a  :    int			=						self.model_tester.prepare_config_and_inputs_for_common()

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

																				_a  :    Any			=						['''pixel_values''']
																				self.assertListEqual(arg_names[:1]		,	lowercase       )




						def      snake_case__(    self       )			->						Union[str, Any]:
													_a  :    Dict			=						self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_model(*lowercase       )




						def      snake_case__(    self       )			->						List[Any]:
													_a  :    Tuple			=						self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_segmentation(*lowercase       )




						def      snake_case__(    self       )			->						Tuple:
													if not self.model_tester.is_training:
																				return

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

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

																				_a  :    Optional[Any]			=						model_class(lowercase       )
																				model.to(lowercase       )
																				model.train()
																				_a  :    str			=						self._prepare_for_class(lowercase		,	lowercase		,	return_labels=lowercase       )
																				_a  :    List[Any]			=						model(**lowercase       ).loss
																				loss.backward()




						def      snake_case__(    self       )			->						Tuple:
													_a		,					_a  :    str			=						self.model_tester.prepare_config_and_inputs_for_common()
													if not self.model_tester.is_training:
																				return

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




						def      snake_case__(    self       )			->						Any:
													_a		,					_a  :    Tuple			=						self.model_tester.prepare_config_and_inputs_for_common()

													_a  :    Optional[Any]			=						_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      snake_case__(    self		,	lowercase		,	lowercase		,	lowercase		,	lowercase=2e-4		,	lowercase="outputs"		,	lowercase=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(lowercase		,	lowercase		,	lowercase		,	lowercase		,	lowercase		,	lowercase       )




						def      snake_case__(    self       )			->						Union[str, Any]:
													_a  :    Optional[Any]			=						self.model_tester.prepare_config_and_inputs()
													self.model_tester.create_and_check_for_image_classification(*lowercase       )







						@slow
						def      snake_case__(    self       )			->						Optional[Any]:
													for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																				_a  :    int			=						DataaVecVisionModel.from_pretrained(lowercase       )
																				self.assertIsNotNone(lowercase       )






def    UpperCamelCase__  (   )     ->		List[Any]:







							"""simple docstring"""





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







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




						@cached_property
						def      snake_case__(    self       )			->						Optional[int]:
													return (
													    BeitImageProcessor.from_pretrained('''facebook/data2vec-vision-base-ft1k'''       ) if is_vision_available() else None
													)







						@slow
						def      snake_case__(    self       )			->						Dict:
													_a  :    Optional[Any]			=						DataaVecVisionForImageClassification.from_pretrained('''facebook/data2vec-vision-base-ft1k'''       ).to(
													    lowercase       )

													_a  :    Union[str, Any]			=						self.default_image_processor
													_a  :    Union[str, Any]			=						prepare_img()
													_a  :    List[Any]			=						image_processor(images=lowercase		,	return_tensors='''pt'''       ).to(lowercase       )

													# forward pass
													with torch.no_grad():
																				_a  :    Optional[Any]			=						model(**lowercase       )
													_a  :    List[Any]			=						outputs.logits

													# verify the logits
													_a  :    List[Any]			=						torch.Size((1, 1_000)       )
													self.assertEqual(logits.shape		,	lowercase       )

													_a  :    Any			=						torch.tensor([0.3277, -0.1395, 0.0911]       ).to(lowercase       )

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

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







__lowerCamelCase						= {0: [1, 2], 1: [0, 3], 2: [0], 3: [1], 4: [5, 6], 5: [4, 6], 6: [4, 5]}

__lowerCamelCase						= {0: [1, 2, 3], 1: [0, 3], 2: [0], 3: [0, 1], 4: [], 5: []}






def    UpperCamelCase__  (   UpperCAmelCase    ,	UpperCAmelCase    ,	UpperCAmelCase     )     ->		list:







							"""simple docstring"""





							_a  :    List[Any]			=						True
							_a  :    Optional[Any]			=						[]

							for neighbour in graph[vert]:
														if not visited[neighbour]:
																					connected_verts += dfs(UpperCAmelCase    ,	UpperCAmelCase    ,	UpperCAmelCase     )

							return [vert, *connected_verts]






def    UpperCamelCase__  (   UpperCAmelCase     )     ->		list:







							"""simple docstring"""





							_a  :    Optional[int]			=						len(UpperCAmelCase     )
							_a  :    Optional[Any]			=						graph_size * [False]
							_a  :    Optional[int]			=						[]

							for i in range(UpperCAmelCase     ):
														if not visited[i]:
																					_a  :    List[str]			=						dfs(UpperCAmelCase    ,	UpperCAmelCase    ,	UpperCAmelCase     )
																					components_list.append(UpperCAmelCase     )

							return components_list


if __name__ == "__main__":
						import doctest

						doctest.testmod()