from typing import Optional

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

from ...activations import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_outputs import (
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import logging
from .configuration_regnet import RegNetConfig


__lowerCamelCase					:	Dict       =  logging.get_logger(__name__)

# General docstring
__lowerCamelCase					:	str       =  '''RegNetConfig'''

# Base docstring
__lowerCamelCase					:	List[str]       =  '''facebook/regnet-y-040'''
__lowerCamelCase					:	str       =  [1, 10_88, 7, 7]

# Image classification docstring
__lowerCamelCase					:	List[str]       =  '''facebook/regnet-y-040'''
__lowerCamelCase					:	str       =  '''tabby, tabby cat'''

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






class 		a__						(					nn.Module					):

					def __init__(    self      :       List[str],_A      :       int,_A      :       int,_A      :       int = 3,_A      :       int = 1,_A      :       int = 1,_A      :       Optional[str] = "relu",):







							"""simple docstring"""






							super().__init__()
							SCREAMING_SNAKE_CASE_  :		int				      =    nn.Convad(
							    _A,_A,kernel_size=_A,stride=_A,padding=kernel_size // 2,groups=_A,bias=_A,)
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    nn.BatchNormad(_A    )
							SCREAMING_SNAKE_CASE_  :		Any				      =    ACTaFN[activation] if activation is not None else nn.Identity()






					def 				__UpperCamelCase   (    self      :       Tuple,_A      :       Optional[int]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		str				      =    self.convolution(_A    )
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    self.normalization(_A    )
							SCREAMING_SNAKE_CASE_  :		int				      =    self.activation(_A    )
							return hidden_state







class 		a__						(					nn.Module					):

					def __init__(    self      :       str,_A      :       RegNetConfig    ):







							"""simple docstring"""






							super().__init__()
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    RegNetConvLayer(
							    config.num_channels,config.embedding_size,kernel_size=3,stride=2,activation=config.hidden_act    )
							SCREAMING_SNAKE_CASE_  :		Dict				      =    config.num_channels






					def 				__UpperCamelCase   (    self      :       Dict,_A      :       int    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    pixel_values.shape[1]
							if 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."    )
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    self.embedder(_A    )
							return hidden_state







class 		a__						(					nn.Module					):

					def __init__(    self      :       int,_A      :       int,_A      :       int,_A      :       int = 2    ):







							"""simple docstring"""






							super().__init__()
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    nn.Convad(_A,_A,kernel_size=1,stride=_A,bias=_A    )
							SCREAMING_SNAKE_CASE_  :		str				      =    nn.BatchNormad(_A    )






					def 				__UpperCamelCase   (    self      :       List[str],_A      :       Tensor    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Any				      =    self.convolution(_A    )
							SCREAMING_SNAKE_CASE_  :		Any				      =    self.normalization(_A    )
							return hidden_state







class 		a__						(					nn.Module					):

					def __init__(    self      :       Dict,_A      :       int,_A      :       int    ):







							"""simple docstring"""






							super().__init__()

							SCREAMING_SNAKE_CASE_  :		int				      =    nn.AdaptiveAvgPoolad((1, 1)    )
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    nn.Sequential(
							    nn.Convad(_A,_A,kernel_size=1    ),nn.ReLU(),nn.Convad(_A,_A,kernel_size=1    ),nn.Sigmoid(),)






					def 				__UpperCamelCase   (    self      :       Tuple,_A      :       Union[str, Any]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.pooler(_A    )
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    self.attention(_A    )
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    hidden_state * attention
							return hidden_state







class 		a__						(					nn.Module					):

					def __init__(    self      :       Tuple,_A      :       RegNetConfig,_A      :       int,_A      :       int,_A      :       int = 1    ):







							"""simple docstring"""






							super().__init__()
							SCREAMING_SNAKE_CASE_  :		Dict				      =    in_channels != out_channels or stride != 1
							SCREAMING_SNAKE_CASE_  :		Dict				      =    max(1,out_channels // config.groups_width    )
							SCREAMING_SNAKE_CASE_  :		Any				      =    (
							    RegNetShortCut(_A,_A,stride=_A    ) if should_apply_shortcut else nn.Identity()
							)
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    nn.Sequential(
							    RegNetConvLayer(_A,_A,kernel_size=1,activation=config.hidden_act    ),RegNetConvLayer(_A,_A,stride=_A,groups=_A,activation=config.hidden_act    ),RegNetConvLayer(_A,_A,kernel_size=1,activation=_A    ),)
							SCREAMING_SNAKE_CASE_  :		List[str]				      =    ACTaFN[config.hidden_act]






					def 				__UpperCamelCase   (    self      :       Union[str, Any],_A      :       int    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Dict				      =    hidden_state
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    self.layer(_A    )
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    self.shortcut(_A    )
							hidden_state += residual
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    self.activation(_A    )
							return hidden_state







class 		a__						(					nn.Module					):

					def __init__(    self      :       Union[str, Any],_A      :       RegNetConfig,_A      :       int,_A      :       int,_A      :       int = 1    ):







							"""simple docstring"""






							super().__init__()
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    in_channels != out_channels or stride != 1
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    max(1,out_channels // config.groups_width    )
							SCREAMING_SNAKE_CASE_  :		Any				      =    (
							    RegNetShortCut(_A,_A,stride=_A    ) if should_apply_shortcut else nn.Identity()
							)
							SCREAMING_SNAKE_CASE_  :		int				      =    nn.Sequential(
							    RegNetConvLayer(_A,_A,kernel_size=1,activation=config.hidden_act    ),RegNetConvLayer(_A,_A,stride=_A,groups=_A,activation=config.hidden_act    ),RegNetSELayer(_A,reduced_channels=int(round(in_channels / 4    )    )    ),RegNetConvLayer(_A,_A,kernel_size=1,activation=_A    ),)
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    ACTaFN[config.hidden_act]






					def 				__UpperCamelCase   (    self      :       Dict,_A      :       List[str]    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		str				      =    hidden_state
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    self.layer(_A    )
							SCREAMING_SNAKE_CASE_  :		Tuple				      =    self.shortcut(_A    )
							hidden_state += residual
							SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    self.activation(_A    )
							return hidden_state







class 		a__						(					nn.Module					):

					def __init__(    self      :       List[Any],_A      :       RegNetConfig,_A      :       int,_A      :       int,_A      :       int = 2,_A      :       int = 2,):







							"""simple docstring"""






							super().__init__()

							SCREAMING_SNAKE_CASE_  :		int				      =    RegNetXLayer if config.layer_type == "x" else RegNetYLayer

							SCREAMING_SNAKE_CASE_  :		Any				      =    nn.Sequential(
							    # downsampling is done in the first layer with stride of 2
							    layer(
							        _A,_A,_A,stride=_A,),*[layer(_A,_A,_A    ) for _ in range(depth - 1    )],)






					def 				__UpperCamelCase   (    self      :       Optional[Any],_A      :       Tuple    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Any				      =    self.layers(_A    )
							return hidden_state







class 		a__						(					nn.Module					):

					def __init__(    self      :       List[str],_A      :       RegNetConfig    ):







							"""simple docstring"""






							super().__init__()
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    nn.ModuleList([]    )
							# based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
							self.stages.append(
							    RegNetStage(
							        _A,config.embedding_size,config.hidden_sizes[0],stride=2 if config.downsample_in_first_stage else 1,depth=config.depths[0],)    )
							SCREAMING_SNAKE_CASE_  :		int				      =    zip(config.hidden_sizes,config.hidden_sizes[1:]    )
							for (in_channels, out_channels), depth in zip(_A,config.depths[1:]    ):
									self.stages.append(RegNetStage(_A,_A,_A,depth=_A    )    )






					def 				__UpperCamelCase   (    self      :       Optional[Any],_A      :       Tensor,_A      :       bool = False,_A      :       bool = True    ):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Any				      =    () if output_hidden_states else None

							for stage_module in self.stages:
									if output_hidden_states:
											SCREAMING_SNAKE_CASE_  :		List[Any]				      =    hidden_states + (hidden_state,)

									SCREAMING_SNAKE_CASE_  :		Dict				      =    stage_module(_A    )

							if output_hidden_states:
									SCREAMING_SNAKE_CASE_  :		List[str]				      =    hidden_states + (hidden_state,)

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

							return BaseModelOutputWithNoAttention(last_hidden_state=_A,hidden_states=_A    )







class 		a__						(					A__					):
					A	       =							RegNetConfig
					A	       =							'regnet'
					A	       =							'pixel_values'
					A	       =							True

					def 				__UpperCamelCase   (    self      :       Any,_A      :       Optional[Any]    ):







							"""simple docstring"""






							if isinstance(_A,nn.Convad    ):
									nn.init.kaiming_normal_(module.weight,mode="fan_out",nonlinearity="relu"    )
							elif isinstance(_A,(nn.BatchNormad, nn.GroupNorm)    ):
									nn.init.constant_(module.weight,1    )
									nn.init.constant_(module.bias,0    )






					def 				__UpperCamelCase   (    self      :       str,_A      :       str,_A      :       Optional[Any]=False    ):







							"""simple docstring"""






							if isinstance(_A,_A    ):
									SCREAMING_SNAKE_CASE_  :		int				      =    value







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

    Parameters:
        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 [`~PreTrainedModel.from_pretrained`] method to load the model weights.
'''

__lowerCamelCase					:	Tuple       =  R'''
    Args:
        pixel_values (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConvNextImageProcessor.__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 [`~file_utils.ModelOutput`] instead of a plain tuple.
'''






@add_start_docstrings(
    'The bare RegNet model outputting raw features without any specific head on top.'    ,		A__    ,		)
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class 		a__						(					A__					):

					def __init__(    self      :       Dict,_A      :       int    ):







							"""simple docstring"""






							super().__init__(_A    )
							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    config
							SCREAMING_SNAKE_CASE_  :		Any				      =    RegNetEmbeddings(_A    )
							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    RegNetEncoder(_A    )
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    nn.AdaptiveAvgPoolad((1, 1)    )
							# Initialize weights and apply final processing
							self.post_init()






					@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 				__UpperCamelCase   (    self      :       str,_A      :       Tensor,_A      :       Optional[bool] = None,_A      :       Optional[bool] = None    ):







							"""simple docstring"""






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

							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    self.embedder(_A    )

							SCREAMING_SNAKE_CASE_  :		List[Any]				      =    self.encoder(
							    _A,output_hidden_states=_A,return_dict=_A    )

							SCREAMING_SNAKE_CASE_  :		int				      =    encoder_outputs[0]

							SCREAMING_SNAKE_CASE_  :		Any				      =    self.pooler(_A    )

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

							return BaseModelOutputWithPoolingAndNoAttention(
							    last_hidden_state=_A,pooler_output=_A,hidden_states=encoder_outputs.hidden_states,)







@add_start_docstrings(
    '\n    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    '    ,		A__    ,		)
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class 		a__						(					A__					):

					def __init__(    self      :       str,_A      :       str    ):







							"""simple docstring"""






							super().__init__(_A    )
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    config.num_labels
							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    RegNetModel(_A    )
							# classification head
							SCREAMING_SNAKE_CASE_  :		int				      =    nn.Sequential(
							    nn.Flatten(),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 				__UpperCamelCase   (    self      :       Optional[Any],_A      :       Optional[torch.FloatTensor] = None,_A      :       Optional[torch.LongTensor] = None,_A      :       Optional[bool] = None,_A      :       Optional[bool] = None,):







							"""simple docstring"""






							SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    return_dict if return_dict is not None else self.config.use_return_dict

							SCREAMING_SNAKE_CASE_  :		int				      =    self.regnet(_A,output_hidden_states=_A,return_dict=_A    )

							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    outputs.pooler_output if return_dict else outputs[1]

							SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    self.classifier(_A    )

							SCREAMING_SNAKE_CASE_  :		int				      =    None

							if labels is not None:
									if self.config.problem_type is None:
											if self.num_labels == 1:
													SCREAMING_SNAKE_CASE_  :		Any				      =    "regression"
											elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
													SCREAMING_SNAKE_CASE_  :		Any				      =    "single_label_classification"
											else:
													SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    "multi_label_classification"
									if self.config.problem_type == "regression":
											SCREAMING_SNAKE_CASE_  :		Union[str, Any]				      =    MSELoss()
											if self.num_labels == 1:
													SCREAMING_SNAKE_CASE_  :		int				      =    loss_fct(logits.squeeze(),labels.squeeze()    )
											else:
													SCREAMING_SNAKE_CASE_  :		Any				      =    loss_fct(_A,_A    )
									elif self.config.problem_type == "single_label_classification":
											SCREAMING_SNAKE_CASE_  :		Optional[Any]				      =    CrossEntropyLoss()
											SCREAMING_SNAKE_CASE_  :		List[str]				      =    loss_fct(logits.view(-1,self.num_labels    ),labels.view(-1    )    )
									elif self.config.problem_type == "multi_label_classification":
											SCREAMING_SNAKE_CASE_  :		Optional[int]				      =    BCEWithLogitsLoss()
											SCREAMING_SNAKE_CASE_  :		Dict				      =    loss_fct(_A,_A    )

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

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







import numpy as np


def 	UpperCamelCase__(       UpperCamelCase__			:       np.array  )->np.array:
       return (2 / (1 + np.exp(-2 * vector  ))) - 1


if __name__ == "__main__":
       import doctest

       doctest.testmod()





