



'''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  lowerCamelCase_   :
  """simple docstring"""




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

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




  def 						_lowercase					(			self				:     Tuple       ) -> str:
    __lowerCamelCase	:	List[Any]   	=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

    __lowerCamelCase	:	int   	=			None
    __lowerCamelCase	:	List[str]   	=			None
    if self.use_labels:
      __lowerCamelCase	:	Any   	=			ids_tensor([self.batch_size]      ,     self.type_sequence_label_size       )
      __lowerCamelCase	:	Any   	=			ids_tensor([self.batch_size, self.image_size, self.image_size]      ,     self.num_labels       )

    __lowerCamelCase	:	int   	=			self.get_config()

    return config, pixel_values, labels, pixel_labels




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




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






@require_torch
class  lowerCamelCase_   (    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 						_lowercase					(			self				:     Union[str, Any]       ) -> List[str]:
    __lowerCamelCase	:	Optional[Any]   	=			DataaVecVisionModelTester(self       )
    __lowerCamelCase	:	Optional[Any]   	=			ConfigTester(
        self      ,     config_class=__lowerCAmelCase      ,     has_text_modality=__lowerCAmelCase      ,     hidden_size=37       )




  def 						_lowercase					(			self				:     List[str]       ) -> int:
    self.config_tester.run_common_tests()




  def 						_lowercase					(			self				:     Dict       ) -> Optional[int]:
    pass




  @require_torch_multi_gpu
  @unittest.skip(
      reason='Data2VecVision has some layers using `add_module` which doesn\'t work well with `nn.DataParallel`'       )
  def 						_lowercase					(			self				:     Optional[Any]       ) -> Optional[int]:
    pass




  def 						_lowercase					(			self				:     Any       ) -> int:
    __lowerCamelCase	,__lowerCamelCase	:	List[str]   	=			self.model_tester.prepare_config_and_inputs_for_common()

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




  def 						_lowercase					(			self				:     Optional[Any]       ) -> Union[str, Any]:
    __lowerCamelCase	,__lowerCamelCase	:	Tuple   	=			self.model_tester.prepare_config_and_inputs_for_common()

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

      __lowerCamelCase	:	str   	=			['pixel_values']
      self.assertListEqual(arg_names[:1]      ,     __lowerCAmelCase       )




  def 						_lowercase					(			self				:     str       ) -> Optional[Any]:
    __lowerCamelCase	:	Optional[int]   	=			self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__lowerCAmelCase       )




  def 						_lowercase					(			self				:     Dict       ) -> Optional[Any]:
    __lowerCamelCase	:	Optional[Any]   	=			self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_segmentation(*__lowerCAmelCase       )




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


    if not self.model_tester.is_training:
      return

    __lowerCamelCase	,__lowerCamelCase	:	List[Any]   	=			self.model_tester.prepare_config_and_inputs_for_common()
    __lowerCamelCase	:	List[str]   	=			True

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

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




  def 						_lowercase					(			self				:     Tuple       ) -> Tuple:
    __lowerCamelCase	,__lowerCamelCase	:	Any   	=			self.model_tester.prepare_config_and_inputs_for_common()
    if not self.model_tester.is_training:
      return

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




  def 						_lowercase					(			self				:     Optional[Any]       ) -> Union[str, Any]:
    __lowerCamelCase	,__lowerCamelCase	:	str   	=			self.model_tester.prepare_config_and_inputs_for_common()

    __lowerCamelCase	:	Dict   	=			_config_zero_init(__lowerCAmelCase       )
    for model_class in self.all_model_classes:
      __lowerCamelCase	:	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 						_lowercase					(			self				:     Tuple      ,     _a				:     Dict      ,     _a				:     Optional[int]      ,     _a				:     List[Any]      ,     _a				:     Dict=2e-4      ,     _a				:     int="outputs"      ,     _a				:     List[Any]=None       ) -> Dict:
    super().check_pt_tf_outputs(__lowerCAmelCase      ,     __lowerCAmelCase      ,     __lowerCAmelCase      ,     __lowerCAmelCase      ,     __lowerCAmelCase      ,     __lowerCAmelCase       )




  def 						_lowercase					(			self				:     Optional[Any]       ) -> Any:
    __lowerCamelCase	:	int   	=			self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*__lowerCAmelCase       )




  @slow
  def 						_lowercase					(			self				:     Tuple       ) -> Union[str, Any]:


    for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
      __lowerCamelCase	:	Optional[Any]   	=			DataaVecVisionModel.from_pretrained(__lowerCAmelCase       )
      self.assertIsNotNone(__lowerCAmelCase       )




def 	a_					(							)				->				Any:
  __lowerCamelCase	:	Tuple   	=			Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'	)
  return image







@require_torch
@require_vision
class  lowerCamelCase_   (    unittest.TestCase					):
  """simple docstring"""




  @cached_property
  def 						_lowercase					(			self				:     Optional[Any]       ) -> Union[str, Any]:
    return (
        BeitImageProcessor.from_pretrained('facebook/data2vec-vision-base-ft1k'       ) if is_vision_available() else None
    )




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

    __lowerCamelCase	:	List[Any]   	=			self.default_image_processor
    __lowerCamelCase	:	Tuple   	=			prepare_img()
    __lowerCamelCase	:	Dict   	=			image_processor(images=__lowerCAmelCase      ,     return_tensors='pt'       ).to(__lowerCAmelCase       )

    # forward pass
    with torch.no_grad():
      __lowerCamelCase	:	Dict   	=			model(**__lowerCAmelCase       )
    __lowerCamelCase	:	List[str]   	=			outputs.logits

    # verify the logits
    __lowerCamelCase	:	Union[str, Any]   	=			torch.Size((1, 1000)       )
    self.assertEqual(logits.shape      ,     __lowerCAmelCase       )

    __lowerCamelCase	:	List[str]   	=			torch.tensor([0.3277, -0.1395, 0.0911]       ).to(__lowerCAmelCase       )

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

    __lowerCamelCase	:	Dict   	=			[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'''





import unittest

from diffusers import __version__
from diffusers.utils import deprecate






class  lowerCamelCase_   (    unittest.TestCase					):
  """simple docstring"""




  a_							 =""".""".join([str(int(__version__.split("""."""					)[0]					) + 1					)] + __version__.split("""."""					)[1:]					)
  a_							 ="""0.0.1"""




  def 						_lowercase					(			self				:     Optional[Any]       ) -> int:
    __lowerCamelCase	:	Any   	=			{'deprecated_arg': 4}

    with self.assertWarns(_a       ) as warning:
      __lowerCamelCase	:	Optional[int]   	=			deprecate('deprecated_arg'      ,     self.higher_version      ,     'message'      ,     take_from=_a       )

    assert output == 4
    assert (
        str(warning.warning       )
        == f'The `deprecated_arg` argument is deprecated and will be removed in version {self.higher_version}.'
        " message"
    )




  def 						_lowercase					(			self				:     Union[str, Any]       ) -> Optional[int]:
    __lowerCamelCase	:	int   	=			{'deprecated_arg': 4}

    with self.assertWarns(_a       ) as warning:
      __lowerCamelCase	:	Optional[Any]   	=			deprecate(('deprecated_arg', self.higher_version, 'message')      ,     take_from=_a       )

    assert output == 4
    assert (
        str(warning.warning       )
        == f'The `deprecated_arg` argument is deprecated and will be removed in version {self.higher_version}.'
        " message"
    )




  def 						_lowercase					(			self				:     int       ) -> Optional[Any]:
    __lowerCamelCase	:	Optional[int]   	=			{'deprecated_arg_1': 4, 'deprecated_arg_2': 8}
    with self.assertWarns(_a       ) as warning:
      __lowerCamelCase	,__lowerCamelCase	:	Any   	=			deprecate(
          ('deprecated_arg_1', self.higher_version, 'Hey')      ,     ('deprecated_arg_2', self.higher_version, 'Hey')      ,     take_from=_a      ,     )
    assert output_a == 4
    assert output_a == 8
    assert (
        str(warning.warnings[0].message       )
        == "The `deprecated_arg_1` argument is deprecated and will be removed in version"
        f' {self.higher_version}. Hey'
    )
    assert (
        str(warning.warnings[1].message       )
        == "The `deprecated_arg_2` argument is deprecated and will be removed in version"
        f' {self.higher_version}. Hey'
    )




  def 						_lowercase					(			self				:     str       ) -> Optional[Any]:
    __lowerCamelCase	:	Optional[int]   	=			{'deprecated_arg': 4}

    with self.assertRaises(_a       ) as error:
      deprecate(('wrong_arg', self.higher_version, 'message')      ,     take_from=_a       )

    assert "test_deprecate_function_incorrect_arg in" in str(error.exception       )
    assert "line" in str(error.exception       )
    assert "got an unexpected keyword argument `deprecated_arg`" in str(error.exception       )




  def 						_lowercase					(			self				:     Optional[Any]       ) -> Union[str, Any]:
    with self.assertWarns(_a       ) as warning:
      deprecate(('deprecated_arg', self.higher_version, 'message')       )

    assert (
        str(warning.warning       )
        == f'`deprecated_arg` is deprecated and will be removed in version {self.higher_version}. message'
    )




  def 						_lowercase					(			self				:     Optional[Any]       ) -> Union[str, Any]:
    with self.assertWarns(_a       ) as warning:
      deprecate(
          ('deprecated_arg_1', self.higher_version, 'Hey')      ,     ('deprecated_arg_2', self.higher_version, 'Hey')      ,     )
    assert (
        str(warning.warnings[0].message       )
        == f'`deprecated_arg_1` is deprecated and will be removed in version {self.higher_version}. Hey'
    )
    assert (
        str(warning.warnings[1].message       )
        == f'`deprecated_arg_2` is deprecated and will be removed in version {self.higher_version}. Hey'
    )




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






    class  lowerCamelCase_   :
      """simple docstring"""




      a_							 =5

    with self.assertWarns(_a       ) as warning:
      __lowerCamelCase	:	int   	=			deprecate(('arg', self.higher_version, 'message')      ,     take_from=Args()       )

    assert arg == 5
    assert (
        str(warning.warning       )
        == f'The `arg` attribute is deprecated and will be removed in version {self.higher_version}. message'
    )




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






    class  lowerCamelCase_   :
      """simple docstring"""




      a_							 =5
      a_							 =7

    with self.assertWarns(_a       ) as warning:
      __lowerCamelCase	,__lowerCamelCase	:	List[str]   	=			deprecate(
          ('arg', self.higher_version, 'message')      ,     ('foo', self.higher_version, 'message')      ,     ('does not exist', self.higher_version, 'message')      ,     take_from=Args()      ,     )

    assert arg_a == 5
    assert arg_a == 7
    assert (
        str(warning.warning       )
        == f'The `arg` attribute is deprecated and will be removed in version {self.higher_version}. message'
    )
    assert (
        str(warning.warnings[0].message       )
        == f'The `arg` attribute is deprecated and will be removed in version {self.higher_version}. message'
    )
    assert (
        str(warning.warnings[1].message       )
        == f'The `foo` attribute is deprecated and will be removed in version {self.higher_version}. message'
    )




  def 						_lowercase					(			self				:     Union[str, Any]       ) -> List[str]:
    __lowerCamelCase	:	Union[str, Any]   	=			{'deprecated_arg': 4}

    with self.assertRaises(_a       ) as error:
      deprecate(('wrong_arg', self.lower_version, 'message')      ,     take_from=_a       )

    assert (
        str(error.exception       )
        == "The deprecation tuple ('wrong_arg', '0.0.1', 'message') should be removed since diffusers' version"
        f' {__version__} is >= {self.lower_version}'
    )




  def 						_lowercase					(			self				:     Optional[int]       ) -> str:
    with self.assertWarns(_a       ) as warning:
      deprecate(('deprecated_arg', self.higher_version, 'This message is better!!!')      ,     standard_warn=_a       )

    assert str(warning.warning       ) == "This message is better!!!"




  def 						_lowercase					(			self				:     List[Any]       ) -> Union[str, Any]:
    with self.assertWarns(_a       ) as warning:
      deprecate(('deprecated_arg', self.higher_version, 'This message is better!!!')      ,     standard_warn=_a       )
    assert str(warning.warning       ) == "This message is better!!!"
    assert "diffusers/tests/others/test_utils.py" in warning.filename






