

import collections.abc
from typing import Optional, Tuple, Union

import torch
import torch.utils.checkpoint
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss

from ...activations import ACTaFN
from ...modeling_outputs import BaseModelOutputWithNoAttention, ImageClassifierOutputWithNoAttention
from ...modeling_utils import PreTrainedModel
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_poolformer import PoolFormerConfig


lowerCAmelCase  : Union[str, Any]      =	logging.get_logger(__name__)

# General docstring
lowerCAmelCase  : List[str]      =	'PoolFormerConfig'

# Base docstring
lowerCAmelCase  : str      =	'sail/poolformer_s12'
lowerCAmelCase  : List[str]      =	[1, 5_12, 7, 7]

# Image classification docstring
lowerCAmelCase  : List[Any]      =	'sail/poolformer_s12'
lowerCAmelCase  : Union[str, Any]      =	'tabby, tabby cat'

lowerCAmelCase  : Union[str, Any]      =	[
    'sail/poolformer_s12',
    # See all PoolFormer models at https://huggingface.co/models?filter=poolformer
]

def  A_	(				a       , a = 0.0       , a = False	):

      """simple docstring"""



      if drop_prob == 0.0 or not training:
            return input
      SCREAMING_SNAKE_CASE_					:	int     							=  1 - drop_prob
      SCREAMING_SNAKE_CASE_					:	List[str]     							=  (input.shape[0],) + (1,) * (input.ndim - 1)  # work with diff dim tensors, not just 2D ConvNets
      SCREAMING_SNAKE_CASE_					:	List[str]     							=  keep_prob + torch.rand(a       , dtype=input.dtype       , device=input.device	)
      random_tensor.floor_()  # binarize
      SCREAMING_SNAKE_CASE_					:	Optional[int]     							=  input.div(a	) * random_tensor
      return output
class 			_A		(	nn.Module):

  def __init__(					self			,       _SCREAMING_SNAKE_CASE = None       ):





        """simple docstring"""







        super().__init__()
        SCREAMING_SNAKE_CASE_					:	int     							=  drop_prob

  def 			UpperCAmelCase     (					self			,       _SCREAMING_SNAKE_CASE       ):





        """simple docstring"""







        return drop_path(_SCREAMING_SNAKE_CASE			,       self.drop_prob			,       self.training       )



  def 			UpperCAmelCase     (					self       ):





        """simple docstring"""







        return "p={}".format(self.drop_prob       )

class 			_A		(	nn.Module):

  def __init__(					self			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE=None       ):





        """simple docstring"""







        super().__init__()
        SCREAMING_SNAKE_CASE_					:	Optional[Any]     							=  patch_size if isinstance(_SCREAMING_SNAKE_CASE			,       collections.abc.Iterable       ) else (patch_size, patch_size)
        SCREAMING_SNAKE_CASE_					:	Union[str, Any]     							=  stride if isinstance(_SCREAMING_SNAKE_CASE			,       collections.abc.Iterable       ) else (stride, stride)
        SCREAMING_SNAKE_CASE_					:	Union[str, Any]     							=  padding if isinstance(_SCREAMING_SNAKE_CASE			,       collections.abc.Iterable       ) else (padding, padding)

        SCREAMING_SNAKE_CASE_					:	Optional[Any]     							=  nn.Convad(_SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE			,       kernel_size=_SCREAMING_SNAKE_CASE			,       stride=_SCREAMING_SNAKE_CASE			,       padding=_SCREAMING_SNAKE_CASE       )
        SCREAMING_SNAKE_CASE_					:	Optional[int]     							=  norm_layer(_SCREAMING_SNAKE_CASE       ) if norm_layer else nn.Identity()



  def 			UpperCAmelCase     (					self			,       _SCREAMING_SNAKE_CASE       ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_					:	str     							=  self.projection(_SCREAMING_SNAKE_CASE       )
        SCREAMING_SNAKE_CASE_					:	Any     							=  self.norm(_SCREAMING_SNAKE_CASE       )
        return embeddings

class 			_A		(	nn.GroupNorm):

  def __init__(					self			,       _SCREAMING_SNAKE_CASE			,       **_SCREAMING_SNAKE_CASE       ):





        """simple docstring"""







        super().__init__(1			,       _SCREAMING_SNAKE_CASE			,       **_SCREAMING_SNAKE_CASE       )

class 			_A		(	nn.Module):

  def __init__(					self			,       _SCREAMING_SNAKE_CASE       ):





        """simple docstring"""







        super().__init__()
        SCREAMING_SNAKE_CASE_					:	Dict     							=  nn.AvgPoolad(_SCREAMING_SNAKE_CASE			,       stride=1			,       padding=pool_size // 2			,       count_include_pad=_SCREAMING_SNAKE_CASE       )



  def 			UpperCAmelCase     (					self			,       _SCREAMING_SNAKE_CASE       ):





        """simple docstring"""







        return self.pool(_SCREAMING_SNAKE_CASE       ) - hidden_states

class 			_A		(	nn.Module):

  def __init__(					self			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE       ):





        """simple docstring"""







        super().__init__()
        SCREAMING_SNAKE_CASE_					:	int     							=  nn.Convad(_SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE			,       1       )
        SCREAMING_SNAKE_CASE_					:	Union[str, Any]     							=  nn.Convad(_SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE			,       1       )
        SCREAMING_SNAKE_CASE_					:	str     							=  PoolFormerDropPath(_SCREAMING_SNAKE_CASE       )
        if isinstance(config.hidden_act			,       _SCREAMING_SNAKE_CASE       ):
              SCREAMING_SNAKE_CASE_					:	List[str]     							=  ACTaFN[config.hidden_act]
        else:
              SCREAMING_SNAKE_CASE_					:	List[Any]     							=  config.hidden_act



  def 			UpperCAmelCase     (					self			,       _SCREAMING_SNAKE_CASE       ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_					:	Union[str, Any]     							=  self.conva(_SCREAMING_SNAKE_CASE       )
        SCREAMING_SNAKE_CASE_					:	Optional[Any]     							=  self.act_fn(_SCREAMING_SNAKE_CASE       )
        SCREAMING_SNAKE_CASE_					:	Optional[Any]     							=  self.drop(_SCREAMING_SNAKE_CASE       )
        SCREAMING_SNAKE_CASE_					:	List[Any]     							=  self.conva(_SCREAMING_SNAKE_CASE       )
        SCREAMING_SNAKE_CASE_					:	Optional[Any]     							=  self.drop(_SCREAMING_SNAKE_CASE       )

        return hidden_states

class 			_A		(	nn.Module):

  def __init__(					self			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE       ):





        """simple docstring"""







        super().__init__()
        SCREAMING_SNAKE_CASE_					:	Optional[Any]     							=  PoolFormerPooling(_SCREAMING_SNAKE_CASE       )
        SCREAMING_SNAKE_CASE_					:	List[Any]     							=  PoolFormerOutput(_SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE       )
        SCREAMING_SNAKE_CASE_					:	int     							=  PoolFormerGroupNorm(_SCREAMING_SNAKE_CASE       )
        SCREAMING_SNAKE_CASE_					:	List[str]     							=  PoolFormerGroupNorm(_SCREAMING_SNAKE_CASE       )

        # Useful for training neural nets
        SCREAMING_SNAKE_CASE_					:	Union[str, Any]     							=  PoolFormerDropPath(_SCREAMING_SNAKE_CASE       ) if drop_path > 0.0 else nn.Identity()
        SCREAMING_SNAKE_CASE_					:	Optional[Any]     							=  config.use_layer_scale
        if config.use_layer_scale:
              SCREAMING_SNAKE_CASE_					:	List[str]     							=  nn.Parameter(
                  config.layer_scale_init_value * torch.ones((_SCREAMING_SNAKE_CASE)       )			,       requires_grad=_SCREAMING_SNAKE_CASE       )
              SCREAMING_SNAKE_CASE_					:	Tuple     							=  nn.Parameter(
                  config.layer_scale_init_value * torch.ones((_SCREAMING_SNAKE_CASE)       )			,       requires_grad=_SCREAMING_SNAKE_CASE       )



  def 			UpperCAmelCase     (					self			,       _SCREAMING_SNAKE_CASE       ):





        """simple docstring"""







        if self.use_layer_scale:
              SCREAMING_SNAKE_CASE_					:	Union[str, Any]     							=  self.pooling(self.before_norm(_SCREAMING_SNAKE_CASE       )       )
              SCREAMING_SNAKE_CASE_					:	Tuple     							=  self.layer_scale_a.unsqueeze(-1       ).unsqueeze(-1       ) * pooling_output
              # First residual connection
              SCREAMING_SNAKE_CASE_					:	Dict     							=  hidden_states + self.drop_path(_SCREAMING_SNAKE_CASE       )
              SCREAMING_SNAKE_CASE_					:	Dict     							=  ()

              SCREAMING_SNAKE_CASE_					:	int     							=  self.output(self.after_norm(_SCREAMING_SNAKE_CASE       )       )
              SCREAMING_SNAKE_CASE_					:	List[Any]     							=  self.layer_scale_a.unsqueeze(-1       ).unsqueeze(-1       ) * layer_output
              # Second residual connection
              SCREAMING_SNAKE_CASE_					:	Dict     							=  hidden_states + self.drop_path(_SCREAMING_SNAKE_CASE       )

              SCREAMING_SNAKE_CASE_					:	Union[str, Any]     							=  (output,) + outputs
              return outputs

        else:
              SCREAMING_SNAKE_CASE_					:	Any     							=  self.drop_path(self.pooling(self.before_norm(_SCREAMING_SNAKE_CASE       )       )       )
              # First residual connection
              SCREAMING_SNAKE_CASE_					:	List[str]     							=  pooling_output + hidden_states
              SCREAMING_SNAKE_CASE_					:	Tuple     							=  ()

              # Second residual connection inside the PoolFormerOutput block
              SCREAMING_SNAKE_CASE_					:	int     							=  self.drop_path(self.output(self.after_norm(_SCREAMING_SNAKE_CASE       )       )       )
              SCREAMING_SNAKE_CASE_					:	int     							=  hidden_states + layer_output

              SCREAMING_SNAKE_CASE_					:	str     							=  (output,) + outputs
              return outputs

class 			_A		(	nn.Module):

  def __init__(					self			,       _SCREAMING_SNAKE_CASE       ):





        """simple docstring"""







        super().__init__()
        SCREAMING_SNAKE_CASE_					:	Dict     							=  config
        # stochastic depth decay rule
        SCREAMING_SNAKE_CASE_					:	Optional[int]     							=  [x.item() for x in torch.linspace(0			,       config.drop_path_rate			,       sum(config.depths       )       )]

        # patch embeddings
        SCREAMING_SNAKE_CASE_					:	Dict     							=  []
        for i in range(config.num_encoder_blocks       ):
              embeddings.append(
                  PoolFormerEmbeddings(
                      patch_size=config.patch_sizes[i]			,       stride=config.strides[i]			,       padding=config.padding[i]			,       num_channels=config.num_channels if i == 0 else config.hidden_sizes[i - 1]			,       hidden_size=config.hidden_sizes[i]			,       )       )
        SCREAMING_SNAKE_CASE_					:	str     							=  nn.ModuleList(_SCREAMING_SNAKE_CASE       )

        # Transformer blocks
        SCREAMING_SNAKE_CASE_					:	str     							=  []
        SCREAMING_SNAKE_CASE_					:	Any     							=  0
        for i in range(config.num_encoder_blocks       ):
              # each block consists of layers
              SCREAMING_SNAKE_CASE_					:	Union[str, Any]     							=  []
              if i != 0:
                    cur += config.depths[i - 1]
              for j in range(config.depths[i]       ):
                    layers.append(
                        PoolFormerLayer(
                            _SCREAMING_SNAKE_CASE			,       num_channels=config.hidden_sizes[i]			,       pool_size=config.pool_size			,       hidden_size=config.hidden_sizes[i]			,       intermediate_size=int(config.hidden_sizes[i] * config.mlp_ratio       )			,       drop_path=dpr[cur + j]			,       )       )
              blocks.append(nn.ModuleList(_SCREAMING_SNAKE_CASE       )       )

        SCREAMING_SNAKE_CASE_					:	List[str]     							=  nn.ModuleList(_SCREAMING_SNAKE_CASE       )



  def 			UpperCAmelCase     (					self			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE=False			,       _SCREAMING_SNAKE_CASE=True       ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_					:	str     							=  () if output_hidden_states else None

        SCREAMING_SNAKE_CASE_					:	Optional[int]     							=  pixel_values
        for idx, layers in enumerate(zip(self.patch_embeddings			,       self.block       )       ):
              SCREAMING_SNAKE_CASE_					:	int     							=  layers
              # Get patch embeddings from hidden_states
              SCREAMING_SNAKE_CASE_					:	str     							=  embedding_layer(_SCREAMING_SNAKE_CASE       )
              # Send the embeddings through the blocks
              for _, blk in enumerate(_SCREAMING_SNAKE_CASE       ):
                    SCREAMING_SNAKE_CASE_					:	Optional[int]     							=  blk(_SCREAMING_SNAKE_CASE       )
                    SCREAMING_SNAKE_CASE_					:	Tuple     							=  layer_outputs[0]

              if output_hidden_states:
                    SCREAMING_SNAKE_CASE_					:	Tuple     							=  all_hidden_states + (hidden_states,)

        if not return_dict:
              return tuple(v for v in [hidden_states, all_hidden_states] if v is not None       )

        return BaseModelOutputWithNoAttention(last_hidden_state=_SCREAMING_SNAKE_CASE			,       hidden_states=_SCREAMING_SNAKE_CASE       )

class 			_A		(	__magic_name__):
  SCREAMING_SNAKE_CASE     :   List[Any]							=	PoolFormerConfig
  SCREAMING_SNAKE_CASE     :   Tuple							=	'''poolformer'''
  SCREAMING_SNAKE_CASE     :   List[str]							=	'''pixel_values'''
  SCREAMING_SNAKE_CASE     :   List[str]							=	True

  def 			UpperCAmelCase     (					self			,       _SCREAMING_SNAKE_CASE       ):





        """simple docstring"""







        if isinstance(_SCREAMING_SNAKE_CASE			,       (nn.Linear, nn.Convad)       ):
              module.weight.data.normal_(mean=0.0			,       std=self.config.initializer_range       )
              if module.bias is not None:
                    module.bias.data.zero_()
        elif isinstance(_SCREAMING_SNAKE_CASE			,       nn.LayerNorm       ):
              module.bias.data.zero_()
              module.weight.data.fill_(1.0       )



  def 			UpperCAmelCase     (					self			,       _SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE=False       ):





        """simple docstring"""







        if isinstance(_SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE       ):
              SCREAMING_SNAKE_CASE_					:	List[Any]     							=  value

lowerCAmelCase  : Optional[Any]      =	R'\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use\n    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and\n    behavior.\n\n    Parameters:\n        config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.\n'

lowerCAmelCase  : int      =	R'\n    Args:\n        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`PoolFormerImageProcessor.__call__`] for details.\n'
@add_start_docstrings(
    '''The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.''' ,  __magic_name__ ,  )
class 			_A		(	__magic_name__):

  def __init__(					self			,       _SCREAMING_SNAKE_CASE       ):





        """simple docstring"""







        super().__init__(_SCREAMING_SNAKE_CASE       )
        SCREAMING_SNAKE_CASE_					:	Tuple     							=  config

        SCREAMING_SNAKE_CASE_					:	Tuple     							=  PoolFormerEncoder(_SCREAMING_SNAKE_CASE       )

        # Initialize weights and apply final processing
        self.post_init()

  def 			UpperCAmelCase     (					self       ):





        """simple docstring"""







        return self.embeddings.patch_embeddings



  @add_start_docstrings_to_model_forward(_SCREAMING_SNAKE_CASE       )
  @add_code_sample_docstrings(
      checkpoint=_CHECKPOINT_FOR_DOC			,       output_type=_SCREAMING_SNAKE_CASE			,       config_class=_CONFIG_FOR_DOC			,       modality='vision'			,       expected_output=_EXPECTED_OUTPUT_SHAPE			,       )
  def 			UpperCAmelCase     (					self			,       _SCREAMING_SNAKE_CASE = None			,       _SCREAMING_SNAKE_CASE = None			,       _SCREAMING_SNAKE_CASE = None			,       ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_					:	str     							=  (
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        SCREAMING_SNAKE_CASE_					:	int     							=  return_dict if return_dict is not None else self.config.use_return_dict

        if pixel_values is None:
              raise ValueError('You have to specify pixel_values'       )

        SCREAMING_SNAKE_CASE_					:	str     							=  self.encoder(
            _SCREAMING_SNAKE_CASE			,       output_hidden_states=_SCREAMING_SNAKE_CASE			,       return_dict=_SCREAMING_SNAKE_CASE			,       )
        SCREAMING_SNAKE_CASE_					:	str     							=  encoder_outputs[0]

        if not return_dict:
              return (sequence_output, None) + encoder_outputs[1:]

        return BaseModelOutputWithNoAttention(
            last_hidden_state=_SCREAMING_SNAKE_CASE			,       hidden_states=encoder_outputs.hidden_states			,       )

class 			_A		(	nn.Module):

  def __init__(					self			,       _SCREAMING_SNAKE_CASE       ):





        """simple docstring"""







        super().__init__()
        SCREAMING_SNAKE_CASE_					:	Any     							=  nn.Linear(config.hidden_size			,       config.hidden_size       )



  def 			UpperCAmelCase     (					self			,       _SCREAMING_SNAKE_CASE       ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_					:	List[str]     							=  self.dense(_SCREAMING_SNAKE_CASE       )
        return output

@add_start_docstrings(
    '''\n    PoolFormer Model transformer with an image classification head on top\n    ''' ,  __magic_name__ ,  )
class 			_A		(	__magic_name__):

  def __init__(					self			,       _SCREAMING_SNAKE_CASE       ):





        """simple docstring"""







        super().__init__(_SCREAMING_SNAKE_CASE       )
        SCREAMING_SNAKE_CASE_					:	List[Any]     							=  config.num_labels
        SCREAMING_SNAKE_CASE_					:	Dict     							=  PoolFormerModel(_SCREAMING_SNAKE_CASE       )

        # Final norm
        SCREAMING_SNAKE_CASE_					:	int     							=  PoolFormerGroupNorm(config.hidden_sizes[-1]       )
        # Classifier head
        SCREAMING_SNAKE_CASE_					:	Union[str, Any]     							=  (
            nn.Linear(config.hidden_sizes[-1]			,       config.num_labels       ) if config.num_labels > 0 else nn.Identity()
        )

        # Initialize weights and apply final processing
        self.post_init()



  @add_start_docstrings_to_model_forward(_SCREAMING_SNAKE_CASE       )
  @add_code_sample_docstrings(
      checkpoint=_IMAGE_CLASS_CHECKPOINT			,       output_type=_SCREAMING_SNAKE_CASE			,       config_class=_CONFIG_FOR_DOC			,       expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT			,       )
  def 			UpperCAmelCase     (					self			,       _SCREAMING_SNAKE_CASE = None			,       _SCREAMING_SNAKE_CASE = None			,       _SCREAMING_SNAKE_CASE = None			,       _SCREAMING_SNAKE_CASE = None			,       ):





        """simple docstring"""







        SCREAMING_SNAKE_CASE_					:	Optional[int]     							=  return_dict if return_dict is not None else self.config.use_return_dict

        SCREAMING_SNAKE_CASE_					:	int     							=  self.poolformer(
            _SCREAMING_SNAKE_CASE			,       output_hidden_states=_SCREAMING_SNAKE_CASE			,       return_dict=_SCREAMING_SNAKE_CASE			,       )

        SCREAMING_SNAKE_CASE_					:	int     							=  outputs[0]

        SCREAMING_SNAKE_CASE_					:	str     							=  self.classifier(self.norm(_SCREAMING_SNAKE_CASE       ).mean([-2, -1]       )       )

        SCREAMING_SNAKE_CASE_					:	Union[str, Any]     							=  None
        if labels is not None:
              if self.config.problem_type is None:
                    if self.num_labels == 1:
                          SCREAMING_SNAKE_CASE_					:	Tuple     							=  "regression"
                    elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                          SCREAMING_SNAKE_CASE_					:	Dict     							=  "single_label_classification"
                    else:
                          SCREAMING_SNAKE_CASE_					:	Any     							=  "multi_label_classification"

              if self.config.problem_type == "regression":
                    SCREAMING_SNAKE_CASE_					:	Tuple     							=  MSELoss()
                    if self.num_labels == 1:
                          SCREAMING_SNAKE_CASE_					:	Optional[int]     							=  loss_fct(logits.squeeze()			,       labels.squeeze()       )
                    else:
                          SCREAMING_SNAKE_CASE_					:	Optional[Any]     							=  loss_fct(_SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE       )
              elif self.config.problem_type == "single_label_classification":
                    SCREAMING_SNAKE_CASE_					:	Dict     							=  CrossEntropyLoss()
                    SCREAMING_SNAKE_CASE_					:	Optional[Any]     							=  loss_fct(logits.view(-1			,       self.num_labels       )			,       labels.view(-1       )       )
              elif self.config.problem_type == "multi_label_classification":
                    SCREAMING_SNAKE_CASE_					:	Dict     							=  BCEWithLogitsLoss()
                    SCREAMING_SNAKE_CASE_					:	Union[str, Any]     							=  loss_fct(_SCREAMING_SNAKE_CASE			,       _SCREAMING_SNAKE_CASE       )

        if not return_dict:
              SCREAMING_SNAKE_CASE_					:	Optional[Any]     							=  (logits,) + outputs[2:]
              return ((loss,) + output) if loss is not None else output

        return ImageClassifierOutputWithNoAttention(loss=_SCREAMING_SNAKE_CASE			,       logits=_SCREAMING_SNAKE_CASE			,       hidden_states=outputs.hidden_states       )










'''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"		)

