




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

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







     def  snake_case_			(							self       )			->							Union[str, Any]:
          snake_case :			Tuple					   = floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

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

          snake_case :			str					   = self.get_config()

          return config, pixel_values, labels, pixel_labels







     def  snake_case_			(							self       )			->							Optional[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=__a       ,initializer_range=self.initializer_range       ,out_indices=self.out_indices       ,)







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







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







@require_torch
class 				_a   (a__,		a__,		unittest.TestCase  ):





     '''simple docstring'''



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

     lowerCAmelCase_     :    List[Any]									=				False
     lowerCAmelCase_     :    str									=				False
     lowerCAmelCase_     :    Optional[int]									=				False







     def  snake_case_			(							self       )			->							int:
          snake_case :			Optional[Any]					   = DataaVecVisionModelTester(self       )
          snake_case :			Optional[Any]					   = ConfigTester(
              self       ,config_class=__a       ,has_text_modality=__a       ,hidden_size=37       )







     def  snake_case_			(							self       )			->							Tuple:
          self.config_tester.run_common_tests()







     def  snake_case_			(							self       )			->							str:
          # 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       )			->							int:
          pass







     def  snake_case_			(							self       )			->							Optional[int]:
          snake_case   ,		snake_case :			Dict					   = self.model_tester.prepare_config_and_inputs_for_common()

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







     def  snake_case_			(							self       )			->							Dict:
          snake_case   ,		snake_case :			List[Any]					   = self.model_tester.prepare_config_and_inputs_for_common()

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

               snake_case :			Dict					   = ["""pixel_values"""]
               self.assertListEqual(arg_names[:1]       ,__a       )







     def  snake_case_			(							self       )			->							Tuple:
          snake_case :			Optional[int]					   = self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*__a       )







     def  snake_case_			(							self       )			->							Optional[Any]:
          snake_case :			str					   = self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_segmentation(*__a       )







     def  snake_case_			(							self       )			->							int:
          if not self.model_tester.is_training:
               return

          snake_case   ,		snake_case :			str					   = self.model_tester.prepare_config_and_inputs_for_common()
          snake_case :			Optional[int]					   = True

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

               snake_case :			Union[str, Any]					   = model_class(__a       )
               model.to(__a       )
               model.train()
               snake_case :			Tuple					   = self._prepare_for_class(__a       ,__a       ,return_labels=__a       )
               snake_case :			Optional[Any]					   = model(**__a       ).loss
               loss.backward()







     def  snake_case_			(							self       )			->							Dict:
          snake_case   ,		snake_case :			Optional[int]					   = self.model_tester.prepare_config_and_inputs_for_common()
          if not self.model_tester.is_training:
               return

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







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

          snake_case :			List[str]					   = _config_zero_init(__a       )
          for model_class in self.all_model_classes:
               snake_case :			Optional[int]					   = 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  snake_case_			(							self       ,__a       ,__a       ,__a       ,__a=2E-4       ,__a="outputs"       ,__a=None       )			->							List[str]:
          # 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  snake_case_			(							self       )			->							Dict:
          snake_case :			Tuple					   = self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*__a       )







     @slow
     def  snake_case_			(							self       )			->							List[str]:
          for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               snake_case :			Dict					   = DataaVecVisionModel.from_pretrained(__a       )
               self.assertIsNotNone(__a       )



def 					lowerCamelCase__							(			):
     snake_case :			List[Any]					   = Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""							)
     return image







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





     '''simple docstring'''



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







     @slow
     def  snake_case_			(							self       )			->							Dict:
          snake_case :			Optional[int]					   = DataaVecVisionForImageClassification.from_pretrained("""facebook/data2vec-vision-base-ft1k"""       ).to(
              __a       )

          snake_case :			Tuple					   = self.default_image_processor
          snake_case :			Tuple					   = prepare_img()
          snake_case :			Any					   = image_processor(images=__a       ,return_tensors="""pt"""       ).to(__a       )

          # forward pass
          with torch.no_grad():
               snake_case :			Optional[Any]					   = model(**__a       )
          snake_case :			Dict					   = outputs.logits

          # verify the logits
          snake_case :			Any					   = torch.Size((1, 1_000)       )
          self.assertEqual(logits.shape       ,__a       )

          snake_case :			List[str]					   = torch.tensor([0.3_277, -0.1_395, 0.0_911]       ).to(__a       )

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

          snake_case :			List[str]					   = [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'''







def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 9 / 5) + 32    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(float(__lowercase							) + 273.15    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 9 / 5) + 491.67    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) - 32) * 5 / 9    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(((float(__lowercase							) - 32) * 5 / 9) + 273.15    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(float(__lowercase							) + 459.67    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(float(__lowercase							) - 273.15    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(((float(__lowercase							) - 273.15) * 9 / 5) + 32    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 9 / 5)    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) - 491.67) * 5 / 9    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round(float(__lowercase							) - 459.67    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 5 / 9)    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 1.25 + 273.15)    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 2.25 + 32)    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 1.25)    ,      __lowercase							)



def 					lowerCamelCase__							(			__lowercase    ,      __lowercase = 2							):
     return round((float(__lowercase							) * 2.25 + 32 + 459.67)    ,      __lowercase							)


if __name__ == "__main__":
      import doctest

      doctest.testmod()



