code: 
  
  
  
  
  
  
  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 					snake_case_							:
  
  
  
  
  
  
  
     """simple docstring"""
  
  
  
     def __init__(    self:	Union[str, Any]   ,       snake_case__:	List[str]   ,       snake_case__:	Dict=100   ,       snake_case__:	str=13   ,       snake_case__:	List[Any]=30   ,       snake_case__:	List[Any]=2   ,       snake_case__:	Union[str, Any]=3   ,       snake_case__:	List[Any]=True   ,       snake_case__:	List[str]=True   ,       snake_case__:	str=32   ,       snake_case__:	List[Any]=4   ,       snake_case__:	Tuple=4   ,       snake_case__:	Optional[Any]=37   ,       snake_case__:	Dict="gelu"   ,       snake_case__:	Any=0.1   ,       snake_case__:	List[Any]=0.1   ,       snake_case__:	int=10   ,       snake_case__:	List[str]=0.02   ,       snake_case__:	Dict=3   ,       snake_case__:	str=None   ,       snake_case__:	Union[str, Any]=[0, 1, 2, 3]   ,       )  ->		List[Any]:
  
  
           """simple docstring"""
  
  
  
           _lowercase     =	parent
           _lowercase     =	100
           _lowercase     =	batch_size
           _lowercase     =	image_size
           _lowercase     =	patch_size
           _lowercase     =	num_channels
           _lowercase     =	is_training
           _lowercase     =	use_labels
           _lowercase     =	hidden_size
           _lowercase     =	num_hidden_layers
           _lowercase     =	num_attention_heads
           _lowercase     =	intermediate_size
           _lowercase     =	hidden_act
           _lowercase     =	hidden_dropout_prob
           _lowercase     =	attention_probs_dropout_prob
           _lowercase     =	type_sequence_label_size
           _lowercase     =	initializer_range
           _lowercase     =	scope
           _lowercase     =	out_indices
           _lowercase     =	num_labels
  
           # in BeiT, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
           _lowercase     =	(image_size // patch_size) ** 2
           _lowercase     =	num_patches + 1
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	Any	)  ->		List[str]:
  
  
           """simple docstring"""
  
  
  
           _lowercase     =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)
  
           _lowercase     =	None
           _lowercase     =	None
           if self.use_labels:
                 _lowercase     =	ids_tensor([self.batch_size]   ,       self.type_sequence_label_size	)
                 _lowercase     =	ids_tensor([self.batch_size, self.image_size, self.image_size]   ,       self.num_labels	)
  
           _lowercase     =	self.get_config()
  
           return config, pixel_values, labels, pixel_labels
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	Optional[int]	)  ->		Dict:
  
  
           """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=snake_case__   ,       initializer_range=self.initializer_range   ,       out_indices=self.out_indices   ,       )
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	str   ,       snake_case__:	List[Any]   ,       snake_case__:	List[str]   ,       snake_case__:	Any   ,       snake_case__:	List[Any]	)  ->		Union[str, Any]:
  
  
           """simple docstring"""
  
  
  
           _lowercase     =	DataaVecVisionModel(config=snake_case__	)
           model.to(snake_case__	)
           model.eval()
           _lowercase     =	model(snake_case__	)
           # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
           _lowercase     =	(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:	Any   ,       snake_case__:	Tuple   ,       snake_case__:	List[str]   ,       snake_case__:	Any   ,       snake_case__:	Dict	)  ->		Optional[Any]:
  
  
           """simple docstring"""
  
  
  
           _lowercase     =	self.type_sequence_label_size
           _lowercase     =	DataaVecVisionForImageClassification(snake_case__	)
           model.to(snake_case__	)
           model.eval()
           _lowercase     =	model(snake_case__   ,       labels=snake_case__	)
           self.parent.assertEqual(result.logits.shape   ,       (self.batch_size, self.type_sequence_label_size)	)
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	List[Any]   ,       snake_case__:	Union[str, Any]   ,       snake_case__:	Optional[int]   ,       snake_case__:	Dict   ,       snake_case__:	str	)  ->		Dict:
  
  
           """simple docstring"""
  
  
  
           _lowercase     =	self.num_labels
           _lowercase     =	DataaVecVisionForSemanticSegmentation(snake_case__	)
           model.to(snake_case__	)
           model.eval()
           _lowercase     =	model(snake_case__	)
           self.parent.assertEqual(
               result.logits.shape   ,       (self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)	)
           _lowercase     =	model(snake_case__   ,       labels=snake_case__	)
           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:	str	)  ->		Dict:
  
  
           """simple docstring"""
  
  
  
           _lowercase     =	self.prepare_config_and_inputs()
           _lowercase ,    _lowercase ,    _lowercase ,    _lowercase     =	config_and_inputs
           _lowercase     =	{'pixel_values': pixel_values}
           return config, inputs_dict
  
  
  
  
  
  
  @require_torch
  class 					snake_case_							(       lowercase_      ,			lowercase_      ,			unittest.TestCase      ):
  
  
  
  
  
  
  
     """simple docstring"""
  
  
  
     __lowerCAmelCase      =						(
         (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
         if is_torch_available()
         else ()
     )
     __lowerCAmelCase      =						(
         {
             """feature-extraction""": DataaVecVisionModel,
             """image-classification""": DataaVecVisionForImageClassification,
             """image-segmentation""": DataaVecVisionForSemanticSegmentation,
         }
         if is_torch_available()
         else {}
     )
  
     __lowerCAmelCase      =						False
     __lowerCAmelCase      =						False
     __lowerCAmelCase      =						False
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	int	)  ->		str:
  
  
           """simple docstring"""
  
  
  
           _lowercase     =	DataaVecVisionModelTester(self	)
           _lowercase     =	ConfigTester(
               self   ,       config_class=snake_case__   ,       has_text_modality=snake_case__   ,       hidden_size=37	)
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	Union[str, Any]	)  ->		Union[str, Any]:
  
  
           """simple docstring"""
  
  
  
           self.config_tester.run_common_tests()
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	Dict	)  ->		List[Any]:
  
  
           """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 			SCREAMING_SNAKE_CASE__				(    self:	str	)  ->		Optional[Any]:
  
  
           """simple docstring"""
  
  
  
           pass
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	str	)  ->		Optional[int]:
  
  
           """simple docstring"""
  
  
  
           _lowercase ,    _lowercase     =	self.model_tester.prepare_config_and_inputs_for_common()
  
           for model_class in self.all_model_classes:
                 _lowercase     =	model_class(snake_case__	)
                 self.assertIsInstance(model.get_input_embeddings()   ,       (nn.Module)	)
                 _lowercase     =	model.get_output_embeddings()
                 self.assertTrue(x is None or isinstance(snake_case__   ,       nn.Linear	)	)
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	int	)  ->		int:
  
  
           """simple docstring"""
  
  
  
           _lowercase ,    _lowercase     =	self.model_tester.prepare_config_and_inputs_for_common()
  
           for model_class in self.all_model_classes:
                 _lowercase     =	model_class(snake_case__	)
                 _lowercase     =	inspect.signature(model.forward	)
                 # signature.parameters is an OrderedDict => so arg_names order is deterministic
                 _lowercase     =	[*signature.parameters.keys()]
  
                 _lowercase     =	['pixel_values']
                 self.assertListEqual(arg_names[:1]   ,       snake_case__	)
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	Dict	)  ->		str:
  
  
           """simple docstring"""
  
  
  
           _lowercase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_model(*snake_case__	)
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	Optional[int]	)  ->		Union[str, Any]:
  
  
           """simple docstring"""
  
  
  
           _lowercase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_segmentation(*snake_case__	)
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	List[Any]	)  ->		Dict:
  
  
           """simple docstring"""
  
  
  
           if not self.model_tester.is_training:
                 return
  
           _lowercase ,    _lowercase     =	self.model_tester.prepare_config_and_inputs_for_common()
           _lowercase     =	True
  
           for model_class in self.all_model_classes:
                 if model_class in [*get_values(snake_case__	)]:
                       continue
  
                 _lowercase     =	model_class(snake_case__	)
                 model.to(snake_case__	)
                 model.train()
                 _lowercase     =	self._prepare_for_class(snake_case__   ,       snake_case__   ,       return_labels=snake_case__	)
                 _lowercase     =	model(**snake_case__	).loss
                 loss.backward()
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	Tuple	)  ->		Dict:
  
  
           """simple docstring"""
  
  
  
           _lowercase ,    _lowercase     =	self.model_tester.prepare_config_and_inputs_for_common()
           if not self.model_tester.is_training:
                 return
  
           _lowercase     =	False
           _lowercase     =	True
  
           for model_class in self.all_model_classes:
                 if model_class in [*get_values(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":
                       _lowercase ,    _lowercase ,    _lowercase ,    _lowercase     =	inputs_dict['pixel_values'].shape
                       _lowercase     =	torch.zeros(
                           [self.model_tester.batch_size, height, width]   ,       device=snake_case__	).long()
                 _lowercase     =	model_class(snake_case__	)
                 model.gradient_checkpointing_enable()
                 model.to(snake_case__	)
                 model.train()
                 _lowercase     =	self._prepare_for_class(snake_case__   ,       snake_case__   ,       return_labels=snake_case__	)
                 _lowercase     =	model(**snake_case__	).loss
                 loss.backward()
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	int	)  ->		List[str]:
  
  
           """simple docstring"""
  
  
  
           _lowercase ,    _lowercase     =	self.model_tester.prepare_config_and_inputs_for_common()
  
           _lowercase     =	_config_zero_init(snake_case__	)
           for model_class in self.all_model_classes:
                 _lowercase     =	model_class(config=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 			SCREAMING_SNAKE_CASE__				(    self:	Optional[int]   ,       snake_case__:	Tuple   ,       snake_case__:	str   ,       snake_case__:	Any   ,       snake_case__:	List[Any]=2E-4   ,       snake_case__:	Optional[int]="outputs"   ,       snake_case__:	List[Any]=None	)  ->		List[str]:
  
  
           """simple docstring"""
  
  
  
           super().check_pt_tf_outputs(snake_case__   ,       snake_case__   ,       snake_case__   ,       snake_case__   ,       snake_case__   ,       snake_case__	)
  
     def 			SCREAMING_SNAKE_CASE__				(    self:	Any	)  ->		List[str]:
  
  
           """simple docstring"""
  
  
  
           _lowercase     =	self.model_tester.prepare_config_and_inputs()
           self.model_tester.create_and_check_for_image_classification(*snake_case__	)
  
     @slow
     def 			SCREAMING_SNAKE_CASE__				(    self:	Union[str, Any]	)  ->		Optional[int]:
  
  
           """simple docstring"""
  
  
  
           for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 _lowercase     =	DataaVecVisionModel.from_pretrained(snake_case__	)
                 self.assertIsNotNone(snake_case__	)
  
  
  
  
  
  
  def        UpperCAmelCase      (   ):
  
  
        '''simple docstring'''
  
  
  
        _lowercase     =	Image.open('./tests/fixtures/tests_samples/COCO/000000039769.png'      )
        return image
  
  @require_torch
  @require_vision
  class 					snake_case_							(       unittest.TestCase      ):
  
  
  
  
  
  
  
     """simple docstring"""
  
  
  
     @cached_property
     def 			SCREAMING_SNAKE_CASE__				(    self:	Tuple	)  ->		str:
  
  
           """simple docstring"""
  
  
  
           return (
               BeitImageProcessor.from_pretrained('facebook/data2vec-vision-base-ft1k'	) if is_vision_available() else None
           )
  
     @slow
     def 			SCREAMING_SNAKE_CASE__				(    self:	List[str]	)  ->		Optional[int]:
  
  
           """simple docstring"""
  
  
  
           _lowercase     =	DataaVecVisionForImageClassification.from_pretrained('facebook/data2vec-vision-base-ft1k'	).to(
               snake_case__	)
  
           _lowercase     =	self.default_image_processor
           _lowercase     =	prepare_img()
           _lowercase     =	image_processor(images=snake_case__   ,       return_tensors='pt'	).to(snake_case__	)
  
           # forward pass
           with torch.no_grad():
                 _lowercase     =	model(**snake_case__	)
           _lowercase     =	outputs.logits
  
           # verify the logits
           _lowercase     =	torch.Size((1, 1_000)	)
           self.assertEqual(logits.shape   ,       snake_case__	)
  
           _lowercase     =	torch.tensor([0.32_77, -0.13_95, 0.09_11]	).to(snake_case__	)
  
           self.assertTrue(torch.allclose(logits[0, :3]   ,       snake_case__   ,       atol=1E-4	)	)
  
           _lowercase     =	[model.config.labelaid[i] for i in ['remote control, remote', 'tabby, tabby cat']]
           self.assertEqual(logits[0].topk(2	).indices.cpu().tolist()   ,       snake_case__	)
  
style_context: 
  
  
  
  
  
  
  import functools
  import operator
  
  from ...configuration_utils import PretrainedConfig
  from ...utils import logging
  
  
  lowerCamelCase										=  logging.get_logger(__name__)
  
  lowerCamelCase										=  {
      '''facebook/hubert-base-ls960''': '''https://huggingface.co/facebook/hubert-base-ls960/resolve/main/config.json''',
      # See all Hubert models at https://huggingface.co/models?filter=hubert
  }
  
  class 					snake_case_							(       lowercase_      ):
  
  
  
  
  
  
  
     """simple docstring"""
  
  
  
     __lowerCAmelCase      =						"""hubert"""
  
     def __init__(    self:	Any   ,       snake_case__:	str=32   ,       snake_case__:	int=768   ,       snake_case__:	Dict=12   ,       snake_case__:	Optional[int]=12   ,       snake_case__:	List[str]=3_072   ,       snake_case__:	Optional[Any]="gelu"   ,       snake_case__:	Optional[int]=0.1   ,       snake_case__:	List[str]=0.1   ,       snake_case__:	Optional[int]=0.1   ,       snake_case__:	List[str]=True   ,       snake_case__:	Union[str, Any]=0.0   ,       snake_case__:	Union[str, Any]=0.1   ,       snake_case__:	List[str]=0.1   ,       snake_case__:	List[Any]=0.02   ,       snake_case__:	Dict=1E-5   ,       snake_case__:	Any="group"   ,       snake_case__:	Union[str, Any]="gelu"   ,       snake_case__:	List[str]=(512, 512, 512, 512, 512, 512, 512)   ,       snake_case__:	Union[str, Any]=(5, 2, 2, 2, 2, 2, 2)   ,       snake_case__:	Any=(10, 3, 3, 3, 3, 2, 2)   ,       snake_case__:	int=False   ,       snake_case__:	Any=128   ,       snake_case__:	Dict=16   ,       snake_case__:	Optional[Any]=False   ,       snake_case__:	Tuple=True   ,       snake_case__:	int=0.05   ,       snake_case__:	List[Any]=10   ,       snake_case__:	Tuple=2   ,       snake_case__:	List[Any]=0.0   ,       snake_case__:	Optional[int]=10   ,       snake_case__:	Optional[int]=0   ,       snake_case__:	Union[str, Any]="sum"   ,       snake_case__:	Union[str, Any]=False   ,       snake_case__:	int=False   ,       snake_case__:	Any=256   ,       snake_case__:	Union[str, Any]=0   ,       snake_case__:	Optional[int]=1   ,       snake_case__:	List[str]=2   ,       **snake_case__:	Optional[int]   ,       )  ->		Any:
  
  
         """simple docstring"""
  
  
  
         super().__init__(**snake_case__   ,       pad_token_id=snake_case__   ,       bos_token_id=snake_case__   ,       eos_token_id=snake_case__	)
         _lowercase     =	hidden_size
         _lowercase     =	feat_extract_norm
         _lowercase     =	feat_extract_activation
         _lowercase     =	list(snake_case__	)
         _lowercase     =	list(snake_case__	)
         _lowercase     =	list(snake_case__	)
         _lowercase     =	conv_bias
         _lowercase     =	num_conv_pos_embeddings
         _lowercase     =	num_conv_pos_embedding_groups
         _lowercase     =	len(self.conv_dim	)
         _lowercase     =	num_hidden_layers
         _lowercase     =	intermediate_size
         _lowercase     =	hidden_act
         _lowercase     =	num_attention_heads
         _lowercase     =	hidden_dropout
         _lowercase     =	attention_dropout
         _lowercase     =	activation_dropout
         _lowercase     =	feat_proj_layer_norm
         _lowercase     =	feat_proj_dropout
         _lowercase     =	final_dropout
         _lowercase     =	layerdrop
         _lowercase     =	layer_norm_eps
         _lowercase     =	initializer_range
         _lowercase     =	vocab_size
         _lowercase     =	do_stable_layer_norm
         _lowercase     =	use_weighted_layer_sum
         _lowercase     =	classifier_proj_size
  
         if (
             (len(self.conv_stride	) != self.num_feat_extract_layers)
             or (len(self.conv_kernel	) != self.num_feat_extract_layers)
             or (len(self.conv_dim	) != self.num_feat_extract_layers)
         ):
             raise ValueError(
                 'Configuration for convolutional layers is incorrect. It is required that `len(config.conv_dim)` =='
                 ' `len(config.conv_stride)` == `len(config.conv_kernel)`, but is `len(config.conv_dim) ='
                 f''' {len(self.conv_dim	)}`, `len(config.conv_stride) = {len(self.conv_stride	)}`,'''
                 f''' `len(config.conv_kernel) = {len(self.conv_kernel	)}`.'''	)
  
         # fine-tuning config parameters for SpecAugment: https://arxiv.org/abs/1904.08779
         _lowercase     =	apply_spec_augment
         _lowercase     =	mask_time_prob
         _lowercase     =	mask_time_length
         _lowercase     =	mask_time_min_masks
         _lowercase     =	mask_feature_prob
         _lowercase     =	mask_feature_length
         _lowercase     =	mask_feature_min_masks
  
         # ctc loss
         _lowercase     =	ctc_loss_reduction
         _lowercase     =	ctc_zero_infinity
  
     @property
     def 			SCREAMING_SNAKE_CASE__				(    self:	int	)  ->		Optional[int]:
  
  
         """simple docstring"""
  
  
  
         return functools.reduce(operator.mul   ,       self.conv_stride   ,       1	)
  