


"""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     A:

		"""simple docstring"""





		def __init__(   self				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__=1_00				,							SCREAMING_SNAKE_CASE__=13				,							SCREAMING_SNAKE_CASE__=30				,							SCREAMING_SNAKE_CASE__=2				,							SCREAMING_SNAKE_CASE__=3				,							SCREAMING_SNAKE_CASE__=True				,							SCREAMING_SNAKE_CASE__=True				,							SCREAMING_SNAKE_CASE__=32				,							SCREAMING_SNAKE_CASE__=4				,							SCREAMING_SNAKE_CASE__=4				,							SCREAMING_SNAKE_CASE__=37				,							SCREAMING_SNAKE_CASE__="gelu"				,							SCREAMING_SNAKE_CASE__=0.1				,							SCREAMING_SNAKE_CASE__=0.1				,							SCREAMING_SNAKE_CASE__=10				,							SCREAMING_SNAKE_CASE__=0.0_2				,							SCREAMING_SNAKE_CASE__=3				,							SCREAMING_SNAKE_CASE__=None				,							SCREAMING_SNAKE_CASE__=[0, 1, 2, 3]				,							)			->  int:

					"""simple docstring"""



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

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

					"""simple docstring"""



					_UpperCamelCase				:Tuple				    =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

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

					_UpperCamelCase				:Optional[Any]				    =  self.get_config()

					return config, pixel_values, labels, pixel_labels
		def      _UpperCamelCase(   self      )			->  Union[str, Any]:

					"""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=SCREAMING_SNAKE_CASE__				,							initializer_range=self.initializer_range				,							out_indices=self.out_indices				,							)
		def      _UpperCamelCase(   self				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__      )			->  Dict:

					"""simple docstring"""



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

					"""simple docstring"""



					_UpperCamelCase				:Union[str, Any]				    =  self.type_sequence_label_size
					_UpperCamelCase				:int				    =  DataaVecVisionForImageClassification(SCREAMING_SNAKE_CASE__      )
					model.to(SCREAMING_SNAKE_CASE__      )
					model.eval()
					_UpperCamelCase				:Optional[int]				    =  model(SCREAMING_SNAKE_CASE__				,							labels=SCREAMING_SNAKE_CASE__      )
					self.parent.assertEqual(result.logits.shape				,							(self.batch_size, self.type_sequence_label_size)      )
		def      _UpperCamelCase(   self				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__      )			->  List[str]:

					"""simple docstring"""



					_UpperCamelCase				:Dict				    =  self.num_labels
					_UpperCamelCase				:Any				    =  DataaVecVisionForSemanticSegmentation(SCREAMING_SNAKE_CASE__      )
					model.to(SCREAMING_SNAKE_CASE__      )
					model.eval()
					_UpperCamelCase				:Optional[Any]				    =  model(SCREAMING_SNAKE_CASE__      )
					self.parent.assertEqual(
					    result.logits.shape				,							(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)      )
					_UpperCamelCase				:int				    =  model(SCREAMING_SNAKE_CASE__				,							labels=SCREAMING_SNAKE_CASE__      )
					self.parent.assertEqual(
					    result.logits.shape				,							(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)      )





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

					"""simple docstring"""



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






@require_torch
class     A(     lowerCamelCase__							,       lowerCamelCase__							,       unittest.TestCase		):

		"""simple docstring"""





		A         =       (
		    (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
		    if is_torch_available()
		    else ()
		)
		A         =       (
		    {
		        "feature-extraction": DataaVecVisionModel,
		        "image-classification": DataaVecVisionForImageClassification,
		        "image-segmentation": DataaVecVisionForSemanticSegmentation,
		    }
		    if is_torch_available()
		    else {}
		)

		A         =       False
		A         =       False
		A         =       False
		def      _UpperCamelCase(   self      )			->  Any:

					"""simple docstring"""



					_UpperCamelCase				:Optional[Any]				    =  DataaVecVisionModelTester(self      )
					_UpperCamelCase				:Any				    =  ConfigTester(
					    self				,							config_class=SCREAMING_SNAKE_CASE__				,							has_text_modality=SCREAMING_SNAKE_CASE__				,							hidden_size=37      )
		def      _UpperCamelCase(   self      )			->  Tuple:

					"""simple docstring"""



					self.config_tester.run_common_tests()
		def      _UpperCamelCase(   self      )			->  Dict:

					"""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      _UpperCamelCase(   self      )			->  Optional[int]:

					"""simple docstring"""



					pass
		def      _UpperCamelCase(   self      )			->  List[str]:

					"""simple docstring"""



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

					for model_class in self.all_model_classes:
								_UpperCamelCase				:Optional[Any]				    =  model_class(SCREAMING_SNAKE_CASE__      )
								self.assertIsInstance(model.get_input_embeddings()				,							(nn.Module)      )
								_UpperCamelCase				:Any				    =  model.get_output_embeddings()
								self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE__				,							nn.Linear      )      )
		def      _UpperCamelCase(   self      )			->  Union[str, Any]:

					"""simple docstring"""



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

					for model_class in self.all_model_classes:
								_UpperCamelCase				:Optional[Any]				    =  model_class(SCREAMING_SNAKE_CASE__      )
								_UpperCamelCase				:Union[str, Any]				    =  inspect.signature(model.forward      )
								# signature.parameters is an OrderedDict => so arg_names order is deterministic
								_UpperCamelCase				:Tuple				    =  [*signature.parameters.keys()]

								_UpperCamelCase				:Union[str, Any]				    =  ['''pixel_values''']
								self.assertListEqual(arg_names[:1]				,							SCREAMING_SNAKE_CASE__      )
		def      _UpperCamelCase(   self      )			->  Any:

					"""simple docstring"""



					_UpperCamelCase				:Optional[int]				    =  self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__      )
		def      _UpperCamelCase(   self      )			->  Dict:

					"""simple docstring"""



					_UpperCamelCase				:Any				    =  self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_segmentation(*SCREAMING_SNAKE_CASE__      )
		def      _UpperCamelCase(   self      )			->  Optional[Any]:

					"""simple docstring"""



					if not self.model_tester.is_training:
								return

					_UpperCamelCase    ,			_UpperCamelCase				:Optional[Any]				    =  self.model_tester.prepare_config_and_inputs_for_common()
					_UpperCamelCase				:int				    =  True

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

								_UpperCamelCase				:str				    =  model_class(SCREAMING_SNAKE_CASE__      )
								model.to(SCREAMING_SNAKE_CASE__      )
								model.train()
								_UpperCamelCase				:Optional[Any]				    =  self._prepare_for_class(SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							return_labels=SCREAMING_SNAKE_CASE__      )
								_UpperCamelCase				:str				    =  model(**SCREAMING_SNAKE_CASE__      ).loss
								loss.backward()
		def      _UpperCamelCase(   self      )			->  Union[str, Any]:

					"""simple docstring"""



					_UpperCamelCase    ,			_UpperCamelCase				:List[str]				    =  self.model_tester.prepare_config_and_inputs_for_common()
					if not self.model_tester.is_training:
								return

					_UpperCamelCase				:Union[str, Any]				    =  False
					_UpperCamelCase				:Union[str, Any]				    =  True

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

					"""simple docstring"""



					_UpperCamelCase    ,			_UpperCamelCase				:Any				    =  self.model_tester.prepare_config_and_inputs_for_common()

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

					"""simple docstring"""



					super().check_pt_tf_outputs(SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__				,							SCREAMING_SNAKE_CASE__      )
		def      _UpperCamelCase(   self      )			->  List[str]:

					"""simple docstring"""



					_UpperCamelCase				:int				    =  self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__      )





		@slow
		def      _UpperCamelCase(   self      )			->  str:

					"""simple docstring"""



					for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
								_UpperCamelCase				:List[Any]				    =  DataaVecVisionModel.from_pretrained(SCREAMING_SNAKE_CASE__      )
								self.assertIsNotNone(SCREAMING_SNAKE_CASE__      )





def 							A_					(   )				->     Optional[Any]:
			_UpperCamelCase				:Tuple				    =  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''		)
			return image






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

		"""simple docstring"""





		@cached_property
		def      _UpperCamelCase(   self      )			->  str:

					"""simple docstring"""



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





		@slow
		def      _UpperCamelCase(   self      )			->  Tuple:

					"""simple docstring"""



					_UpperCamelCase				:Optional[int]				    =  DataaVecVisionForImageClassification.from_pretrained('''facebook/data2vec-vision-base-ft1k'''      ).to(
					    SCREAMING_SNAKE_CASE__      )

					_UpperCamelCase				:int				    =  self.default_image_processor
					_UpperCamelCase				:Optional[Any]				    =  prepare_img()
					_UpperCamelCase				:Union[str, Any]				    =  image_processor(images=SCREAMING_SNAKE_CASE__				,							return_tensors='''pt'''      ).to(SCREAMING_SNAKE_CASE__      )

					# forward pass
					with torch.no_grad():
								_UpperCamelCase				:Union[str, Any]				    =  model(**SCREAMING_SNAKE_CASE__      )
					_UpperCamelCase				:str				    =  outputs.logits

					# verify the logits
					_UpperCamelCase				:Union[str, Any]				    =  torch.Size((1, 10_00)      )
					self.assertEqual(logits.shape				,							SCREAMING_SNAKE_CASE__      )

					_UpperCamelCase				:int				    =  torch.tensor([0.3_2_7_7, -0.1_3_9_5, 0.0_9_1_1]      ).to(SCREAMING_SNAKE_CASE__      )

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

					_UpperCamelCase				: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()				,							SCREAMING_SNAKE_CASE__      )





"""simple docstring"""






from dataclasses import dataclass
from typing import List, Optional, Union

import numpy as np
import PIL

from ...utils import BaseOutput, is_invisible_watermark_available, is_torch_available, is_transformers_available






@dataclass
class     A(     lowerCamelCase__		):

		"""simple docstring"""





		A         =       42


if is_transformers_available() and is_torch_available() and is_invisible_watermark_available():
					from .pipeline_stable_diffusion_xl import StableDiffusionXLPipeline
					from .pipeline_stable_diffusion_xl_imgaimg import StableDiffusionXLImgaImgPipeline

