


'''simple docstring'''


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 ...modeling_outputs import (
    BackboneOutput,
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import (
    add_code_sample_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    logging,
    replace_return_docstrings,
)
from ...utils.backbone_utils import BackboneMixin
from .configuration_resnet import ResNetConfig


__magic_name__			=      logging.get_logger(__name__)

# General docstring
__magic_name__			=      'ResNetConfig'

# Base docstring
__magic_name__			=      'microsoft/resnet-50'
__magic_name__			=      [1, 2_048, 7, 7]

# Image classification docstring
__magic_name__			=      'microsoft/resnet-50'
__magic_name__			=      'tiger cat'

__magic_name__			=      [
    'microsoft/resnet-50',
    # See all resnet models at https://huggingface.co/models?filter=resnet
]



class 	__lowerCAmelCase		(							nn.Module    ):


  '''simple docstring'''







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

        '''simple docstring'''




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






  def        _a							(							self :       List[Any]	,_a :       List[str] ):

        '''simple docstring'''




        A_						:  Optional[int]          =				self.convolution(_a )
        A_						:  List[Any]          =				self.normalization(_a )
        A_						:  Optional[int]          =				self.activation(_a )
        return hidden_state







class 	__lowerCAmelCase		(							nn.Module    ):


  '''simple docstring'''







  def __init__(							self :       Any	,_a :       Tuple ):

        '''simple docstring'''




        super().__init__()
        A_						:  Optional[int]          =				ResNetConvLayer(
            config.num_channels	,config.embedding_size	,kernel_size=7	,stride=2	,activation=config.hidden_act )
        A_						:  int          =				nn.MaxPoolad(kernel_size=3	,stride=2	,padding=1 )
        A_						:  Dict          =				config.num_channels






  def        _a							(							self :       Optional[Any]	,_a :       Any ):

        '''simple docstring'''




        A_						:  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.""" )
        A_						:  Any          =				self.embedder(_a )
        A_						:  str          =				self.pooler(_a )
        return embedding







class 	__lowerCAmelCase		(							nn.Module    ):


  '''simple docstring'''







  def __init__(							self :       List[Any]	,_a :       List[Any]	,_a :       Any	,_a :       Optional[int] = 2 ):

        '''simple docstring'''




        super().__init__()
        A_						:  List[Any]          =				nn.Convad(_a	,_a	,kernel_size=1	,stride=_a	,bias=_a )
        A_						:  Optional[int]          =				nn.BatchNormad(_a )






  def        _a							(							self :       List[str]	,_a :       int ):

        '''simple docstring'''




        A_						:  Any          =				self.convolution(_a )
        A_						:  Union[str, Any]          =				self.normalization(_a )
        return hidden_state







class 	__lowerCAmelCase		(							nn.Module    ):


  '''simple docstring'''







  def __init__(							self :       Union[str, Any]	,_a :       List[str]	,_a :       Any	,_a :       Dict = 1	,_a :       Optional[Any] = "relu" ):

        '''simple docstring'''




        super().__init__()
        A_						:  Dict          =				in_channels != out_channels or stride != 1
        A_						:  Union[str, Any]          =				(
            ResNetShortCut(_a	,_a	,stride=_a ) if should_apply_shortcut else nn.Identity()
        )
        A_						:  Tuple          =				nn.Sequential(
            ResNetConvLayer(_a	,_a	,stride=_a )	,ResNetConvLayer(_a	,_a	,activation=_a )	,)
        A_						:  int          =				ACTaFN[activation]






  def        _a							(							self :       List[Any]	,_a :       Optional[int] ):

        '''simple docstring'''




        A_						:  Dict          =				hidden_state
        A_						:  Optional[int]          =				self.layer(_a )
        A_						:  Any          =				self.shortcut(_a )
        hidden_state += residual
        A_						:  Tuple          =				self.activation(_a )
        return hidden_state







class 	__lowerCAmelCase		(							nn.Module    ):


  '''simple docstring'''







  def __init__(							self :       Dict	,_a :       List[str]	,_a :       int	,_a :       Any = 1	,_a :       Union[str, Any] = "relu"	,_a :       str = 4 ):

        '''simple docstring'''




        super().__init__()
        A_						:  Optional[int]          =				in_channels != out_channels or stride != 1
        A_						:  List[Any]          =				out_channels // reduction
        A_						:  Dict          =				(
            ResNetShortCut(_a	,_a	,stride=_a ) if should_apply_shortcut else nn.Identity()
        )
        A_						:  Dict          =				nn.Sequential(
            ResNetConvLayer(_a	,_a	,kernel_size=1 )	,ResNetConvLayer(_a	,_a	,stride=_a )	,ResNetConvLayer(_a	,_a	,kernel_size=1	,activation=_a )	,)
        A_						:  Union[str, Any]          =				ACTaFN[activation]






  def        _a							(							self :       List[Any]	,_a :       Optional[Any] ):

        '''simple docstring'''




        A_						:  Any          =				hidden_state
        A_						:  List[str]          =				self.layer(_a )
        A_						:  Any          =				self.shortcut(_a )
        hidden_state += residual
        A_						:  int          =				self.activation(_a )
        return hidden_state







class 	__lowerCAmelCase		(							nn.Module    ):


  '''simple docstring'''







  def __init__(							self :       Optional[int]	,_a :       str	,_a :       str	,_a :       int	,_a :       Optional[Any] = 2	,_a :       List[Any] = 2	,):

        '''simple docstring'''




        super().__init__()

        A_						:  Optional[int]          =				ResNetBottleNeckLayer if config.layer_type == """bottleneck""" else ResNetBasicLayer

        A_						:  str          =				nn.Sequential(
            # downsampling is done in the first layer with stride of 2
            layer(_a	,_a	,stride=_a	,activation=config.hidden_act )	,*[layer(_a	,_a	,activation=config.hidden_act ) for _ in range(depth - 1 )]	,)






  def        _a							(							self :       Optional[int]	,_a :       Optional[int] ):

        '''simple docstring'''




        A_						:  Optional[int]          =				input
        for layer in self.layers:
              A_						:  str          =				layer(_a )
        return hidden_state







class 	__lowerCAmelCase		(							nn.Module    ):


  '''simple docstring'''







  def __init__(							self :       Tuple	,_a :       str ):

        '''simple docstring'''




        super().__init__()
        A_						:  Optional[int]          =				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(
            ResNetStage(
                _a	,config.embedding_size	,config.hidden_sizes[0]	,stride=2 if config.downsample_in_first_stage else 1	,depth=config.depths[0]	,) )
        A_						:  str          =				zip(config.hidden_sizes	,config.hidden_sizes[1:] )
        for (in_channels, out_channels), depth in zip(_a	,config.depths[1:] ):
              self.stages.append(ResNetStage(_a	,_a	,_a	,depth=_a ) )






  def        _a							(							self :       Tuple	,_a :       Optional[Any]	,_a :       Optional[Any] = False	,_a :       Tuple = True ):

        '''simple docstring'''




        A_						:  Optional[Any]          =				() if output_hidden_states else None

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

              A_						:  Tuple          =				stage_module(_a )

        if output_hidden_states:
              A_						:  int          =				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 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  a_  					=							ResNetConfig
  a_  					=							"""resnet"""
  a_  					=							"""pixel_values"""
  a_  					=							True






  def        _a							(							self :       List[Any]	,_a :       int ):

        '''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        _a							(							self :       str	,_a :       List[Any]	,_a :       Tuple=False ):

        '''simple docstring'''




        if isinstance(_a	,_a ):
              A_						:  Tuple          =				value







__magic_name__			=      r'\n    This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass. Use it\n    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 ([`ResNetConfig`]): 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'

__magic_name__			=      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            [`ConvNextImageProcessor.__call__`] for details.\n\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'



@add_start_docstrings(
    """The bare ResNet model outputting raw features without any specific head on top."""  , __SCREAMING_SNAKE_CASE  , )
class 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  def __init__(							self :       List[str]	,_a :       Dict ):

        '''simple docstring'''




        super().__init__(_a )
        A_						:  str          =				config
        A_						:  Optional[int]          =				ResNetEmbeddings(_a )
        A_						:  Union[str, Any]          =				ResNetEncoder(_a )
        A_						:  str          =				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        _a							(							self :       str	,_a :       str	,_a :       str = None	,_a :       Optional[int] = None ):

        '''simple docstring'''




        A_						:  List[Any]          =				(
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        A_						:  int          =				return_dict if return_dict is not None else self.config.use_return_dict

        A_						:  List[Any]          =				self.embedder(_a )

        A_						:  List[Any]          =				self.encoder(
            _a	,output_hidden_states=_a	,return_dict=_a )

        A_						:  str          =				encoder_outputs[0]

        A_						:  Optional[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(
    """
    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    """  , __SCREAMING_SNAKE_CASE  , )
class 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  def __init__(							self :       Dict	,_a :       Union[str, Any] ):

        '''simple docstring'''




        super().__init__(_a )
        A_						:  Dict          =				config.num_labels
        A_						:  List[Any]          =				ResNetModel(_a )
        # classification head
        A_						:  Optional[Any]          =				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        _a							(							self :       Union[str, Any]	,_a :       Union[str, Any] = None	,_a :       Optional[int] = None	,_a :       List[str] = None	,_a :       str = None	,):

        '''simple docstring'''




        A_						:  Any          =				return_dict if return_dict is not None else self.config.use_return_dict

        A_						:  List[str]          =				self.resnet(_a	,output_hidden_states=_a	,return_dict=_a )

        A_						:  List[str]          =				outputs.pooler_output if return_dict else outputs[1]

        A_						:  str          =				self.classifier(_a )

        A_						:  int          =				None

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

        if not return_dict:
              A_						:  List[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 )







@add_start_docstrings(
    """
    ResNet backbone, to be used with frameworks like DETR and MaskFormer.
    """  , __SCREAMING_SNAKE_CASE  , )
class 	__lowerCAmelCase		(							__SCREAMING_SNAKE_CASE  , __SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  def __init__(							self :       Union[str, Any]	,_a :       int ):

        '''simple docstring'''




        super().__init__(_a )
        super()._init_backbone(_a )

        A_						:  List[str]          =				[config.embedding_size] + config.hidden_sizes
        A_						:  Tuple          =				ResNetEmbeddings(_a )
        A_						:  Optional[Any]          =				ResNetEncoder(_a )

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






  @add_start_docstrings_to_model_forward(_a )
  @replace_return_docstrings(output_type=_a	,config_class=_CONFIG_FOR_DOC )
  def        _a							(							self :       str	,_a :       Any	,_a :       List[Any] = None	,_a :       Optional[Any] = None ):

        '''simple docstring'''




        A_						:  Optional[int]          =				return_dict if return_dict is not None else self.config.use_return_dict
        A_						:  str          =				(
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )

        A_						:  List[Any]          =				self.embedder(_a )

        A_						:  List[str]          =				self.encoder(_a	,output_hidden_states=_a	,return_dict=_a )

        A_						:  Optional[int]          =				outputs.hidden_states

        A_						:  int          =				()
        for idx, stage in enumerate(self.stage_names ):
              if stage in self.out_features:
                    feature_maps += (hidden_states[idx],)

        if not return_dict:
              A_						:  Tuple          =				(feature_maps,)
              if output_hidden_states:
                    output += (outputs.hidden_states,)
              return output

        return BackboneOutput(
            feature_maps=_a	,hidden_states=outputs.hidden_states if output_hidden_states else None	,attentions=_a	,)




'''simple docstring'''


from ..utils import DummyObject, requires_backends



class 	__lowerCAmelCase		(							metaclass=__SCREAMING_SNAKE_CASE    ):


  '''simple docstring'''







  a_  					=							["""torch""", """torchsde"""]






  def __init__(							self :       Any	,*_a :       Union[str, Any]	,**_a :       Optional[int] ):

        '''simple docstring'''




        requires_backends(self	,["""torch""", """torchsde"""] )






  @classmethod
  def        _a							(							cls :       Optional[int]	,*_a :       List[Any]	,**_a :       Any ):

        '''simple docstring'''




        requires_backends(cls	,["""torch""", """torchsde"""] )






  @classmethod
  def        _a							(							cls :       List[Any]	,*_a :       Tuple	,**_a :       Union[str, Any] ):

        '''simple docstring'''




        requires_backends(cls	,["""torch""", """torchsde"""] )
