

from typing import TYPE_CHECKING

from ...utils import (
    OptionalDependencyNotAvailable,
    _LazyModule,
    is_flax_available,
    is_tf_available,
    is_torch_available,
)


lowerCAmelCase  : Optional[Any]      =	{
    'configuration_vision_text_dual_encoder': ['VisionTextDualEncoderConfig'],
    'processing_vision_text_dual_encoder': ['VisionTextDualEncoderProcessor'],
}


try:
    if not is_torch_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    lowerCAmelCase  : List[Any]      =	['VisionTextDualEncoderModel']


try:
    if not is_flax_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    lowerCAmelCase  : Any      =	['FlaxVisionTextDualEncoderModel']

try:
    if not is_tf_available():
        raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
    pass
else:
    lowerCAmelCase  : List[str]      =	['TFVisionTextDualEncoderModel']


if TYPE_CHECKING:
    from .configuration_vision_text_dual_encoder import VisionTextDualEncoderConfig
    from .processing_vision_text_dual_encoder import VisionTextDualEncoderProcessor

    try:
        if not is_torch_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_vision_text_dual_encoder import VisionTextDualEncoderModel

    try:
        if not is_flax_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_flax_vision_text_dual_encoder import FlaxVisionTextDualEncoderModel

    try:
        if not is_tf_available():
            raise OptionalDependencyNotAvailable()
    except OptionalDependencyNotAvailable:
        pass
    else:
        from .modeling_tf_vision_text_dual_encoder import TFVisionTextDualEncoderModel


else:
    import sys

    lowerCAmelCase  : int      =	_LazyModule(__name__, globals()['__file__'], _import_structure)










'''simple docstring'''


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 							__magic_name__	:

     """simple docstring"""






     def __init__(   self			,     lowerCamelCase			,     lowerCamelCase=13			,     lowerCamelCase=64			,     lowerCamelCase=2			,     lowerCamelCase=3			,     lowerCamelCase=True			,     lowerCamelCase=True			,     lowerCamelCase=32			,     lowerCamelCase=5			,     lowerCamelCase=4			,     lowerCamelCase=37			,     lowerCamelCase="gelu"			,     lowerCamelCase=0.1			,     lowerCamelCase=0.1			,     lowerCamelCase=10			,     lowerCamelCase=0.02			,     lowerCamelCase=[1, 16, 4, 4]			,     lowerCamelCase=None			,     ):


          '''simple docstring'''





          __A	:       Any      =							parent
          __A	:       Union[str, Any]      =							batch_size
          __A	:       Any      =							image_size
          __A	:       Dict      =							patch_size
          __A	:       Dict      =							num_channels
          __A	:       Dict      =							is_training
          __A	:       Optional[Any]      =							use_labels
          __A	:       Any      =							hidden_size
          __A	:       Optional[Any]      =							num_hidden_layers
          __A	:       Optional[int]      =							num_attention_heads
          __A	:       str      =							intermediate_size
          __A	:       int      =							hidden_act
          __A	:       Any      =							hidden_dropout_prob
          __A	:       int      =							attention_probs_dropout_prob
          __A	:       Any      =							type_sequence_label_size
          __A	:       Union[str, Any]      =							initializer_range
          __A	:       Dict      =							scope
          __A	:       Union[str, Any]      =							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	:       int      =							(self.image_size // 32) ** 2
          __A	:       Union[str, Any]      =							num_patches + 1


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       str      =							floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

          __A	:       Any      =							None
          if self.use_labels:
               __A	:       Optional[Any]      =							ids_tensor([self.batch_size]			,     self.type_sequence_label_size		)

          __A	:       Any      =							self.get_config()

          return config, pixel_values, labels


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       Union[str, Any]      =							{
              "global_padding": "same",
              "layer_type": "bottleneck",
              "depths": [3, 4, 9],
              "out_features": ["stage1", "stage2", "stage3"],
              "embedding_dynamic_padding": True,
              "hidden_sizes": [4, 8, 16, 32],
              "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=lowerCamelCase			,     initializer_range=self.initializer_range			,     backbone_featmap_shape=self.backbone_featmap_shape			,     backbone_config=lowerCamelCase			,     )


     def lowerCAmelCase__  (   self			,     lowerCamelCase			,     lowerCamelCase			,     lowerCamelCase		):


          '''simple docstring'''





          __A	:       int      =							ViTHybridModel(config=lowerCamelCase		)
          model.to(lowerCamelCase		)
          model.eval()
          __A	:       Optional[Any]      =							model(lowerCamelCase		)
          self.parent.assertEqual(result.last_hidden_state.shape			,     (self.batch_size, self.seq_length, self.hidden_size)		)


     def lowerCAmelCase__  (   self			,     lowerCamelCase			,     lowerCamelCase			,     lowerCamelCase		):


          '''simple docstring'''





          __A	:       Any      =							self.type_sequence_label_size
          __A	:       int      =							ViTHybridForImageClassification(lowerCamelCase		)
          model.to(lowerCamelCase		)
          model.eval()
          __A	:       Any      =							model(lowerCamelCase			,     labels=lowerCamelCase		)
          self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.type_sequence_label_size)		)


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       Dict      =							self.prepare_config_and_inputs()
          __A  ,__A  ,__A	:       Optional[int]      =							config_and_inputs
          __A	:       Dict      =							{"pixel_values": pixel_values}
          return config, inputs_dict







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

     """simple docstring"""






     lowerCamelCase__       						=				(ViTHybridModel, ViTHybridForImageClassification) if is_torch_available() else ()
     lowerCamelCase__       						=				(
         {'feature-extraction': ViTHybridModel, 'image-classification': ViTHybridForImageClassification}
         if is_torch_available()
         else {}
     )
     lowerCamelCase__       						=				False
     lowerCamelCase__       						=				False
     lowerCamelCase__       						=				False


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       str      =							ViTHybridModelTester(self		)
          __A	:       Optional[Any]      =							ConfigTester(self			,     config_class=lowerCamelCase			,     has_text_modality=lowerCamelCase			,     hidden_size=37		)


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          self.config_tester.run_common_tests()


     @unittest.skip(reason="ViT does not use inputs_embeds"		)
     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          pass


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __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(lowerCamelCase		)
               self.assertIsInstance(model.get_input_embeddings()			,     (nn.Module)		)
               __A	:       int      =							model.get_output_embeddings()
               self.assertTrue(x is None or isinstance(lowerCamelCase			,     nn.Linear		)		)


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A  ,__A	:       Any      =							self.model_tester.prepare_config_and_inputs_for_common()

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

               __A	:       Dict      =							["pixel_values"]
               self.assertListEqual(arg_names[:1]			,     lowerCamelCase		)


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       int      =							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_model(*lowerCamelCase		)


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       Optional[int]      =							self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_for_image_classification(*lowerCamelCase		)


     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A  ,__A	:       Any      =							self.model_tester.prepare_config_and_inputs_for_common()

          __A	:       Dict      =							_config_zero_init(lowerCamelCase		)
          for model_class in self.all_model_classes:
               __A	:       List[str]      =							model_class(config=lowerCamelCase		)
               # Skip the check for the backbone
               for name, module in model.named_modules():
                    if module.__class__.__name__ == "ViTHybridPatchEmbeddings":
                         __A	:       int      =							[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		):


          '''simple docstring'''





          for model_name in VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               __A	:       Tuple      =							ViTHybridModel.from_pretrained(lowerCamelCase		)
               self.assertIsNotNone(lowerCamelCase		)


def 		_lowercase ():




     '''simple docstring'''





     __A	:       Optional[Any]      =							Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"							)
     return image







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

     """simple docstring"""






     @cached_property
     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          return (
              ViTHybridImageProcessor.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)
              if is_vision_available()
              else None
          )


     @slow
     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       str      =							ViTHybridForImageClassification.from_pretrained(VIT_HYBRID_PRETRAINED_MODEL_ARCHIVE_LIST[0]		).to(
              lowerCamelCase		)

          __A	:       str      =							self.default_image_processor
          __A	:       Union[str, Any]      =							prepare_img()
          __A	:       List[str]      =							image_processor(images=lowerCamelCase			,     return_tensors="pt"		).to(lowerCamelCase		)

          # forward pass
          with torch.no_grad():
               __A	:       Any      =							model(**lowerCamelCase		)

          # verify the logits
          __A	:       List[str]      =							torch.Size((1, 1000)		)
          self.assertEqual(outputs.logits.shape			,     lowerCamelCase		)

          __A	:       Optional[int]      =							torch.tensor([-1.9090, -0.4993, -0.2389]		).to(lowerCamelCase		)

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


     @slow
     @require_accelerate
     def lowerCAmelCase__  (   self		):


          '''simple docstring'''





          __A	:       List[Any]      =							ViTHybridImageProcessor.from_pretrained("google/vit-hybrid-base-bit-384"		)
          __A	:       Optional[Any]      =							ViTHybridForImageClassification.from_pretrained("google/vit-hybrid-base-bit-384"			,     device_map="auto"		)

          __A	:       Union[str, Any]      =							prepare_img()

          __A	:       Tuple      =							image_processor(images=lowerCamelCase			,     return_tensors="pt"		)
          __A	:       Optional[Any]      =							model(**lowerCamelCase		)
          __A	:       List[Any]      =							outputs.logits
          # model predicts one of the 1000 ImageNet classes
          __A	:       Tuple      =							logits.argmax(-1		).item()

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

