





'''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     :	List[Any] ,				lowerCAmelCase__     :	Dict ,				lowerCAmelCase__     :	Dict=100 ,				lowerCAmelCase__     :	List[str]=13 ,				lowerCAmelCase__     :	Dict=30 ,				lowerCAmelCase__     :	str=2 ,				lowerCAmelCase__     :	str=3 ,				lowerCAmelCase__     :	int=True ,				lowerCAmelCase__     :	Optional[Any]=True ,				lowerCAmelCase__     :	Tuple=32 ,				lowerCAmelCase__     :	int=4 ,				lowerCAmelCase__     :	Tuple=4 ,				lowerCAmelCase__     :	Dict=37 ,				lowerCAmelCase__     :	str="gelu" ,				lowerCAmelCase__     :	Dict=0.1 ,				lowerCAmelCase__     :	Optional[Any]=0.1 ,				lowerCAmelCase__     :	Optional[Any]=10 ,				lowerCAmelCase__     :	Optional[Any]=0.02 ,				lowerCAmelCase__     :	str=3 ,				lowerCAmelCase__     :	Optional[Any]=None ,				lowerCAmelCase__     :	Dict=[0, 1, 2, 3] ,				)					->  Union[str, Any]:

            '''simple docstring'''




            _UpperCamelCase       					= parent
            _UpperCamelCase       					= 100
            _UpperCamelCase       					= batch_size
            _UpperCamelCase       					= image_size
            _UpperCamelCase       					= patch_size
            _UpperCamelCase       					= num_channels
            _UpperCamelCase       					= is_training
            _UpperCamelCase       					= use_labels
            _UpperCamelCase       					= hidden_size
            _UpperCamelCase       					= num_hidden_layers
            _UpperCamelCase       					= num_attention_heads
            _UpperCamelCase       					= intermediate_size
            _UpperCamelCase       					= hidden_act
            _UpperCamelCase       					= hidden_dropout_prob
            _UpperCamelCase       					= attention_probs_dropout_prob
            _UpperCamelCase       					= type_sequence_label_size
            _UpperCamelCase       					= initializer_range
            _UpperCamelCase       					= scope
            _UpperCamelCase       					= out_indices
            _UpperCamelCase       					= num_labels

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





       def snake_case__		(							self     :	List[Any]  )					->  List[str]:

            '''simple docstring'''




            _UpperCamelCase       					= floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

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

            _UpperCamelCase       					= self.get_config()

            return config, pixel_values, labels, pixel_labels





       def snake_case__		(							self     :	List[Any]  )					->  List[Any]:

            '''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=lowerCAmelCase__ ,				initializer_range=self.initializer_range ,				out_indices=self.out_indices ,				)





       def snake_case__		(							self     :	Union[str, Any] ,				lowerCAmelCase__     :	Optional[Any] ,				lowerCAmelCase__     :	Dict ,				lowerCAmelCase__     :	List[str] ,				lowerCAmelCase__     :	List[Any]  )					->  Union[str, Any]:

            '''simple docstring'''




            _UpperCamelCase       					= DataaVecVisionModel(config=lowerCAmelCase__  )
            model.to(lowerCAmelCase__  )
            model.eval()
            _UpperCamelCase       					= model(lowerCAmelCase__  )
            # expected sequence length = num_patches + 1 (we add 1 for the [CLS] token)
            _UpperCamelCase       					= (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     :	List[Any] ,				lowerCAmelCase__     :	List[Any] ,				lowerCAmelCase__     :	Dict ,				lowerCAmelCase__     :	Optional[Any] ,				lowerCAmelCase__     :	Union[str, Any]  )					->  str:

            '''simple docstring'''




            _UpperCamelCase       					= self.type_sequence_label_size
            _UpperCamelCase       					= DataaVecVisionForImageClassification(lowerCAmelCase__  )
            model.to(lowerCAmelCase__  )
            model.eval()
            _UpperCamelCase       					= model(lowerCAmelCase__ ,				labels=lowerCAmelCase__  )
            self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.type_sequence_label_size)  )





       def snake_case__		(							self     :	Dict ,				lowerCAmelCase__     :	List[Any] ,				lowerCAmelCase__     :	Dict ,				lowerCAmelCase__     :	List[str] ,				lowerCAmelCase__     :	Tuple  )					->  Dict:

            '''simple docstring'''




            _UpperCamelCase       					= self.num_labels
            _UpperCamelCase       					= DataaVecVisionForSemanticSegmentation(lowerCAmelCase__  )
            model.to(lowerCAmelCase__  )
            model.eval()
            _UpperCamelCase       					= model(lowerCAmelCase__  )
            self.parent.assertEqual(
                result.logits.shape ,				(self.batch_size, self.num_labels, self.image_size * 2, self.image_size * 2)  )
            _UpperCamelCase       					= 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 snake_case__		(							self     :	Any  )					->  Tuple:

            '''simple docstring'''




            _UpperCamelCase       					= self.prepare_config_and_inputs()
            _UpperCamelCase					,       _UpperCamelCase					,       _UpperCamelCase					,       _UpperCamelCase       					= config_and_inputs
            _UpperCamelCase       					= {'''pixel_values''': pixel_values}
            return config, inputs_dict

@require_torch
class        __lowerCAmelCase  (					__magic_name__		,		__magic_name__		,		unittest.TestCase				):






       """simple docstring"""
       _snake_case			:  Dict		       =					(
           (DataaVecVisionModel, DataaVecVisionForImageClassification, DataaVecVisionForSemanticSegmentation)
           if is_torch_available()
           else ()
       )
       _snake_case			:  Any		       =					(
           {
               'feature-extraction': DataaVecVisionModel,
               'image-classification': DataaVecVisionForImageClassification,
               'image-segmentation': DataaVecVisionForSemanticSegmentation,
           }
           if is_torch_available()
           else {}
       )

       _snake_case			:  Union[str, Any]		       =					False
       _snake_case			:  List[str]		       =					False
       _snake_case			:  Optional[Any]		       =					False





       def snake_case__		(							self     :	str  )					->  int:

            '''simple docstring'''




            _UpperCamelCase       					= DataaVecVisionModelTester(self  )
            _UpperCamelCase       					= ConfigTester(
                self ,				config_class=lowerCAmelCase__ ,				has_text_modality=lowerCAmelCase__ ,				hidden_size=37  )





       def snake_case__		(							self     :	Union[str, Any]  )					->  int:

            '''simple docstring'''




            self.config_tester.run_common_tests()





       def snake_case__		(							self     :	int  )					->  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 snake_case__		(							self     :	Any  )					->  Optional[Any]:

            '''simple docstring'''




            pass





       def snake_case__		(							self     :	Any  )					->  Optional[int]:

            '''simple docstring'''




            _UpperCamelCase					,       _UpperCamelCase       					= self.model_tester.prepare_config_and_inputs_for_common()

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





       def snake_case__		(							self     :	Any  )					->  Tuple:

            '''simple docstring'''




            _UpperCamelCase					,       _UpperCamelCase       					= self.model_tester.prepare_config_and_inputs_for_common()

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

                 _UpperCamelCase       					= ['''pixel_values''']
                 self.assertListEqual(arg_names[:1] ,				lowerCAmelCase__  )





       def snake_case__		(							self     :	Optional[Any]  )					->  str:

            '''simple docstring'''




            _UpperCamelCase       					= self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_model(*lowerCAmelCase__  )





       def snake_case__		(							self     :	Optional[Any]  )					->  List[str]:

            '''simple docstring'''




            _UpperCamelCase       					= self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_segmentation(*lowerCAmelCase__  )





       def snake_case__		(							self     :	int  )					->  Dict:

            '''simple docstring'''




            if not self.model_tester.is_training:
                 return

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

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

                 _UpperCamelCase       					= model_class(lowerCAmelCase__  )
                 model.to(lowerCAmelCase__  )
                 model.train()
                 _UpperCamelCase       					= self._prepare_for_class(lowerCAmelCase__ ,				lowerCAmelCase__ ,				return_labels=lowerCAmelCase__  )
                 _UpperCamelCase       					= model(**lowerCAmelCase__  ).loss
                 loss.backward()





       def snake_case__		(							self     :	List[Any]  )					->  Optional[Any]:

            '''simple docstring'''




            _UpperCamelCase					,       _UpperCamelCase       					= self.model_tester.prepare_config_and_inputs_for_common()
            if not self.model_tester.is_training:
                 return

            _UpperCamelCase       					= False
            _UpperCamelCase       					= 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       					= inputs_dict['''pixel_values'''].shape
                      _UpperCamelCase       					= torch.zeros(
                          [self.model_tester.batch_size, height, width] ,				device=lowerCAmelCase__  ).long()
                 _UpperCamelCase       					= model_class(lowerCAmelCase__  )
                 model.gradient_checkpointing_enable()
                 model.to(lowerCAmelCase__  )
                 model.train()
                 _UpperCamelCase       					= self._prepare_for_class(lowerCAmelCase__ ,				lowerCAmelCase__ ,				return_labels=lowerCAmelCase__  )
                 _UpperCamelCase       					= model(**lowerCAmelCase__  ).loss
                 loss.backward()





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

            '''simple docstring'''




            _UpperCamelCase					,       _UpperCamelCase       					= self.model_tester.prepare_config_and_inputs_for_common()

            _UpperCamelCase       					= _config_zero_init(lowerCAmelCase__  )
            for model_class in self.all_model_classes:
                 _UpperCamelCase       					= 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 snake_case__		(							self     :	Any ,				lowerCAmelCase__     :	List[Any] ,				lowerCAmelCase__     :	Optional[int] ,				lowerCAmelCase__     :	Dict ,				lowerCAmelCase__     :	Union[str, Any]=2e-4 ,				lowerCAmelCase__     :	List[str]="outputs" ,				lowerCAmelCase__     :	int=None  )					->  Any:

            '''simple docstring'''




            super().check_pt_tf_outputs(lowerCAmelCase__ ,				lowerCAmelCase__ ,				lowerCAmelCase__ ,				lowerCAmelCase__ ,				lowerCAmelCase__ ,				lowerCAmelCase__  )





       def snake_case__		(							self     :	List[str]  )					->  List[str]:

            '''simple docstring'''




            _UpperCamelCase       					= self.model_tester.prepare_config_and_inputs()
            self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__  )







       @slow
       def snake_case__		(							self     :	Optional[int]  )					->  Dict:

            '''simple docstring'''




            for model_name in DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                 _UpperCamelCase       					= DataaVecVisionModel.from_pretrained(lowerCAmelCase__  )
                 self.assertIsNotNone(lowerCAmelCase__  )







def       a__       (       )	->	Dict:





     """simple docstring"""

     _UpperCamelCase       					= Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''   )
     return image




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






       """simple docstring"""





       @cached_property
       def snake_case__		(							self     :	str  )					->  Optional[int]:

            '''simple docstring'''




            return (
                BeitImageProcessor.from_pretrained('''facebook/data2vec-vision-base-ft1k'''  ) if is_vision_available() else None
            )







       @slow
       def snake_case__		(							self     :	Union[str, Any]  )					->  Dict:

            '''simple docstring'''




            _UpperCamelCase       					= DataaVecVisionForImageClassification.from_pretrained('''facebook/data2vec-vision-base-ft1k'''  ).to(
                lowerCAmelCase__  )

            _UpperCamelCase       					= self.default_image_processor
            _UpperCamelCase       					= prepare_img()
            _UpperCamelCase       					= image_processor(images=lowerCAmelCase__ ,				return_tensors='''pt'''  ).to(lowerCAmelCase__  )

            # forward pass
            with torch.no_grad():
                 _UpperCamelCase       					= model(**lowerCAmelCase__  )
            _UpperCamelCase       					= outputs.logits

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

            _UpperCamelCase       					= torch.tensor([0.3277, -0.1395, 0.0911]  ).to(lowerCAmelCase__  )

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

            _UpperCamelCase       					= [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 typing import TYPE_CHECKING

from ....utils import OptionalDependencyNotAvailable, _LazyModule, is_tokenizers_available, is_torch_available


lowercase__		:    Union[str, Any] =       {
    'configuration_retribert': ['RETRIBERT_PRETRAINED_CONFIG_ARCHIVE_MAP', 'RetriBertConfig'],
    'tokenization_retribert': ['RetriBertTokenizer'],
}

try:
   if not is_tokenizers_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   lowercase__		:    Dict =       ['RetriBertTokenizerFast']

try:
   if not is_torch_available():
      raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
   pass
else:
   lowercase__		:    Tuple =       [
       'RETRIBERT_PRETRAINED_MODEL_ARCHIVE_LIST',
       'RetriBertModel',
       'RetriBertPreTrainedModel',
   ]


if TYPE_CHECKING:
   from .configuration_retribert import RETRIBERT_PRETRAINED_CONFIG_ARCHIVE_MAP, RetriBertConfig
   from .tokenization_retribert import RetriBertTokenizer

   try:
      if not is_tokenizers_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .tokenization_retribert_fast import RetriBertTokenizerFast

   try:
      if not is_torch_available():
         raise OptionalDependencyNotAvailable()
   except OptionalDependencyNotAvailable:
      pass
   else:
      from .modeling_retribert import (
          RETRIBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
          RetriBertModel,
          RetriBertPreTrainedModel,
      )

else:
   import sys

   lowercase__		:    Optional[Any] =       _LazyModule(__name__, globals()['__file__'], _import_structure, module_spec=__spec__)



