
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


a__							:	int  						=			logging.get_logger(__name__)

# General docstring
a__							:	Union[str, Any]  						=			'''ResNetConfig'''

# Base docstring
a__							:	Tuple  						=			'''microsoft/resnet-50'''
a__							:	str  						=			[1, 2_048, 7, 7]

# Image classification docstring
a__							:	Optional[int]  						=			'''microsoft/resnet-50'''
a__							:	Optional[int]  						=			'''tiger cat'''

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






class   a_    (       nn.Module				):



       """simple docstring"""






       def __init__(						self							,    _lowerCamelCase							,    _lowerCamelCase							,    _lowerCamelCase = 3							,    _lowerCamelCase = 1							,    _lowerCamelCase = "relu"					) ->Any:
           super().__init__()
           SCREAMING_SNAKE_CASE							:							int								=      nn.Convad(
               _lowerCamelCase							,    _lowerCamelCase							,    kernel_size=_lowerCamelCase							,    stride=_lowerCamelCase							,    padding=kernel_size // 2							,    bias=_lowerCamelCase					)
           SCREAMING_SNAKE_CASE							:							str								=      nn.BatchNormad(_lowerCamelCase					)
           SCREAMING_SNAKE_CASE							:							Optional[int]								=      ACTaFN[activation] if activation is not None else nn.Identity()






       def      __lowerCAmelCase			(						self							,    _lowerCamelCase					) ->Tensor:
           SCREAMING_SNAKE_CASE							:							int								=      self.convolution(_lowerCamelCase					)
           SCREAMING_SNAKE_CASE							:							Optional[Any]								=      self.normalization(_lowerCamelCase					)
           SCREAMING_SNAKE_CASE							:							List[str]								=      self.activation(_lowerCamelCase					)
           return hidden_state






class   a_    (       nn.Module				):



       """simple docstring"""






       def __init__(						self							,    _lowerCamelCase					) ->str:
           super().__init__()
           SCREAMING_SNAKE_CASE							:							Union[str, Any]								=      ResNetConvLayer(
               config.num_channels							,    config.embedding_size							,    kernel_size=7							,    stride=2							,    activation=config.hidden_act					)
           SCREAMING_SNAKE_CASE							:							Union[str, Any]								=      nn.MaxPoolad(kernel_size=3							,    stride=2							,    padding=1					)
           SCREAMING_SNAKE_CASE							:							str								=      config.num_channels






       def      __lowerCAmelCase			(						self							,    _lowerCamelCase					) ->Tensor:
           SCREAMING_SNAKE_CASE							:							List[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							:							Any								=      self.embedder(_lowerCamelCase					)
           SCREAMING_SNAKE_CASE							:							int								=      self.pooler(_lowerCamelCase					)
           return embedding






class   a_    (       nn.Module				):



       """simple docstring"""






       def __init__(						self							,    _lowerCamelCase							,    _lowerCamelCase							,    _lowerCamelCase = 2					) ->Dict:
           super().__init__()
           SCREAMING_SNAKE_CASE							:							List[str]								=      nn.Convad(_lowerCamelCase							,    _lowerCamelCase							,    kernel_size=1							,    stride=_lowerCamelCase							,    bias=_lowerCamelCase					)
           SCREAMING_SNAKE_CASE							:							Tuple								=      nn.BatchNormad(_lowerCamelCase					)






       def      __lowerCAmelCase			(						self							,    _lowerCamelCase					) ->Tensor:
           SCREAMING_SNAKE_CASE							:							List[Any]								=      self.convolution(_lowerCamelCase					)
           SCREAMING_SNAKE_CASE							:							List[str]								=      self.normalization(_lowerCamelCase					)
           return hidden_state






class   a_    (       nn.Module				):



       """simple docstring"""






       def __init__(						self							,    _lowerCamelCase							,    _lowerCamelCase							,    _lowerCamelCase = 1							,    _lowerCamelCase = "relu"					) ->Optional[Any]:
           super().__init__()
           SCREAMING_SNAKE_CASE							:							Any								=      in_channels != out_channels or stride != 1
           SCREAMING_SNAKE_CASE							:							Optional[Any]								=      (
               ResNetShortCut(_lowerCamelCase							,    _lowerCamelCase							,    stride=_lowerCamelCase					) if should_apply_shortcut else nn.Identity()
           )
           SCREAMING_SNAKE_CASE							:							Optional[int]								=      nn.Sequential(
               ResNetConvLayer(_lowerCamelCase							,    _lowerCamelCase							,    stride=_lowerCamelCase					)							,    ResNetConvLayer(_lowerCamelCase							,    _lowerCamelCase							,    activation=_lowerCamelCase					)							,    )
           SCREAMING_SNAKE_CASE							:							Any								=      ACTaFN[activation]






       def      __lowerCAmelCase			(						self							,    _lowerCamelCase					) ->List[str]:
           SCREAMING_SNAKE_CASE							:							str								=      hidden_state
           SCREAMING_SNAKE_CASE							:							int								=      self.layer(_lowerCamelCase					)
           SCREAMING_SNAKE_CASE							:							Optional[Any]								=      self.shortcut(_lowerCamelCase					)
           hidden_state += residual
           SCREAMING_SNAKE_CASE							:							Dict								=      self.activation(_lowerCamelCase					)
           return hidden_state






class   a_    (       nn.Module				):



       """simple docstring"""






       def __init__(						self							,    _lowerCamelCase							,    _lowerCamelCase							,    _lowerCamelCase = 1							,    _lowerCamelCase = "relu"							,    _lowerCamelCase = 4					) ->Any:
           super().__init__()
           SCREAMING_SNAKE_CASE							:							Tuple								=      in_channels != out_channels or stride != 1
           SCREAMING_SNAKE_CASE							:							List[Any]								=      out_channels // reduction
           SCREAMING_SNAKE_CASE							:							List[Any]								=      (
               ResNetShortCut(_lowerCamelCase							,    _lowerCamelCase							,    stride=_lowerCamelCase					) if should_apply_shortcut else nn.Identity()
           )
           SCREAMING_SNAKE_CASE							:							Any								=      nn.Sequential(
               ResNetConvLayer(_lowerCamelCase							,    _lowerCamelCase							,    kernel_size=1					)							,    ResNetConvLayer(_lowerCamelCase							,    _lowerCamelCase							,    stride=_lowerCamelCase					)							,    ResNetConvLayer(_lowerCamelCase							,    _lowerCamelCase							,    kernel_size=1							,    activation=_lowerCamelCase					)							,    )
           SCREAMING_SNAKE_CASE							:							Optional[int]								=      ACTaFN[activation]






       def      __lowerCAmelCase			(						self							,    _lowerCamelCase					) ->Dict:
           SCREAMING_SNAKE_CASE							:							Union[str, Any]								=      hidden_state
           SCREAMING_SNAKE_CASE							:							List[Any]								=      self.layer(_lowerCamelCase					)
           SCREAMING_SNAKE_CASE							:							Optional[Any]								=      self.shortcut(_lowerCamelCase					)
           hidden_state += residual
           SCREAMING_SNAKE_CASE							:							List[Any]								=      self.activation(_lowerCamelCase					)
           return hidden_state






class   a_    (       nn.Module				):



       """simple docstring"""






       def __init__(						self							,    _lowerCamelCase							,    _lowerCamelCase							,    _lowerCamelCase							,    _lowerCamelCase = 2							,    _lowerCamelCase = 2							,    ) ->List[Any]:
           super().__init__()

           SCREAMING_SNAKE_CASE							:							List[str]								=      ResNetBottleNeckLayer if config.layer_type == '''bottleneck''' else ResNetBasicLayer

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






       def      __lowerCAmelCase			(						self							,    _lowerCamelCase					) ->Tensor:
           SCREAMING_SNAKE_CASE							:							Any								=      input
           for layer in self.layers:
               SCREAMING_SNAKE_CASE							:							Optional[Any]								=      layer(_lowerCamelCase					)
           return hidden_state






class   a_    (       nn.Module				):



       """simple docstring"""






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






       def      __lowerCAmelCase			(						self							,    _lowerCamelCase							,    _lowerCamelCase = False							,    _lowerCamelCase = True					) ->BaseModelOutputWithNoAttention:
           SCREAMING_SNAKE_CASE							:							Tuple								=      () if output_hidden_states else None

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

               SCREAMING_SNAKE_CASE							:							List[Any]								=      stage_module(_lowerCamelCase					)

           if output_hidden_states:
               SCREAMING_SNAKE_CASE							:							Union[str, Any]								=      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=_lowerCamelCase							,    hidden_states=_lowerCamelCase							,    )






class   a_    (       a__				):



       """simple docstring"""
       __SCREAMING_SNAKE_CASE    : str		=   ResNetConfig
       __SCREAMING_SNAKE_CASE    : Dict		=   'resnet'
       __SCREAMING_SNAKE_CASE    : int		=   'pixel_values'
       __SCREAMING_SNAKE_CASE    : Dict		=   True






       def      __lowerCAmelCase			(						self							,    _lowerCamelCase					) ->Union[str, Any]:
           if isinstance(_lowerCamelCase							,    nn.Convad					):
               nn.init.kaiming_normal_(module.weight							,    mode='''fan_out'''							,    nonlinearity='''relu'''					)
           elif isinstance(_lowerCamelCase							,    (nn.BatchNormad, nn.GroupNorm)					):
               nn.init.constant_(module.weight							,    1					)
               nn.init.constant_(module.bias							,    0					)






       def      __lowerCAmelCase			(						self							,    _lowerCamelCase							,    _lowerCamelCase=False					) ->Dict:
           if isinstance(_lowerCamelCase							,    _lowerCamelCase					):
               SCREAMING_SNAKE_CASE							:							Optional[int]								=      value





a__							:	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 ([`ResNetConfig`]): 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.
'''

a__							:	Any  						=			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 [`~utils.ModelOutput`] instead of a plain tuple.
'''






@add_start_docstrings(
    'The bare ResNet model outputting raw features without any specific head on top.'							,  a__							,  )
class   a_    (       a__				):



       """simple docstring"""






       def __init__(						self							,    _lowerCamelCase					) ->str:
           super().__init__(_lowerCamelCase					)
           SCREAMING_SNAKE_CASE							:							Any								=      config
           SCREAMING_SNAKE_CASE							:							int								=      ResNetEmbeddings(_lowerCamelCase					)
           SCREAMING_SNAKE_CASE							:							Dict								=      ResNetEncoder(_lowerCamelCase					)
           SCREAMING_SNAKE_CASE							:							List[str]								=      nn.AdaptiveAvgPoolad((1, 1)					)
           # Initialize weights and apply final processing
           self.post_init()






       @add_start_docstrings_to_model_forward(_lowerCamelCase					)
       @add_code_sample_docstrings(
           checkpoint=_CHECKPOINT_FOR_DOC							,    output_type=_lowerCamelCase							,    config_class=_CONFIG_FOR_DOC							,    modality='''vision'''							,    expected_output=_EXPECTED_OUTPUT_SHAPE							,    )
       def      __lowerCAmelCase			(						self							,    _lowerCamelCase							,    _lowerCamelCase = None							,    _lowerCamelCase = None					) ->BaseModelOutputWithPoolingAndNoAttention:
           SCREAMING_SNAKE_CASE							:							int								=      (
               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

           SCREAMING_SNAKE_CASE							:							Union[str, Any]								=      self.embedder(_lowerCamelCase					)

           SCREAMING_SNAKE_CASE							:							Any								=      self.encoder(
               _lowerCamelCase							,    output_hidden_states=_lowerCamelCase							,    return_dict=_lowerCamelCase					)

           SCREAMING_SNAKE_CASE							:							Optional[Any]								=      encoder_outputs[0]

           SCREAMING_SNAKE_CASE							:							Tuple								=      self.pooler(_lowerCamelCase					)

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

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






@add_start_docstrings(
    '\n    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    '							,  a__							,  )
class   a_    (       a__				):



       """simple docstring"""






       def __init__(						self							,    _lowerCamelCase					) ->int:
           super().__init__(_lowerCamelCase					)
           SCREAMING_SNAKE_CASE							:							Dict								=      config.num_labels
           SCREAMING_SNAKE_CASE							:							Optional[Any]								=      ResNetModel(_lowerCamelCase					)
           # classification head
           SCREAMING_SNAKE_CASE							:							Union[str, 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(_lowerCamelCase					)
       @add_code_sample_docstrings(
           checkpoint=_IMAGE_CLASS_CHECKPOINT							,    output_type=_lowerCamelCase							,    config_class=_CONFIG_FOR_DOC							,    expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT							,    )
       def      __lowerCAmelCase			(						self							,    _lowerCamelCase = None							,    _lowerCamelCase = None							,    _lowerCamelCase = None							,    _lowerCamelCase = None							,    ) ->ImageClassifierOutputWithNoAttention:
           SCREAMING_SNAKE_CASE							:							List[str]								=      return_dict if return_dict is not None else self.config.use_return_dict

           SCREAMING_SNAKE_CASE							:							Tuple								=      self.resnet(_lowerCamelCase							,    output_hidden_states=_lowerCamelCase							,    return_dict=_lowerCamelCase					)

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

           SCREAMING_SNAKE_CASE							:							List[str]								=      self.classifier(_lowerCamelCase					)

           SCREAMING_SNAKE_CASE							:							Dict								=      None

           if labels is not None:
               if self.config.problem_type is None:
                   if self.num_labels == 1:
                       SCREAMING_SNAKE_CASE							:							Optional[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							:							Optional[Any]								=      '''multi_label_classification'''
               if self.config.problem_type == "regression":
                   SCREAMING_SNAKE_CASE							:							Any								=      MSELoss()
                   if self.num_labels == 1:
                       SCREAMING_SNAKE_CASE							:							List[str]								=      loss_fct(logits.squeeze()							,    labels.squeeze()					)
                   else:
                       SCREAMING_SNAKE_CASE							:							Union[str, Any]								=      loss_fct(_lowerCamelCase							,    _lowerCamelCase					)
               elif self.config.problem_type == "single_label_classification":
                   SCREAMING_SNAKE_CASE							:							str								=      CrossEntropyLoss()
                   SCREAMING_SNAKE_CASE							:							int								=      loss_fct(logits.view(-1							,    self.num_labels					)							,    labels.view(-1					)					)
               elif self.config.problem_type == "multi_label_classification":
                   SCREAMING_SNAKE_CASE							:							Optional[Any]								=      BCEWithLogitsLoss()
                   SCREAMING_SNAKE_CASE							:							Union[str, Any]								=      loss_fct(_lowerCamelCase							,    _lowerCamelCase					)

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

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






@add_start_docstrings(
    '\n    ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n    '							,  a__							,  )
class   a_    (       a__							,  a__				):



       """simple docstring"""






       def __init__(						self							,    _lowerCamelCase					) ->Tuple:
           super().__init__(_lowerCamelCase					)
           super()._init_backbone(_lowerCamelCase					)

           SCREAMING_SNAKE_CASE							:							List[str]								=      [config.embedding_size] + config.hidden_sizes
           SCREAMING_SNAKE_CASE							:							Optional[Any]								=      ResNetEmbeddings(_lowerCamelCase					)
           SCREAMING_SNAKE_CASE							:							Optional[Any]								=      ResNetEncoder(_lowerCamelCase					)

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






       @add_start_docstrings_to_model_forward(_lowerCamelCase					)
       @replace_return_docstrings(output_type=_lowerCamelCase							,    config_class=_CONFIG_FOR_DOC					)
       def      __lowerCAmelCase			(						self							,    _lowerCamelCase							,    _lowerCamelCase = None							,    _lowerCamelCase = None					) ->BackboneOutput:
           SCREAMING_SNAKE_CASE							:							Dict								=      return_dict if return_dict is not None else self.config.use_return_dict
           SCREAMING_SNAKE_CASE							:							Union[str, Any]								=      (
               output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
           )

           SCREAMING_SNAKE_CASE							:							List[str]								=      self.embedder(_lowerCamelCase					)

           SCREAMING_SNAKE_CASE							:							str								=      self.encoder(_lowerCamelCase							,    output_hidden_states=_lowerCamelCase							,    return_dict=_lowerCamelCase					)

           SCREAMING_SNAKE_CASE							:							int								=      outputs.hidden_states

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

           if not return_dict:
               SCREAMING_SNAKE_CASE							:							Optional[Any]								=      (feature_maps,)
               if output_hidden_states:
                   output += (outputs.hidden_states,)
               return output

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




def 				UpperCAmelCase_					(							__snake_case     ,						__snake_case						)     ->			List[Any]:







 """simple docstring"""


 if b == 0:
  return 1
 if (b % 2) == 0:
  return actual_power(__snake_case     ,						int(b / 2						)						) * actual_power(__snake_case     ,						int(b / 2						)						)
 else:
  return a * actual_power(__snake_case     ,						int(b / 2						)						) * actual_power(__snake_case     ,						int(b / 2						)						)
def 				UpperCAmelCase_					(							__snake_case     ,						__snake_case						)     ->			float:







 """simple docstring"""


 if b < 0:
  return 1 / actual_power(__snake_case     ,						__snake_case						)
 return actual_power(__snake_case     ,						__snake_case						)


if __name__ == "__main__":
  print(power(-2, -3))

