


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

        # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
        __snake_case    			=	(image_size // patch_size) ** 2
        __snake_case    			=	num_patches + 1
   def a     (	self					:			int			)   ->       List[Any]:
        __snake_case    			=	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]			)

        __snake_case    			=	None
        __snake_case    			=	None
        if self.use_labels:
             __snake_case    			=	ids_tensor([self.batch_size]					,      self.type_sequence_label_size			)
             __snake_case    			=	ids_tensor([self.batch_size, self.image_size, self.image_size]					,      self.num_labels			)

        __snake_case    			=	self.get_config()

        return config, pixel_values, labels, pixel_labels
   def a     (	self					:			Dict			)   ->       List[Any]:
        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 a     (	self					:			Union[str, Any]					,      SCREAMING_SNAKE_CASE_					:			Any					,      SCREAMING_SNAKE_CASE_					:			Union[str, Any]					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]					,      SCREAMING_SNAKE_CASE_					:			Dict			)   ->       Union[str, Any]:
        __snake_case    			=	DataaVecVisionModel(config=SCREAMING_SNAKE_CASE_			)
        model.to(SCREAMING_SNAKE_CASE_			)
        model.eval()
        __snake_case    			=	model(SCREAMING_SNAKE_CASE_			)
        # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
        __snake_case    			=	(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					:			str					,      SCREAMING_SNAKE_CASE_					:			int					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]					,      SCREAMING_SNAKE_CASE_					:			Optional[int]					,      SCREAMING_SNAKE_CASE_					:			Tuple			)   ->       Dict:
        __snake_case    			=	self.type_sequence_label_size
        __snake_case    			=	DataaVecVisionForImageClassification(SCREAMING_SNAKE_CASE_			)
        model.to(SCREAMING_SNAKE_CASE_			)
        model.eval()
        __snake_case    			=	model(SCREAMING_SNAKE_CASE_					,      labels=SCREAMING_SNAKE_CASE_			)
        self.parent.assertEqual(result.logits.shape					,      (self.batch_size, self.type_sequence_label_size)			)
   def a     (	self					:			Any					,      SCREAMING_SNAKE_CASE_					:			Union[str, Any]					,      SCREAMING_SNAKE_CASE_					:			List[str]					,      SCREAMING_SNAKE_CASE_					:			List[Any]					,      SCREAMING_SNAKE_CASE_					:			Tuple			)   ->       List[str]:
        __snake_case    			=	self.num_labels
        __snake_case    			=	DataaVecVisionForSemanticSegmentation(SCREAMING_SNAKE_CASE_			)
        model.to(SCREAMING_SNAKE_CASE_			)
        model.eval()
        __snake_case    			=	model(SCREAMING_SNAKE_CASE_			)
        self.parent.assertEqual(
            result.logits.shape					,      (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)			)
        __snake_case    			=	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 a     (	self					:			Union[str, Any]			)   ->       Tuple:
        __snake_case    			=	self.prepare_config_and_inputs()
        __snake_case			,					__snake_case			,					__snake_case			,					__snake_case    			=	config_and_inputs
        __snake_case    			=	{'pixel_values': pixel_values}
        return config, inputs_dict




@require_torch
class  _lowercase   (  __lowercase	,				__lowercase	,				unittest.TestCase       ):
   _SCREAMING_SNAKE_CASE     :     Tuple									=  (
       (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
       if is_torch_available()
       else ()
   )
   _SCREAMING_SNAKE_CASE     :     Union[str, Any]									=  (
       {
           "feature-extraction": DataaVecVisionModel,
           "image-classification": DataaVecVisionForImageClassification,
           "image-segmentation": DataaVecVisionForSemanticSegmentation,
       }
       if is_torch_available()
       else {}
   )

   _SCREAMING_SNAKE_CASE     :     List[str]									=  False
   _SCREAMING_SNAKE_CASE     :     Any									=  False
   _SCREAMING_SNAKE_CASE     :     Union[str, Any]									=  False
   def a     (	self					:			int			)   ->       List[Any]:
        __snake_case    			=	DataaVecVisionModelTester(self			)
        __snake_case    			=	ConfigTester(
            self					,      config_class=SCREAMING_SNAKE_CASE_					,      has_text_modality=SCREAMING_SNAKE_CASE_					,      hidden_size=37			)
   def a     (	self					:			str			)   ->       Optional[int]:
        self.config_tester.run_common_tests()
   def a     (	self					:			List[str]			)   ->       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 a     (	self					:			str			)   ->       Optional[Any]:
        pass
   def a     (	self					:			Union[str, Any]			)   ->       str:
        __snake_case			,					__snake_case    			=	self.model_tester.prepare_config_and_inputs_for_common()

        for model_class in self.all_model_classes:
             __snake_case    			=	model_class(SCREAMING_SNAKE_CASE_			)
             self.assertIsInstance(model.get_input_embeddings()					,      (nn.Module)			)
             __snake_case    			=	model.get_output_embeddings()
             self.assertTrue(x is None or isinstance(SCREAMING_SNAKE_CASE_					,      nn.Linear			)			)
   def a     (	self					:			int			)   ->       Union[str, Any]:
        __snake_case			,					__snake_case    			=	self.model_tester.prepare_config_and_inputs_for_common()

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

             __snake_case    			=	['pixel_values']
             self.assertListEqual(arg_names[:1]					,      SCREAMING_SNAKE_CASE_			)
   def a     (	self					:			Optional[int]			)   ->       List[str]:
        __snake_case    			=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE_			)
   def a     (	self					:			Optional[Any]			)   ->       Optional[int]:
        __snake_case    			=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_segmentation(*SCREAMING_SNAKE_CASE_			)
   def a     (	self					:			List[str]			)   ->       Optional[Any]:
        if not self.model_tester.is_training:
             return

        __snake_case			,					__snake_case    			=	self.model_tester.prepare_config_and_inputs_for_common()
        __snake_case    			=	True

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

             __snake_case    			=	model_class(SCREAMING_SNAKE_CASE_			)
             model.to(SCREAMING_SNAKE_CASE_			)
             model.train()
             __snake_case    			=	self._prepare_for_class(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_					,      return_labels=SCREAMING_SNAKE_CASE_			)
             __snake_case    			=	model(**SCREAMING_SNAKE_CASE_			).loss
             loss.backward()
   def a     (	self					:			Dict			)   ->       Union[str, Any]:
        __snake_case			,					__snake_case    			=	self.model_tester.prepare_config_and_inputs_for_common()
        if not self.model_tester.is_training:
             return

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

        __snake_case    			=	_config_zero_init(SCREAMING_SNAKE_CASE_			)
        for model_class in self.all_model_classes:
             __snake_case    			=	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 a     (	self					:			Dict					,      SCREAMING_SNAKE_CASE_					:			str					,      SCREAMING_SNAKE_CASE_					:			Dict					,      SCREAMING_SNAKE_CASE_					:			Any					,      SCREAMING_SNAKE_CASE_					:			List[str]=2e-4					,      SCREAMING_SNAKE_CASE_					:			List[Any]="outputs"					,      SCREAMING_SNAKE_CASE_					:			Optional[Any]=None			)   ->       str:
        # We override with a slightly higher tol value, as semseg models tend to diverge a bit more
        super().check_pt_tf_outputs(SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_					,      SCREAMING_SNAKE_CASE_			)
   def a     (	self					:			int			)   ->       List[str]:
        __snake_case    			=	self.model_tester.prepare_config_and_inputs()
        self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE_			)





   @slow
   def a     (	self					:			List[str]			)   ->       Union[str, Any]:
        for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             __snake_case    			=	DataaVecVisionModel.from_pretrained(SCREAMING_SNAKE_CASE_			)
             self.assertIsNotNone(SCREAMING_SNAKE_CASE_			)





def      _a		() -> List[Any]:






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




@require_torch
@require_vision
class  _lowercase   (  unittest.TestCase       ):
   @cached_property
   def a     (	self					:			Union[str, Any]			)   ->       List[str]:
        return (
            BeitImageProcessor.from_pretrained('facebook/data2vec-vision-base-ft1k'			) if is_vision_available() else None
        )





   @slow
   def a     (	self					:			List[str]			)   ->       Optional[Any]:
        __snake_case    			=	DataaVecVisionForImageClassification.from_pretrained('facebook/data2vec-vision-base-ft1k'			).to(
            SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	self.default_image_processor
        __snake_case    			=	prepare_img()
        __snake_case    			=	image_processor(images=SCREAMING_SNAKE_CASE_					,      return_tensors='pt'			).to(SCREAMING_SNAKE_CASE_			)

        # forward pass
        with torch.no_grad():
             __snake_case    			=	model(**SCREAMING_SNAKE_CASE_			)
        __snake_case    			=	outputs.logits

        # verify the logits
        __snake_case    			=	torch.Size((1, 1000)			)
        self.assertEqual(logits.shape					,      SCREAMING_SNAKE_CASE_			)

        __snake_case    			=	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			)			)

        __snake_case    			=	[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'''




def      _a		(lowercase__ :      int	) -> int:






     """simple docstring"""
     return 1 if input_a == 0 else 0





def      _a		() -> None:






     """simple docstring"""
     assert not_gate(0	) == 1
     assert not_gate(1	) == 0


if __name__ == "__main__":
       print(not_gate(0))
       print(not_gate(1))




