
import inspect
import unittest

from transformers import ViTHybridConfig
from transformers.testing_utils import require_accelerate, require_torch, 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 ViTHybridForImageClassification, ViTHybridImageProcessor, ViTHybridModel
      from transformers.models.vit_hybrid.modeling_vit_hybrid import VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST


if is_vision_available():
      from PIL import Image



class 		UpperCamelCase__  :
   def __init__(self			: Optional[Any] ,    snake_case_			: Union[str, Any] ,    snake_case_			: Any=1_3 ,    snake_case_			: Optional[int]=6_4 ,    snake_case_			: Dict=2 ,    snake_case_			: Tuple=3 ,    snake_case_			: Tuple=True ,    snake_case_			: Tuple=True ,    snake_case_			: int=3_2 ,    snake_case_			: str=5 ,    snake_case_			: Optional[Any]=4 ,    snake_case_			: List[str]=3_7 ,    snake_case_			: Union[str, Any]="gelu" ,    snake_case_			: Optional[int]=0.1 ,    snake_case_			: Optional[Any]=0.1 ,    snake_case_			: List[str]=1_0 ,    snake_case_			: int=0.02 ,    snake_case_			: int=[1, 1_6, 4, 4] ,    snake_case_			: List[Any]=None ,    ):
    __a			:  Union[str, Any]		    =  parent
    __a			:  Tuple		    =  batch_size
    __a			:  Dict		    =  image_size
    __a			:  Dict		    =  patch_size
    __a			:  str		    =  num_channels
    __a			:  List[str]		    =  is_training
    __a			:  str		    =  use_labels
    __a			:  int		    =  hidden_size
    __a			:  int		    =  num_hidden_layers
    __a			:  Tuple		    =  num_attention_heads
    __a			:  str		    =  intermediate_size
    __a			:  Optional[Any]		    =  hidden_act
    __a			:  Tuple		    =  hidden_dropout_prob
    __a			:  str		    =  attention_probs_dropout_prob
    __a			:  str		    =  type_sequence_label_size
    __a			:  Tuple		    =  initializer_range
    __a			:  Union[str, Any]		    =  scope
    __a			:  Optional[int]		    =  backbone_featmap_shape

    # in ViT hybrid, the seq length equals the number of patches + 1 (we add 1 for the [CLS] token)
    # the number of patches is based on the feature map of the backbone, which by default uses an output stride
    # of 32, which means that the feature map has a spatial resolution of 1/32 of the input image size
    __a			:  Optional[Any]		    =  (self.image_size // 3_2) ** 2
    __a			:  Union[str, Any]		    =  num_patches + 1
   def 				lowerCAmelCase      (self			: str       ):
    __a			:  Optional[int]		    =  floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]       )

    __a			:  Tuple		    =  None
    if self.use_labels:
     __a			:  Optional[int]		    =  ids_tensor([self.batch_size] ,    self.type_sequence_label_size       )

    __a			:  Tuple		    =  self.get_config()

    return config, pixel_values, labels
   def 				lowerCAmelCase      (self			: str       ):
    __a			:  str		    =  {
        '''global_padding''': '''same''',
        '''layer_type''': '''bottleneck''',
        '''depths''': [3, 4, 9],
        '''out_features''': ['''stage1''', '''stage2''', '''stage3'''],
        '''embedding_dynamic_padding''': True,
        '''hidden_sizes''': [4, 8, 1_6, 3_2],
        '''num_groups''': 2,
    }

    return ViTHybridConfig(
        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=__lowercase ,    initializer_range=self.initializer_range ,    backbone_featmap_shape=self.backbone_featmap_shape ,    backbone_config=__lowercase ,    )
   def 				lowerCAmelCase      (self			: Dict ,    snake_case_			: Union[str, Any] ,    snake_case_			: List[Any] ,    snake_case_			: str       ):
    __a			:  Dict		    =  ViTHybridModel(config=__lowercase       )
    model.to(__lowercase       )
    model.eval()
    __a			:  Dict		    =  model(__lowercase       )
    self.parent.assertEqual(result.last_hidden_state.shape ,    (self.batch_size, self.seq_length, self.hidden_size)       )
   def 				lowerCAmelCase      (self			: Optional[int] ,    snake_case_			: List[str] ,    snake_case_			: List[str] ,    snake_case_			: Union[str, Any]       ):
    __a			:  Optional[int]		    =  self.type_sequence_label_size
    __a			:  Tuple		    =  ViTHybridForImageClassification(__lowercase       )
    model.to(__lowercase       )
    model.eval()
    __a			:  Optional[int]		    =  model(__lowercase ,    labels=__lowercase       )
    self.parent.assertEqual(result.logits.shape ,    (self.batch_size, self.type_sequence_label_size)       )







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





@require_torch
class 		UpperCamelCase__  (	__A   ,__A   ,unittest.TestCase   ):
   _SCREAMING_SNAKE_CASE				:							Optional[int]     	=				(ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else ()
   _SCREAMING_SNAKE_CASE				:							Optional[int]     	=				(
       {'feature-extraction': ViTHybridModel, 'image-classification': ViTHybridForImageClassification}
       if is_torch_available()
       else {}
   )
   _SCREAMING_SNAKE_CASE				:							Optional[Any]     	=				False
   _SCREAMING_SNAKE_CASE				:							str     	=				False
   _SCREAMING_SNAKE_CASE				:							Tuple     	=				False
   def 				lowerCAmelCase      (self			: str       ):
    __a			:  Dict		    =  ViTHybridModelTester(self       )
    __a			:  List[str]		    =  ConfigTester(self ,    config_class=__lowercase ,    has_text_modality=__lowercase ,    hidden_size=3_7       )
   def 				lowerCAmelCase      (self			: Tuple       ):
    self.config_tester.run_common_tests()
   @unittest.skip(reason='''ViT does not use inputs_embeds'''       )
   def 				lowerCAmelCase      (self			: str       ):
    pass
   def 				lowerCAmelCase      (self			: Union[str, Any]       ):
    __a    ,	__a			:  int		    =  self.model_tester.prepare_config_and_inputs_for_common()

    for model_class in self.all_model_classes:
     __a			:  List[Any]		    =  model_class(__lowercase       )
     self.assertIsInstance(model.get_input_embeddings() ,    (nn.Module)       )
     __a			:  int		    =  model.get_output_embeddings()
     self.assertTrue(x is None or isinstance(__lowercase ,    nn.Linear       )       )
   def 				lowerCAmelCase      (self			: int       ):
    __a    ,	__a			:  Dict		    =  self.model_tester.prepare_config_and_inputs_for_common()

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

     __a			:  int		    =  ['''pixel_values''']
     self.assertListEqual(arg_names[:1] ,    __lowercase       )
   def 				lowerCAmelCase      (self			: str       ):
    __a			:  int		    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_model(*__lowercase       )
   def 				lowerCAmelCase      (self			: List[Any]       ):
    __a			:  Optional[int]		    =  self.model_tester.prepare_config_and_inputs()
    self.model_tester.create_and_check_for_image_classification(*__lowercase       )
   def 				lowerCAmelCase      (self			: Any       ):
    __a    ,	__a			:  List[str]		    =  self.model_tester.prepare_config_and_inputs_for_common()

    __a			:  Dict		    =  _config_zero_init(__lowercase       )
    for model_class in self.all_model_classes:
     __a			:  Union[str, Any]		    =  model_class(config=__lowercase       )
     # Skip the check for the backbone
     for name, module in model.named_modules():
      if module.__class__.__name__ == "ViTHybridPatchEmbeddings":
       __a			:  Optional[Any]		    =  [f"{name}.{key}" for key in module.state_dict().keys()]
       break

     for name, param in model.named_parameters():
      if param.requires_grad:
       if name in backbone_params:
        continue
       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" ,    )







   @slow
   def 				lowerCAmelCase      (self			: List[Any]       ):
    for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
     __a			:  Dict		    =  ViTHybridModel.from_pretrained(__lowercase       )
     self.assertIsNotNone(__lowercase       )





def        __UpperCamelCase					(    ):
 __a			:  Any		    =  Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''  )
 return image



@require_torch
@require_vision
class 		UpperCamelCase__  (	unittest.TestCase   ):
   @cached_property
   def 				lowerCAmelCase      (self			: List[Any]       ):
    return (
        ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]       )
        if is_vision_available()
        else None
    )
   @slow
   def 				lowerCAmelCase      (self			: Optional[Any]       ):
    __a			:  List[Any]		    =  ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]       ).to(
        __lowercase       )

    __a			:  Tuple		    =  self.default_image_processor
    __a			:  int		    =  prepare_img()
    __a			:  int		    =  image_processor(images=__lowercase ,    return_tensors='''pt'''       ).to(__lowercase       )

    # forward pass
    with torch.no_grad():
     __a			:  List[str]		    =  model(**__lowercase       )

    # verify the logits
    __a			:  Union[str, Any]		    =  torch.Size((1, 1_0_0_0)       )
    self.assertEqual(outputs.logits.shape ,    __lowercase       )

    __a			:  List[Any]		    =  torch.tensor([-1.9090, -0.4993, -0.2389]       ).to(__lowercase       )

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







   @slow
   @require_accelerate
   def 				lowerCAmelCase      (self			: int       ):
    __a			:  str		    =  ViTHybridImageProcessor.from_pretrained('''google/vit-hybrid-base-bit-384'''       )
    __a			:  Dict		    =  ViTHybridForImageClassification.from_pretrained('''google/vit-hybrid-base-bit-384''' ,    device_map='''auto'''       )

    __a			:  Any		    =  prepare_img()

    __a			:  Optional[int]		    =  image_processor(images=__lowercase ,    return_tensors='''pt'''       )
    __a			:  str		    =  model(**__lowercase       )
    __a			:  Union[str, Any]		    =  outputs.logits
    # model predicts one of the 1000 ImageNet classes
    __a			:  Optional[int]		    =  logits.argmax(-1       ).item()

    self.assertTrue(model.config.idalabel[predicted_class_idx] ,    '''tabby, tabby cat'''       )







from typing import TYPE_CHECKING

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


lowercase__          ={
    'configuration_data2vec_audio': ['DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP', 'Data2VecAudioConfig'],
    'configuration_data2vec_text': [
        'DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'Data2VecTextConfig',
        'Data2VecTextOnnxConfig',
    ],
    'configuration_data2vec_vision': [
        'DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP',
        'Data2VecVisionConfig',
        'Data2VecVisionOnnxConfig',
    ],
}

try:
      if not is_torch_available():
            raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
      pass
else:
      lowercase__          =[
          'DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST',
          'Data2VecAudioForAudioFrameClassification',
          'Data2VecAudioForCTC',
          'Data2VecAudioForSequenceClassification',
          'Data2VecAudioForXVector',
          'Data2VecAudioModel',
          'Data2VecAudioPreTrainedModel',
      ]
      lowercase__          =[
          'DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST',
          'Data2VecTextForCausalLM',
          'Data2VecTextForMaskedLM',
          'Data2VecTextForMultipleChoice',
          'Data2VecTextForQuestionAnswering',
          'Data2VecTextForSequenceClassification',
          'Data2VecTextForTokenClassification',
          'Data2VecTextModel',
          'Data2VecTextPreTrainedModel',
      ]
      lowercase__          =[
          'DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST',
          'Data2VecVisionForImageClassification',
          'Data2VecVisionForMaskedImageModeling',
          'Data2VecVisionForSemanticSegmentation',
          'Data2VecVisionModel',
          'Data2VecVisionPreTrainedModel',
      ]

if is_tf_available():
      lowercase__          =[
          'TFData2VecVisionForImageClassification',
          'TFData2VecVisionForSemanticSegmentation',
          'TFData2VecVisionModel',
          'TFData2VecVisionPreTrainedModel',
      ]

if TYPE_CHECKING:
      from .configuration_dataavec_audio import DATA2VEC_AUDIO_PRETRAINED_CONFIG_ARCHIVE_MAP, DataaVecAudioConfig
      from .configuration_dataavec_text import (
          DATA2VEC_TEXT_PRETRAINED_CONFIG_ARCHIVE_MAP,
          DataaVecTextConfig,
          DataaVecTextOnnxConfig,
      )
      from .configuration_dataavec_vision import (
          DATA2VEC_VISION_PRETRAINED_CONFIG_ARCHIVE_MAP,
          DataaVecVisionConfig,
          DataaVecVisionOnnxConfig,
      )

      try:
            if not is_torch_available():
                  raise OptionalDependencyNotAvailable()
      except OptionalDependencyNotAvailable:
            pass
      else:
            from .modeling_dataavec_audio import (
                DATA2VEC_AUDIO_PRETRAINED_MODEL_ARCHIVE_LIST,
                DataaVecAudioForAudioFrameClassification,
                DataaVecAudioForCTC,
                DataaVecAudioForSequenceClassification,
                DataaVecAudioForXVector,
                DataaVecAudioModel,
                DataaVecAudioPreTrainedModel,
            )
            from .modeling_dataavec_text import (
                DATA2VEC_TEXT_PRETRAINED_MODEL_ARCHIVE_LIST,
                DataaVecTextForCausalLM,
                DataaVecTextForMaskedLM,
                DataaVecTextForMultipleChoice,
                DataaVecTextForQuestionAnswering,
                DataaVecTextForSequenceClassification,
                DataaVecTextForTokenClassification,
                DataaVecTextModel,
                DataaVecTextPreTrainedModel,
            )
            from .modeling_dataavec_vision import (
                DATA2VEC_VISION_PRETRAINED_MODEL_ARCHIVE_LIST,
                DataaVecVisionForImageClassification,
                DataaVecVisionForMaskedImageModeling,
                DataaVecVisionForSemanticSegmentation,
                DataaVecVisionModel,
                DataaVecVisionPreTrainedModel,
            )
      if is_tf_available():
            from .modeling_tf_dataavec_vision import (
                TFDataaVecVisionForImageClassification,
                TFDataaVecVisionForSemanticSegmentation,
                TFDataaVecVisionModel,
                TFDataaVecVisionPreTrainedModel,
            )

else:
      import sys

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