


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


 def __init__(			self       :  List[Any] ,					__lowerCamelCase       :  Union[str, Any] ,					__lowerCamelCase       :  List[Any]=1_0_0 ,					__lowerCamelCase       :  int=1_3 ,					__lowerCamelCase       :  int=3_0 ,					__lowerCamelCase       :  List[str]=2 ,					__lowerCamelCase       :  Tuple=3 ,					__lowerCamelCase       :  Optional[int]=True ,					__lowerCamelCase       :  List[str]=True ,					__lowerCamelCase       :  Optional[int]=3_2 ,					__lowerCamelCase       :  Tuple=4 ,					__lowerCamelCase       :  List[str]=4 ,					__lowerCamelCase       :  int=3_7 ,					__lowerCamelCase       :  Optional[Any]="gelu" ,					__lowerCamelCase       :  int=0.1 ,					__lowerCamelCase       :  List[Any]=0.1 ,					__lowerCamelCase       :  Optional[int]=1_0 ,					__lowerCamelCase       :  str=0.02 ,					__lowerCamelCase       :  Tuple=3 ,					__lowerCamelCase       :  str=None ,					__lowerCamelCase       :  Optional[Any]=[0, 1, 2, 3] ,					):
    UpperCAmelCase__  :str            =			parent
    UpperCAmelCase__  :Tuple            =			1_0_0
    UpperCAmelCase__  :Optional[int]            =			batch_size
    UpperCAmelCase__  :Optional[int]            =			image_size
    UpperCAmelCase__  :Tuple            =			patch_size
    UpperCAmelCase__  :int            =			num_channels
    UpperCAmelCase__  :List[Any]            =			is_training
    UpperCAmelCase__  :Optional[int]            =			use_labels
    UpperCAmelCase__  :Tuple            =			hidden_size
    UpperCAmelCase__  :List[Any]            =			num_hidden_layers
    UpperCAmelCase__  :Union[str, Any]            =			num_attention_heads
    UpperCAmelCase__  :Optional[Any]            =			intermediate_size
    UpperCAmelCase__  :Tuple            =			hidden_act
    UpperCAmelCase__  :Optional[Any]            =			hidden_dropout_prob
    UpperCAmelCase__  :Dict            =			attention_probs_dropout_prob
    UpperCAmelCase__  :Optional[int]            =			type_sequence_label_size
    UpperCAmelCase__  :Tuple            =			initializer_range
    UpperCAmelCase__  :Dict            =			scope
    UpperCAmelCase__  :Optional[int]            =			out_indices
    UpperCAmelCase__  :List[str]            =			num_labels

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


 def 					__SCREAMING_SNAKE_CASE				(			self       :  int   ):
    UpperCAmelCase__  :str            =			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]   )

    UpperCAmelCase__  :Union[str, Any]            =			None
    UpperCAmelCase__  :Optional[int]            =			None
    if self.use_labels:
       UpperCAmelCase__  :Any            =			ids_tensor([self.batch_size] ,					self.type_sequence_label_size   )
       UpperCAmelCase__  :List[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 					__SCREAMING_SNAKE_CASE				(			self       :  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=__lowerCamelCase ,					initializer_range=self.initializer_range ,					out_indices=self.out_indices ,					)


 def 					__SCREAMING_SNAKE_CASE				(			self       :  List[str] ,					__lowerCamelCase       :  Tuple ,					__lowerCamelCase       :  str ,					__lowerCamelCase       :  Optional[int] ,					__lowerCamelCase       :  str   ):
    UpperCAmelCase__  :Union[str, Any]            =			DataaVecVisionModel(config=__lowerCamelCase   )
    model.to(__lowerCamelCase   )
    model.eval()
    UpperCAmelCase__  :int            =			model(__lowerCamelCase   )
    # 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 					__SCREAMING_SNAKE_CASE				(			self       :  Union[str, Any] ,					__lowerCamelCase       :  str ,					__lowerCamelCase       :  Dict ,					__lowerCamelCase       :  Dict ,					__lowerCamelCase       :  Any   ):
    UpperCAmelCase__  :Tuple            =			self.type_sequence_label_size
    UpperCAmelCase__  :List[Any]            =			DataaVecVisionForImageClassification(__lowerCamelCase   )
    model.to(__lowerCamelCase   )
    model.eval()
    UpperCAmelCase__  :int            =			model(__lowerCamelCase ,					labels=__lowerCamelCase   )
    self.parent.assertEqual(result.logits.shape ,					(self.batch_size, self.type_sequence_label_size)   )


 def 					__SCREAMING_SNAKE_CASE				(			self       :  Optional[Any] ,					__lowerCamelCase       :  List[str] ,					__lowerCamelCase       :  Dict ,					__lowerCamelCase       :  List[str] ,					__lowerCamelCase       :  List[str]   ):
    UpperCAmelCase__  :Any            =			self.num_labels
    UpperCAmelCase__  :Union[str, Any]            =			DataaVecVisionForSemanticSegmentation(__lowerCamelCase   )
    model.to(__lowerCamelCase   )
    model.eval()
    UpperCAmelCase__  :List[str]            =			model(__lowerCamelCase   )
    self.parent.assertEqual(
        result.logits.shape ,					(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)   )
    UpperCAmelCase__  :Dict            =			model(__lowerCamelCase ,					labels=__lowerCamelCase   )
    self.parent.assertEqual(
        result.logits.shape ,					(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)   )





 def 					__SCREAMING_SNAKE_CASE				(			self       :  Optional[Any]   ):
    UpperCAmelCase__  :List[Any]            =			self.prepare_config_and_inputs()
    UpperCAmelCase__      ,	UpperCAmelCase__      ,	UpperCAmelCase__      ,	UpperCAmelCase__  :Union[str, Any]            =			config_and_inputs
    UpperCAmelCase__  :Optional[Any]            =			{'''pixel_values''': pixel_values}
    return config, inputs_dict




@require_torch
class 							UpperCAmelCase ( _snake_case	,   _snake_case	,   unittest.TestCase	):
 UpperCAmelCase				=				(
     (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
     if is_torch_available()
     else ()
 )
 UpperCAmelCase				=				(
     {
         "feature-extraction": DataaVecVisionModel,
         "image-classification": DataaVecVisionForImageClassification,
         "image-segmentation": DataaVecVisionForSemanticSegmentation,
     }
     if is_torch_available()
     else {}
 )

 UpperCAmelCase				=				False
 UpperCAmelCase				=				False
 UpperCAmelCase				=				False


 def 					__SCREAMING_SNAKE_CASE				(			self       :  List[str]   ):
    UpperCAmelCase__  :Optional[Any]            =			DataaVecVisionModelTester(self   )
    UpperCAmelCase__  :Optional[int]            =			ConfigTester(
        self ,					config_class=__lowerCamelCase ,					has_text_modality=__lowerCamelCase ,					hidden_size=3_7   )


 def 					__SCREAMING_SNAKE_CASE				(			self       :  Any   ):
    self.config_tester.run_common_tests()


 def 					__SCREAMING_SNAKE_CASE				(			self       :  Dict   ):
    # 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 					__SCREAMING_SNAKE_CASE				(			self       :  List[str]   ):
    pass


 def 					__SCREAMING_SNAKE_CASE				(			self       :  Dict   ):
    UpperCAmelCase__      ,	UpperCAmelCase__  :List[Any]            =			self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
       UpperCAmelCase__  :Tuple            =			model_class(__lowerCamelCase   )
       self.assertIsInstance(model.get_input_embeddings() ,					(nn.Module)   )
       UpperCAmelCase__  :Any            =			model.get_output_embeddings()
       self.assertTrue(x is None or isinstance(__lowerCamelCase ,					nn.Linear   )   )


 def 					__SCREAMING_SNAKE_CASE				(			self       :  List[str]   ):
    UpperCAmelCase__      ,	UpperCAmelCase__  :Dict            =			self.model_tester.prepare_config_and_inputs_for_common()

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

       UpperCAmelCase__  :Any            =			['''pixel_values''']
       self.assertListEqual(arg_names[:1] ,					__lowerCamelCase   )


 def 					__SCREAMING_SNAKE_CASE				(			self       :  List[str]   ):
    UpperCAmelCase__  :Optional[int]            =			self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__lowerCamelCase   )


 def 					__SCREAMING_SNAKE_CASE				(			self       :  Union[str, Any]   ):
    UpperCAmelCase__  :int            =			self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_segmentation(*__lowerCamelCase   )


 def 					__SCREAMING_SNAKE_CASE				(			self       :  Union[str, Any]   ):
    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(__lowerCamelCase   )]:
          continue

       UpperCAmelCase__  :Dict            =			model_class(__lowerCamelCase   )
       model.to(__lowerCamelCase   )
       model.train()
       UpperCAmelCase__  :Optional[Any]            =			self._prepare_for_class(__lowerCamelCase ,					__lowerCamelCase ,					return_labels=__lowerCamelCase   )
       UpperCAmelCase__  :Optional[int]            =			model(**__lowerCamelCase   ).loss
       loss.backward()


 def 					__SCREAMING_SNAKE_CASE				(			self       :  Any   ):
    UpperCAmelCase__      ,	UpperCAmelCase__  :str            =			self.model_tester.prepare_config_and_inputs_for_common()
    if not self.model_tester.is_training:
       return

    UpperCAmelCase__  :str            =			False
    UpperCAmelCase__  :Dict            =			True

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


 def 					__SCREAMING_SNAKE_CASE				(			self       :  Optional[Any]   ):
    UpperCAmelCase__      ,	UpperCAmelCase__  :Any            =			self.model_tester.prepare_config_and_inputs_for_common()

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


 def 					__SCREAMING_SNAKE_CASE				(			self       :  Any   ):
    UpperCAmelCase__  :Optional[int]            =			self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*__lowerCamelCase   )





 @slow
 def 					__SCREAMING_SNAKE_CASE				(			self       :  int   ):
    for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       UpperCAmelCase__  :int            =			DataaVecVisionModel.from_pretrained(__lowerCamelCase   )
       self.assertIsNotNone(__lowerCamelCase   )


def 					a__    (				):
   UpperCAmelCase__  :List[str]            =			Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''	)
   return image




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


 @cached_property
 def 					__SCREAMING_SNAKE_CASE				(			self       :  str   ):
    return (
        BeitImageProcessor.from_pretrained('''facebook/data2vec-vision-base-ft1k'''   ) if is_vision_available() else None
    )





 @slow
 def 					__SCREAMING_SNAKE_CASE				(			self       :  List[Any]   ):
    UpperCAmelCase__  :Tuple            =			DataaVecVisionForImageClassification.from_pretrained('''facebook/data2vec-vision-base-ft1k'''   ).to(
        __lowerCamelCase   )

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

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

    # verify the logits
    UpperCAmelCase__  :int            =			torch.Size((1, 1_0_0_0)   )
    self.assertEqual(logits.shape ,					__lowerCamelCase   )

    UpperCAmelCase__  :str            =			torch.tensor([0.32_77, -0.13_95, 0.09_11]   ).to(__lowerCamelCase   )

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

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







'''simple docstring'''





from scipy.constants import g


def 					a__    (				UpperCamelCase_	:			float,      UpperCamelCase_	:			float	):
   if mass < 0:
      # handling of negative values of mass
      raise ValueError('''The mass of a body cannot be negative'''	)
   if height < 0:
      # handling of negative values of height
      raise ValueError('''The height above the ground cannot be negative'''	)
   return mass * g * height


if __name__ == "__main__":
    from doctest import testmod

    testmod(name='''potential_energy''')



