





'''simple docstring'''






from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFSequenceClassifierOutput,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import logging
from .configuration_regnet import RegNetConfig


A__				:   Any      =logging.get_logger(__name__)

# General docstring
A__				:   Optional[int]      ='''RegNetConfig'''

# Base docstring
A__				:   Union[str, Any]      ='''facebook/regnet-y-040'''
A__				:   Optional[Any]      =[1, 10_88, 7, 7]

# Image classification docstring
A__				:   int      ='''facebook/regnet-y-040'''
A__				:   List[Any]      ='''tabby, tabby cat'''

A__				:   Any      =[
    '''facebook/regnet-y-040''',
    # See all regnet models at https://huggingface.co/models?filter=regnet
]




class  UpperCAmelCase     (			tf.keras.layers.Layer   ):




      def __init__(			self			: Dict			,			__snake_case			: List[Any]			,			__snake_case			: Optional[Any] = 3			,			__snake_case			: Optional[int] = 1			,			__snake_case			: str = 1			,			__snake_case			: Optional[Any] = "relu"			,			**__snake_case			: Optional[Any]			,			)				->      Optional[Any]:
            super().__init__(**__snake_case  )
            # The padding and conv has been verified in
            # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb
            _lowerCAmelCase							     =							tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2  )
            _lowerCAmelCase							     =							tf.keras.layers.ConvaD(
                filters=__snake_case			,			kernel_size=__snake_case			,			strides=__snake_case			,			padding="""VALID"""			,			groups=__snake_case			,			use_bias=__snake_case			,			name="""convolution"""			,			)
            _lowerCAmelCase							     =							tf.keras.layers.BatchNormalization(epsilon=1E-5			,			momentum=0.9			,			name="""normalization"""  )
            _lowerCAmelCase							     =							ACTaFN[activation] if activation is not None else tf.identity




      def 				lowercase__    (			self			: Dict			,			__snake_case			: Tuple  )				->      str:
            _lowerCAmelCase							     =							self.convolution(self.padding(__snake_case  )  )
            _lowerCAmelCase							     =							self.normalization(__snake_case  )
            _lowerCAmelCase							     =							self.activation(__snake_case  )
            return hidden_state




class  UpperCAmelCase     (			tf.keras.layers.Layer   ):




      def __init__(			self			: Tuple			,			__snake_case			: Optional[Any]			,			**__snake_case			: Optional[int]  )				->      Optional[int]:
            super().__init__(**__snake_case  )
            _lowerCAmelCase							     =							config.num_channels
            _lowerCAmelCase							     =							TFRegNetConvLayer(
                out_channels=config.embedding_size			,			kernel_size=3			,			stride=2			,			activation=config.hidden_act			,			name="""embedder"""			,			)




      def 				lowercase__    (			self			: Any			,			__snake_case			: str  )				->      Union[str, Any]:
            _lowerCAmelCase							     =							shape_list(__snake_case  )[1]
            if tf.executing_eagerly() and num_channels != self.num_channels:
                  raise ValueError(
                      """Make sure that the channel dimension of the pixel values match with the one set in the configuration."""  )

            # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format.
            # So change the input format from `NCHW` to `NHWC`.
            # shape = (batch_size, in_height, in_width, in_channels=num_channels)
            _lowerCAmelCase							     =							tf.transpose(__snake_case			,			perm=(0, 2, 3, 1)  )
            _lowerCAmelCase							     =							self.embedder(__snake_case  )
            return hidden_state




class  UpperCAmelCase     (			tf.keras.layers.Layer   ):




      def __init__(			self			: Dict			,			__snake_case			: List[str]			,			__snake_case			: int = 2			,			**__snake_case			: Any  )				->      List[str]:
            super().__init__(**__snake_case  )
            _lowerCAmelCase							     =							tf.keras.layers.ConvaD(
                filters=__snake_case			,			kernel_size=1			,			strides=__snake_case			,			use_bias=__snake_case			,			name="""convolution"""  )
            _lowerCAmelCase							     =							tf.keras.layers.BatchNormalization(epsilon=1E-5			,			momentum=0.9			,			name="""normalization"""  )




      def 				lowercase__    (			self			: Tuple			,			__snake_case			: Union[str, Any]			,			__snake_case			: List[str] = False  )				->      tf.Tensor:
            return self.normalization(self.convolution(__snake_case  )			,			training=__snake_case  )




class  UpperCAmelCase     (			tf.keras.layers.Layer   ):




      def __init__(			self			: Tuple			,			__snake_case			: Optional[Any]			,			__snake_case			: Optional[int]			,			**__snake_case			: Tuple  )				->      str:
            super().__init__(**__snake_case  )
            _lowerCAmelCase							     =							tf.keras.layers.GlobalAveragePoolingaD(keepdims=__snake_case			,			name="""pooler"""  )
            _lowerCAmelCase							     =							[
                tf.keras.layers.ConvaD(filters=__snake_case			,			kernel_size=1			,			activation="""relu"""			,			name="""attention.0"""  ),
                tf.keras.layers.ConvaD(filters=__snake_case			,			kernel_size=1			,			activation="""sigmoid"""			,			name="""attention.2"""  ),
            ]




      def 				lowercase__    (			self			: int			,			__snake_case			: Optional[Any]  )				->      Dict:
            # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels]
            _lowerCAmelCase							     =							self.pooler(__snake_case  )
            for layer_module in self.attention:
                  _lowerCAmelCase							     =							layer_module(__snake_case  )
            _lowerCAmelCase							     =							hidden_state * pooled
            return hidden_state




class  UpperCAmelCase     (			tf.keras.layers.Layer   ):




      def __init__(			self			: Any			,			__snake_case			: str			,			__snake_case			: Union[str, Any]			,			__snake_case			: Tuple			,			__snake_case			: Tuple = 1			,			**__snake_case			: Optional[Any]  )				->      int:
            super().__init__(**__snake_case  )
            _lowerCAmelCase							     =							in_channels != out_channels or stride != 1
            _lowerCAmelCase							     =							max(1			,			out_channels // config.groups_width  )
            _lowerCAmelCase							     =							(
                TFRegNetShortCut(__snake_case			,			stride=__snake_case			,			name="""shortcut"""  )
                if should_apply_shortcut
                else tf.keras.layers.Activation("""linear"""			,			name="""shortcut"""  )
            )
            # `self.layers` instead of `self.layer` because that is a reserved argument.
            _lowerCAmelCase							     =							[
                TFRegNetConvLayer(__snake_case			,			kernel_size=1			,			activation=config.hidden_act			,			name="""layer.0"""  ),
                TFRegNetConvLayer(
                    __snake_case			,			stride=__snake_case			,			groups=__snake_case			,			activation=config.hidden_act			,			name="""layer.1"""  ),
                TFRegNetConvLayer(__snake_case			,			kernel_size=1			,			activation=__snake_case			,			name="""layer.2"""  ),
            ]
            _lowerCAmelCase							     =							ACTaFN[config.hidden_act]




      def 				lowercase__    (			self			: int			,			__snake_case			: List[Any]  )				->      Union[str, Any]:
            _lowerCAmelCase							     =							hidden_state
            for layer_module in self.layers:
                  _lowerCAmelCase							     =							layer_module(__snake_case  )
            _lowerCAmelCase							     =							self.shortcut(__snake_case  )
            hidden_state += residual
            _lowerCAmelCase							     =							self.activation(__snake_case  )
            return hidden_state




class  UpperCAmelCase     (			tf.keras.layers.Layer   ):




      def __init__(			self			: Optional[int]			,			__snake_case			: Tuple			,			__snake_case			: Union[str, Any]			,			__snake_case			: Union[str, Any]			,			__snake_case			: Dict = 1			,			**__snake_case			: List[Any]  )				->      Tuple:
            super().__init__(**__snake_case  )
            _lowerCAmelCase							     =							in_channels != out_channels or stride != 1
            _lowerCAmelCase							     =							max(1			,			out_channels // config.groups_width  )
            _lowerCAmelCase							     =							(
                TFRegNetShortCut(__snake_case			,			stride=__snake_case			,			name="""shortcut"""  )
                if should_apply_shortcut
                else tf.keras.layers.Activation("""linear"""			,			name="""shortcut"""  )
            )
            _lowerCAmelCase							     =							[
                TFRegNetConvLayer(__snake_case			,			kernel_size=1			,			activation=config.hidden_act			,			name="""layer.0"""  ),
                TFRegNetConvLayer(
                    __snake_case			,			stride=__snake_case			,			groups=__snake_case			,			activation=config.hidden_act			,			name="""layer.1"""  ),
                TFRegNetSELayer(__snake_case			,			reduced_channels=int(round(in_channels / 4  )  )			,			name="""layer.2"""  ),
                TFRegNetConvLayer(__snake_case			,			kernel_size=1			,			activation=__snake_case			,			name="""layer.3"""  ),
            ]
            _lowerCAmelCase							     =							ACTaFN[config.hidden_act]




      def 				lowercase__    (			self			: Dict			,			__snake_case			: int  )				->      Optional[int]:
            _lowerCAmelCase							     =							hidden_state
            for layer_module in self.layers:
                  _lowerCAmelCase							     =							layer_module(__snake_case  )
            _lowerCAmelCase							     =							self.shortcut(__snake_case  )
            hidden_state += residual
            _lowerCAmelCase							     =							self.activation(__snake_case  )
            return hidden_state




class  UpperCAmelCase     (			tf.keras.layers.Layer   ):




      def __init__(			self			: Any			,			__snake_case			: List[Any]			,			__snake_case			: Dict			,			__snake_case			: Optional[Any]			,			__snake_case			: Optional[Any] = 2			,			__snake_case			: List[Any] = 2			,			**__snake_case			: Tuple  )				->      int:
            super().__init__(**__snake_case  )

            _lowerCAmelCase							     =							TFRegNetXLayer if config.layer_type == """x""" else TFRegNetYLayer
            _lowerCAmelCase							     =							[
                # downsampling is done in the first layer with stride of 2
                layer(__snake_case			,			__snake_case			,			__snake_case			,			stride=__snake_case			,			name="""layers.0"""  ),
                *[layer(__snake_case			,			__snake_case			,			__snake_case			,			name=f"layers.{i+1}"  ) for i in range(depth - 1  )],
            ]




      def 				lowercase__    (			self			: Tuple			,			__snake_case			: Tuple  )				->      Optional[Any]:
            for layer_module in self.layers:
                  _lowerCAmelCase							     =							layer_module(__snake_case  )
            return hidden_state




class  UpperCAmelCase     (			tf.keras.layers.Layer   ):




      def __init__(			self			: Union[str, Any]			,			__snake_case			: List[Any]			,			**__snake_case			: Tuple  )				->      Tuple:
            super().__init__(**__snake_case  )
            _lowerCAmelCase							     =							[]
            # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
            self.stages.append(
                TFRegNetStage(
                    __snake_case			,			config.embedding_size			,			config.hidden_sizes[0]			,			stride=2 if config.downsample_in_first_stage else 1			,			depth=config.depths[0]			,			name="""stages.0"""			,			)  )
            _lowerCAmelCase							     =							zip(config.hidden_sizes			,			config.hidden_sizes[1:]  )
            for i, ((in_channels, out_channels), depth) in enumerate(zip(__snake_case			,			config.depths[1:]  )  ):
                  self.stages.append(TFRegNetStage(__snake_case			,			__snake_case			,			__snake_case			,			depth=__snake_case			,			name=f"stages.{i+1}"  )  )




      def 				lowercase__    (			self			: Dict			,			__snake_case			: Optional[Any]			,			__snake_case			: int = False			,			__snake_case			: int = True  )				->      TFBaseModelOutputWithNoAttention:
            _lowerCAmelCase							     =							() if output_hidden_states else None

            for stage_module in self.stages:
                  if output_hidden_states:
                        _lowerCAmelCase							     =							hidden_states + (hidden_state,)

                  _lowerCAmelCase							     =							stage_module(__snake_case  )

            if output_hidden_states:
                  _lowerCAmelCase							     =							hidden_states + (hidden_state,)

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

            return TFBaseModelOutputWithNoAttention(last_hidden_state=__snake_case			,			hidden_states=__snake_case  )




@keras_serializable
class  UpperCAmelCase     (			tf.keras.layers.Layer   ):
      _lowercase:			str						     =   RegNetConfig




      def __init__(			self			: Optional[Any]			,			__snake_case			: Any			,			**__snake_case			: List[Any]  )				->      Any:
            super().__init__(**__snake_case  )
            _lowerCAmelCase							     =							config
            _lowerCAmelCase							     =							TFRegNetEmbeddings(__snake_case			,			name="""embedder"""  )
            _lowerCAmelCase							     =							TFRegNetEncoder(__snake_case			,			name="""encoder"""  )
            _lowerCAmelCase							     =							tf.keras.layers.GlobalAveragePoolingaD(keepdims=__snake_case			,			name="""pooler"""  )




      @unpack_inputs
      def 				lowercase__    (			self			: int			,			__snake_case			: List[str]			,			__snake_case			: Any = None			,			__snake_case			: List[Any] = None			,			__snake_case			: List[str] = False			,			)				->      TFBaseModelOutputWithPoolingAndNoAttention:
            _lowerCAmelCase							     =							(
                output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
            )
            _lowerCAmelCase							     =							return_dict if return_dict is not None else self.config.use_return_dict

            _lowerCAmelCase							     =							self.embedder(__snake_case			,			training=__snake_case  )

            _lowerCAmelCase							     =							self.encoder(
                __snake_case			,			output_hidden_states=__snake_case			,			return_dict=__snake_case			,			training=__snake_case  )

            _lowerCAmelCase							     =							encoder_outputs[0]
            _lowerCAmelCase							     =							self.pooler(__snake_case  )

            # Change to NCHW output format have uniformity in the modules
            _lowerCAmelCase							     =							tf.transpose(__snake_case			,			perm=(0, 3, 1, 2)  )
            _lowerCAmelCase							     =							tf.transpose(__snake_case			,			perm=(0, 3, 1, 2)  )

            # Change the other hidden state outputs to NCHW as well
            if output_hidden_states:
                  _lowerCAmelCase							     =							tuple([tf.transpose(__snake_case			,			perm=(0, 3, 1, 2)  ) for h in encoder_outputs[1]]  )

            if not return_dict:
                  return (last_hidden_state, pooled_output) + encoder_outputs[1:]

            return TFBaseModelOutputWithPoolingAndNoAttention(
                last_hidden_state=__snake_case			,			pooler_output=__snake_case			,			hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states			,			)




class  UpperCAmelCase     (			snake_case_   ):
      _lowercase:			List[str]						     =   RegNetConfig
      _lowercase:			str						     =   '''regnet'''
      _lowercase:			Optional[int]						     =   '''pixel_values'''




      @property
      def 				lowercase__    (			self			: str  )				->      str:
            return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24)			,			dtype=tf.floataa  )}




A__				:   Dict      =r'''
    Parameters:
    This model is a Tensorflow
    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a
    regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and
    behavior.
        config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
'''

A__				:   Any      =r'''
    Args:
        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConveNextImageProcessor.__call__`] for details.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
'''




@add_start_docstrings(
    '''The bare RegNet model outputting raw features without any specific head on top.'''							,		snake_case_							,		)
class  UpperCAmelCase     (			snake_case_   ):




      def __init__(			self			: List[Any]			,			__snake_case			: List[Any]			,			*__snake_case			: str			,			**__snake_case			: Optional[int]  )				->      Any:
            super().__init__(__snake_case			,			*__snake_case			,			**__snake_case  )
            _lowerCAmelCase							     =							TFRegNetMainLayer(__snake_case			,			name="""regnet"""  )




      @unpack_inputs
      @add_start_docstrings_to_model_forward(__snake_case  )
      @add_code_sample_docstrings(
          checkpoint=_CHECKPOINT_FOR_DOC			,			output_type=__snake_case			,			config_class=_CONFIG_FOR_DOC			,			modality="""vision"""			,			expected_output=_EXPECTED_OUTPUT_SHAPE			,			)
      def 				lowercase__    (			self			: Dict			,			__snake_case			: Optional[Any]			,			__snake_case			: Optional[int] = None			,			__snake_case			: Optional[int] = None			,			__snake_case			: List[str]=False			,			)				->      Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]:
            _lowerCAmelCase							     =							(
                output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
            )
            _lowerCAmelCase							     =							return_dict if return_dict is not None else self.config.use_return_dict

            _lowerCAmelCase							     =							self.regnet(
                pixel_values=__snake_case			,			output_hidden_states=__snake_case			,			return_dict=__snake_case			,			training=__snake_case			,			)
            if not return_dict:
                  return (outputs[0],) + outputs[1:]

            return TFBaseModelOutputWithPoolingAndNoAttention(
                last_hidden_state=outputs.last_hidden_state			,			pooler_output=outputs.pooler_output			,			hidden_states=outputs.hidden_states			,			)




@add_start_docstrings(
    '''
    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    '''							,		snake_case_							,		)
class  UpperCAmelCase     (			snake_case_							,		snake_case_   ):




      def __init__(			self			: str			,			__snake_case			: Tuple			,			*__snake_case			: int			,			**__snake_case			: Optional[int]  )				->      str:
            super().__init__(__snake_case			,			*__snake_case			,			**__snake_case  )
            _lowerCAmelCase							     =							config.num_labels
            _lowerCAmelCase							     =							TFRegNetMainLayer(__snake_case			,			name="""regnet"""  )
            # classification head
            _lowerCAmelCase							     =							[
                tf.keras.layers.Flatten(),
                tf.keras.layers.Dense(config.num_labels			,			name="""classifier.1"""  ) if config.num_labels > 0 else tf.identity,
            ]




      @unpack_inputs
      @add_start_docstrings_to_model_forward(__snake_case  )
      @add_code_sample_docstrings(
          checkpoint=_IMAGE_CLASS_CHECKPOINT			,			output_type=__snake_case			,			config_class=_CONFIG_FOR_DOC			,			expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT			,			)
      def 				lowercase__    (			self			: Tuple			,			__snake_case			: Optional[int] = None			,			__snake_case			: int = None			,			__snake_case			: Tuple = None			,			__snake_case			: int = None			,			__snake_case			: int=False			,			)				->      Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
            _lowerCAmelCase							     =							(
                output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
            )
            _lowerCAmelCase							     =							return_dict if return_dict is not None else self.config.use_return_dict

            _lowerCAmelCase							     =							self.regnet(
                __snake_case			,			output_hidden_states=__snake_case			,			return_dict=__snake_case			,			training=__snake_case  )

            _lowerCAmelCase							     =							outputs.pooler_output if return_dict else outputs[1]

            _lowerCAmelCase							     =							self.classifier[0](__snake_case  )
            _lowerCAmelCase							     =							self.classifier[1](__snake_case  )

            _lowerCAmelCase							     =							None if labels is None else self.hf_compute_loss(labels=__snake_case			,			logits=__snake_case  )

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

            return TFSequenceClassifierOutput(loss=__snake_case			,			logits=__snake_case			,			hidden_states=outputs.hidden_states  )













'''simple docstring'''

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


lowercase_					= logging.get_logger(__name__)

# General docstring
lowercase_					= """PoolFormerConfig"""

# Base docstring
lowercase_					= """sail/poolformer_s12"""
lowercase_					= [1, 512, 7, 7]

# Image classification docstring
lowercase_					= """sail/poolformer_s12"""
lowercase_					= """tabby, tabby cat"""

lowercase_					= [
    """sail/poolformer_s12""",
    # See all PoolFormer models at https://huggingface.co/models?filter=poolformer
]





def lowerCamelCase						(     __lowerCamelCase :    List[Any]					,       __lowerCamelCase :    float = 0.0					,       __lowerCamelCase :    bool = False    )						->int:
    if drop_prob == 0.0 or not training:
        return input
    _SCREAMING_SNAKE_CASE									=			1 - drop_prob
    _SCREAMING_SNAKE_CASE									=			(input.shape[0],) + (1,) * (input.ndim - 1)  # work with diff dim tensors, not just 2D ConvNets
    _SCREAMING_SNAKE_CASE									=			keep_prob + torch.rand(__lowerCamelCase					,       dtype=input.dtype					,       device=input.device    )
    random_tensor.floor_()  # binarize
    _SCREAMING_SNAKE_CASE									=			input.div(__lowerCamelCase    ) * random_tensor
    return output


class 					a_     (				nn.Module       ):

    '''simple docstring'''


    def __init__(		self ,		A = None       )		->   None:
        super().__init__()
        _SCREAMING_SNAKE_CASE									=			drop_prob


    def 			snake_case_(		self ,		A       )		->   torch.Tensor:
        return drop_path(A ,		self.drop_prob ,		self.training       )





    def 			snake_case_(		self       )		->   str:
        return "p={}".format(self.drop_prob       )




class 					a_     (				nn.Module       ):

    '''simple docstring'''


    def __init__(		self ,		A ,		A ,		A ,		A ,		A ,		A=None       )		->   Union[str, Any]:
        super().__init__()
        _SCREAMING_SNAKE_CASE									=			patch_size if isinstance(A ,		collections.abc.Iterable       ) else (patch_size, patch_size)
        _SCREAMING_SNAKE_CASE									=			stride if isinstance(A ,		collections.abc.Iterable       ) else (stride, stride)
        _SCREAMING_SNAKE_CASE									=			padding if isinstance(A ,		collections.abc.Iterable       ) else (padding, padding)

        _SCREAMING_SNAKE_CASE									=			nn.Convad(A ,		A ,		kernel_size=A ,		stride=A ,		padding=A       )
        _SCREAMING_SNAKE_CASE									=			norm_layer(A       ) if norm_layer else nn.Identity()





    def 			snake_case_(		self ,		A       )		->   Optional[Any]:
        _SCREAMING_SNAKE_CASE									=			self.projection(A       )
        _SCREAMING_SNAKE_CASE									=			self.norm(A       )
        return embeddings




class 					a_     (				nn.GroupNorm       ):

    '''simple docstring'''


    def __init__(		self ,		A ,		**A       )		->   Union[str, Any]:
        super().__init__(1 ,		A ,		**A       )




class 					a_     (				nn.Module       ):

    '''simple docstring'''


    def __init__(		self ,		A       )		->   Union[str, Any]:
        super().__init__()
        _SCREAMING_SNAKE_CASE									=			nn.AvgPoolad(A ,		stride=1 ,		padding=pool_size // 2 ,		count_include_pad=A       )





    def 			snake_case_(		self ,		A       )		->   Union[str, Any]:
        return self.pool(A       ) - hidden_states




class 					a_     (				nn.Module       ):

    '''simple docstring'''


    def __init__(		self ,		A ,		A ,		A ,		A       )		->   List[Any]:
        super().__init__()
        _SCREAMING_SNAKE_CASE									=			nn.Convad(A ,		A ,		1       )
        _SCREAMING_SNAKE_CASE									=			nn.Convad(A ,		A ,		1       )
        _SCREAMING_SNAKE_CASE									=			PoolFormerDropPath(A       )
        if isinstance(config.hidden_act ,		A       ):
            _SCREAMING_SNAKE_CASE									=			ACTaFN[config.hidden_act]
        else:
            _SCREAMING_SNAKE_CASE									=			config.hidden_act





    def 			snake_case_(		self ,		A       )		->   Optional[int]:
        _SCREAMING_SNAKE_CASE									=			self.conva(A       )
        _SCREAMING_SNAKE_CASE									=			self.act_fn(A       )
        _SCREAMING_SNAKE_CASE									=			self.drop(A       )
        _SCREAMING_SNAKE_CASE									=			self.conva(A       )
        _SCREAMING_SNAKE_CASE									=			self.drop(A       )

        return hidden_states




class 					a_     (				nn.Module       ):

    '''simple docstring'''


    def __init__(		self ,		A ,		A ,		A ,		A ,		A ,		A       )		->   Union[str, Any]:
        super().__init__()
        _SCREAMING_SNAKE_CASE									=			PoolFormerPooling(A       )
        _SCREAMING_SNAKE_CASE									=			PoolFormerOutput(A ,		A ,		A ,		A       )
        _SCREAMING_SNAKE_CASE									=			PoolFormerGroupNorm(A       )
        _SCREAMING_SNAKE_CASE									=			PoolFormerGroupNorm(A       )

        # Useful for training neural nets
        _SCREAMING_SNAKE_CASE									=			PoolFormerDropPath(A       ) if drop_path > 0.0 else nn.Identity()
        _SCREAMING_SNAKE_CASE									=			config.use_layer_scale
        if config.use_layer_scale:
            _SCREAMING_SNAKE_CASE									=			nn.Parameter(
                config.layer_scale_init_value * torch.ones((A)       ) ,		requires_grad=A       )
            _SCREAMING_SNAKE_CASE									=			nn.Parameter(
                config.layer_scale_init_value * torch.ones((A)       ) ,		requires_grad=A       )





    def 			snake_case_(		self ,		A       )		->   Optional[Any]:
        if self.use_layer_scale:
            _SCREAMING_SNAKE_CASE									=			self.pooling(self.before_norm(A       )       )
            _SCREAMING_SNAKE_CASE									=			self.layer_scale_a.unsqueeze(-1       ).unsqueeze(-1       ) * pooling_output
            # First residual connection
            _SCREAMING_SNAKE_CASE									=			hidden_states + self.drop_path(A       )
            _SCREAMING_SNAKE_CASE									=			()

            _SCREAMING_SNAKE_CASE									=			self.output(self.after_norm(A       )       )
            _SCREAMING_SNAKE_CASE									=			self.layer_scale_a.unsqueeze(-1       ).unsqueeze(-1       ) * layer_output
            # Second residual connection
            _SCREAMING_SNAKE_CASE									=			hidden_states + self.drop_path(A       )

            _SCREAMING_SNAKE_CASE									=			(output,) + outputs
            return outputs

        else:
            _SCREAMING_SNAKE_CASE									=			self.drop_path(self.pooling(self.before_norm(A       )       )       )
            # First residual connection
            _SCREAMING_SNAKE_CASE									=			pooling_output + hidden_states
            _SCREAMING_SNAKE_CASE									=			()

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

            _SCREAMING_SNAKE_CASE									=			(output,) + outputs
            return outputs




class 					a_     (				nn.Module       ):

    '''simple docstring'''


    def __init__(		self ,		A       )		->   Any:
        super().__init__()
        _SCREAMING_SNAKE_CASE									=			config
        # stochastic depth decay rule
        _SCREAMING_SNAKE_CASE									=			[x.item() for x in torch.linspace(0 ,		config.drop_path_rate ,		sum(config.depths       )       )]

        # patch embeddings
        _SCREAMING_SNAKE_CASE									=			[]
        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									=			nn.ModuleList(A       )

        # Transformer blocks
        _SCREAMING_SNAKE_CASE									=			[]
        _SCREAMING_SNAKE_CASE									=			0
        for i in range(config.num_encoder_blocks       ):
            # each block consists of layers
            _SCREAMING_SNAKE_CASE									=			[]
            if i != 0:
                cur += config.depths[i - 1]
            for j in range(config.depths[i]       ):
                layers.append(
                    PoolFormerLayer(
                        A ,		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(A       )       )

        _SCREAMING_SNAKE_CASE									=			nn.ModuleList(A       )





    def 			snake_case_(		self ,		A ,		A=False ,		A=True       )		->   List[Any]:
        _SCREAMING_SNAKE_CASE									=			() if output_hidden_states else None

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

            if output_hidden_states:
                _SCREAMING_SNAKE_CASE									=			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=A ,		hidden_states=A       )




class 					a_     (				snake_case_       ):

    '''simple docstring'''
    UpperCamelCase     = PoolFormerConfig
    UpperCamelCase     = '''poolformer'''
    UpperCamelCase     = '''pixel_values'''
    UpperCamelCase     = True


    def 			snake_case_(		self ,		A       )		->   int:
        if isinstance(A ,		(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(A ,		nn.LayerNorm       ):
            module.bias.data.zero_()
            module.weight.data.fill_(1.0       )





    def 			snake_case_(		self ,		A ,		A=False       )		->   Dict:
        if isinstance(A ,		A       ):
            _SCREAMING_SNAKE_CASE									=			value




lowercase_					= R"""
    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
    it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`PoolFormerConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""

lowercase_					= R"""
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`PoolFormerImageProcessor.__call__`] for details.
"""


@add_start_docstrings(
    '''The bare PoolFormer Model transformer outputting raw hidden-states without any specific head on top.'''      ,    snake_case_      ,    )
class 					a_     (				snake_case_       ):

    '''simple docstring'''


    def __init__(		self ,		A       )		->   int:
        super().__init__(A       )
        _SCREAMING_SNAKE_CASE									=			config

        _SCREAMING_SNAKE_CASE									=			PoolFormerEncoder(A       )

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


    def 			snake_case_(		self       )		->   Any:
        return self.embeddings.patch_embeddings





    @add_start_docstrings_to_model_forward(A       )
    @add_code_sample_docstrings(
        checkpoint=_CHECKPOINT_FOR_DOC ,		output_type=A ,		config_class=_CONFIG_FOR_DOC ,		modality="""vision""" ,		expected_output=_EXPECTED_OUTPUT_SHAPE ,		)
    def 			snake_case_(		self ,		A = None ,		A = None ,		A = None ,		)		->   Union[Tuple, BaseModelOutputWithNoAttention]:
        _SCREAMING_SNAKE_CASE									=			(
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        _SCREAMING_SNAKE_CASE									=			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									=			self.encoder(
            A ,		output_hidden_states=A ,		return_dict=A ,		)
        _SCREAMING_SNAKE_CASE									=			encoder_outputs[0]

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

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




class 					a_     (				nn.Module       ):

    '''simple docstring'''


    def __init__(		self ,		A       )		->   Dict:
        super().__init__()
        _SCREAMING_SNAKE_CASE									=			nn.Linear(config.hidden_size ,		config.hidden_size       )





    def 			snake_case_(		self ,		A       )		->   str:
        _SCREAMING_SNAKE_CASE									=			self.dense(A       )
        return output




@add_start_docstrings(
    '''
    PoolFormer Model transformer with an image classification head on top
    '''      ,    snake_case_      ,    )
class 					a_     (				snake_case_       ):

    '''simple docstring'''


    def __init__(		self ,		A       )		->   Optional[Any]:
        super().__init__(A       )
        _SCREAMING_SNAKE_CASE									=			config.num_labels
        _SCREAMING_SNAKE_CASE									=			PoolFormerModel(A       )

        # Final norm
        _SCREAMING_SNAKE_CASE									=			PoolFormerGroupNorm(config.hidden_sizes[-1]       )
        # Classifier head
        _SCREAMING_SNAKE_CASE									=			(
            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(A       )
    @add_code_sample_docstrings(
        checkpoint=_IMAGE_CLASS_CHECKPOINT ,		output_type=A ,		config_class=_CONFIG_FOR_DOC ,		expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT ,		)
    def 			snake_case_(		self ,		A = None ,		A = None ,		A = None ,		A = None ,		)		->   Union[Tuple, ImageClassifierOutputWithNoAttention]:
        _SCREAMING_SNAKE_CASE									=			return_dict if return_dict is not None else self.config.use_return_dict

        _SCREAMING_SNAKE_CASE									=			self.poolformer(
            A ,		output_hidden_states=A ,		return_dict=A ,		)

        _SCREAMING_SNAKE_CASE									=			outputs[0]

        _SCREAMING_SNAKE_CASE									=			self.classifier(self.norm(A       ).mean([-2, -1]       )       )

        _SCREAMING_SNAKE_CASE									=			None
        if labels is not None:
            if self.config.problem_type is None:
                if self.num_labels == 1:
                    _SCREAMING_SNAKE_CASE									=			"""regression"""
                elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                    _SCREAMING_SNAKE_CASE									=			"""single_label_classification"""
                else:
                    _SCREAMING_SNAKE_CASE									=			"""multi_label_classification"""

            if self.config.problem_type == "regression":
                _SCREAMING_SNAKE_CASE									=			MSELoss()
                if self.num_labels == 1:
                    _SCREAMING_SNAKE_CASE									=			loss_fct(logits.squeeze() ,		labels.squeeze()       )
                else:
                    _SCREAMING_SNAKE_CASE									=			loss_fct(A ,		A       )
            elif self.config.problem_type == "single_label_classification":
                _SCREAMING_SNAKE_CASE									=			CrossEntropyLoss()
                _SCREAMING_SNAKE_CASE									=			loss_fct(logits.view(-1 ,		self.num_labels       ) ,		labels.view(-1       )       )
            elif self.config.problem_type == "multi_label_classification":
                _SCREAMING_SNAKE_CASE									=			BCEWithLogitsLoss()
                _SCREAMING_SNAKE_CASE									=			loss_fct(A ,		A       )

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

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



