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


__UpperCAmelCase					=logging.get_logger(__name__)

# General docstring
__UpperCAmelCase					="ResNetConfig"

# Base docstring
__UpperCAmelCase					="microsoft/resnet-50"
__UpperCAmelCase					=[1, 2_0_4_8, 7, 7]

# Image classification docstring
__UpperCAmelCase					="microsoft/resnet-50"
__UpperCAmelCase					="tiger cat"

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




class        a__ (  nn.Module					):






     def __init__(					self						:						str    ,							a						:						int    ,							a						:						int    ,							a						:						int = 3    ,							a						:						int = 1    ,							a						:						str = "relu"       ):





         """simple docstring"""



         super().__init__()
         __lowerCamelCase            =    nn.Convad(
             a    ,							a    ,							kernel_size=a    ,							stride=a    ,							padding=kernel_size // 2    ,							bias=a       )
         __lowerCamelCase            =    nn.BatchNormad(a       )
         __lowerCamelCase            =    ACTaFN[activation] if activation is not None else nn.Identity()






     def   SCREAMING_SNAKE_CASE__  (					self						:						List[str]    ,							a						:						Tensor       ):





         """simple docstring"""



         __lowerCamelCase            =    self.convolution(a       )
         __lowerCamelCase            =    self.normalization(a       )
         __lowerCamelCase            =    self.activation(a       )
         return hidden_state




class        a__ (  nn.Module					):






     def __init__(					self						:						str    ,							a						:						ResNetConfig       ):





         """simple docstring"""



         super().__init__()
         __lowerCamelCase            =    ResNetConvLayer(
             config.num_channels    ,							config.embedding_size    ,							kernel_size=7    ,							stride=2    ,							activation=config.hidden_act       )
         __lowerCamelCase            =    nn.MaxPoolad(kernel_size=3    ,							stride=2    ,							padding=1       )
         __lowerCamelCase            =    config.num_channels






     def   SCREAMING_SNAKE_CASE__  (					self						:						str    ,							a						:						Tensor       ):





         """simple docstring"""



         __lowerCamelCase            =    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.'''       )
         __lowerCamelCase            =    self.embedder(a       )
         __lowerCamelCase            =    self.pooler(a       )
         return embedding




class        a__ (  nn.Module					):






     def __init__(					self						:						Tuple    ,							a						:						int    ,							a						:						int    ,							a						:						int = 2       ):





         """simple docstring"""



         super().__init__()
         __lowerCamelCase            =    nn.Convad(a    ,							a    ,							kernel_size=1    ,							stride=a    ,							bias=a       )
         __lowerCamelCase            =    nn.BatchNormad(a       )






     def   SCREAMING_SNAKE_CASE__  (					self						:						Union[str, Any]    ,							a						:						Tensor       ):





         """simple docstring"""



         __lowerCamelCase            =    self.convolution(a       )
         __lowerCamelCase            =    self.normalization(a       )
         return hidden_state




class        a__ (  nn.Module					):






     def __init__(					self						:						Union[str, Any]    ,							a						:						int    ,							a						:						int    ,							a						:						int = 1    ,							a						:						str = "relu"       ):





         """simple docstring"""



         super().__init__()
         __lowerCamelCase            =    in_channels != out_channels or stride != 1
         __lowerCamelCase            =    (
             ResNetShortCut(a    ,							a    ,							stride=a       ) if should_apply_shortcut else nn.Identity()
         )
         __lowerCamelCase            =    nn.Sequential(
             ResNetConvLayer(a    ,							a    ,							stride=a       )    ,							ResNetConvLayer(a    ,							a    ,							activation=a       )    ,							)
         __lowerCamelCase            =    ACTaFN[activation]






     def   SCREAMING_SNAKE_CASE__  (					self						:						str    ,							a						:						Optional[int]       ):





         """simple docstring"""



         __lowerCamelCase            =    hidden_state
         __lowerCamelCase            =    self.layer(a       )
         __lowerCamelCase            =    self.shortcut(a       )
         hidden_state += residual
         __lowerCamelCase            =    self.activation(a       )
         return hidden_state




class        a__ (  nn.Module					):






     def __init__(					self						:						Optional[int]    ,							a						:						int    ,							a						:						int    ,							a						:						int = 1    ,							a						:						str = "relu"    ,							a						:						int = 4       ):





         """simple docstring"""



         super().__init__()
         __lowerCamelCase            =    in_channels != out_channels or stride != 1
         __lowerCamelCase            =    out_channels // reduction
         __lowerCamelCase            =    (
             ResNetShortCut(a    ,							a    ,							stride=a       ) if should_apply_shortcut else nn.Identity()
         )
         __lowerCamelCase            =    nn.Sequential(
             ResNetConvLayer(a    ,							a    ,							kernel_size=1       )    ,							ResNetConvLayer(a    ,							a    ,							stride=a       )    ,							ResNetConvLayer(a    ,							a    ,							kernel_size=1    ,							activation=a       )    ,							)
         __lowerCamelCase            =    ACTaFN[activation]






     def   SCREAMING_SNAKE_CASE__  (					self						:						int    ,							a						:						List[Any]       ):





         """simple docstring"""



         __lowerCamelCase            =    hidden_state
         __lowerCamelCase            =    self.layer(a       )
         __lowerCamelCase            =    self.shortcut(a       )
         hidden_state += residual
         __lowerCamelCase            =    self.activation(a       )
         return hidden_state




class        a__ (  nn.Module					):






     def __init__(					self						:						List[Any]    ,							a						:						ResNetConfig    ,							a						:						int    ,							a						:						int    ,							a						:						int = 2    ,							a						:						int = 2    ,							):





         """simple docstring"""



         super().__init__()

         __lowerCamelCase            =    ResNetBottleNeckLayer if config.layer_type == '''bottleneck''' else ResNetBasicLayer

         __lowerCamelCase            =    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   SCREAMING_SNAKE_CASE__  (					self						:						Optional[Any]    ,							a						:						Tensor       ):





         """simple docstring"""



         __lowerCamelCase            =    input
         for layer in self.layers:
             __lowerCamelCase            =    layer(a       )
         return hidden_state




class        a__ (  nn.Module					):






     def __init__(					self						:						int    ,							a						:						ResNetConfig       ):





         """simple docstring"""



         super().__init__()
         __lowerCamelCase            =    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]    ,							)       )
         __lowerCamelCase            =    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   SCREAMING_SNAKE_CASE__  (					self						:						List[Any]    ,							a						:						Tensor    ,							a						:						bool = False    ,							a						:						bool = True       ):





         """simple docstring"""



         __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(a       )

         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 BaseModelOutputWithNoAttention(
             last_hidden_state=a    ,							hidden_states=a    ,							)




class        a__ (  UpperCAmelCase__					):
     lowerCamelCase    :	Optional[int]				=ResNetConfig
     lowerCamelCase    :	List[Any]				="resnet"
     lowerCamelCase    :	Optional[int]				="pixel_values"
     lowerCamelCase    :	int				=True






     def   SCREAMING_SNAKE_CASE__  (					self						:						Dict    ,							a						:						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   SCREAMING_SNAKE_CASE__  (					self						:						List[str]    ,							a						:						Optional[Any]    ,							a						:						List[Any]=False       ):





         """simple docstring"""



         if isinstance(a    ,							a       ):
             __lowerCamelCase            =    value
__UpperCAmelCase					=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"

__UpperCAmelCase					=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."				,  UpperCAmelCase__				,  )
class        a__ (  UpperCAmelCase__					):






     def __init__(					self						:						Optional[Any]    ,							a						:						List[str]       ):





         """simple docstring"""



         super().__init__(a       )
         __lowerCamelCase            =    config
         __lowerCamelCase            =    ResNetEmbeddings(a       )
         __lowerCamelCase            =    ResNetEncoder(a       )
         __lowerCamelCase            =    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   SCREAMING_SNAKE_CASE__  (					self						:						Any    ,							a						:						Tensor    ,							a						:						Optional[bool] = None    ,							a						:						Optional[bool] = None       ):





         """simple docstring"""



         __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(a       )

         __lowerCamelCase            =    self.encoder(
             a    ,							output_hidden_states=a    ,							return_dict=a       )

         __lowerCamelCase            =    encoder_outputs[0]

         __lowerCamelCase            =    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    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    "				,  UpperCAmelCase__				,  )
class        a__ (  UpperCAmelCase__					):






     def __init__(					self						:						Optional[Any]    ,							a						:						Dict       ):





         """simple docstring"""



         super().__init__(a       )
         __lowerCamelCase            =    config.num_labels
         __lowerCamelCase            =    ResNetModel(a       )
         # classification head
         __lowerCamelCase            =    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   SCREAMING_SNAKE_CASE__  (					self						:						int    ,							a						:						Optional[torch.FloatTensor] = None    ,							a						:						Optional[torch.LongTensor] = None    ,							a						:						Optional[bool] = None    ,							a						:						Optional[bool] = None    ,							):





         """simple docstring"""



         __lowerCamelCase            =    return_dict if return_dict is not None else self.config.use_return_dict

         __lowerCamelCase            =    self.resnet(a    ,							output_hidden_states=a    ,							return_dict=a       )

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

         __lowerCamelCase            =    self.classifier(a       )

         __lowerCamelCase            =    None

         if labels is not None:
             if self.config.problem_type is None:
                 if self.num_labels == 1:
                     __lowerCamelCase            =    '''regression'''
                 elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
                     __lowerCamelCase            =    '''single_label_classification'''
                 else:
                     __lowerCamelCase            =    '''multi_label_classification'''
             if self.config.problem_type == "regression":
                 __lowerCamelCase            =    MSELoss()
                 if self.num_labels == 1:
                     __lowerCamelCase            =    loss_fct(logits.squeeze()    ,							labels.squeeze()       )
                 else:
                     __lowerCamelCase            =    loss_fct(a    ,							a       )
             elif self.config.problem_type == "single_label_classification":
                 __lowerCamelCase            =    CrossEntropyLoss()
                 __lowerCamelCase            =    loss_fct(logits.view(-1    ,							self.num_labels       )    ,							labels.view(-1       )       )
             elif self.config.problem_type == "multi_label_classification":
                 __lowerCamelCase            =    BCEWithLogitsLoss()
                 __lowerCamelCase            =    loss_fct(a    ,							a       )

         if not return_dict:
             __lowerCamelCase            =    (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(
    "\n    ResNet backbone, to be used with frameworks like DETR and MaskFormer.\n    "				,  UpperCAmelCase__				,  )
class        a__ (  UpperCAmelCase__				,  UpperCAmelCase__					):






     def __init__(					self						:						Optional[int]    ,							a						:						str       ):





         """simple docstring"""



         super().__init__(a       )
         super()._init_backbone(a       )

         __lowerCamelCase            =    [config.embedding_size] + config.hidden_sizes
         __lowerCamelCase            =    ResNetEmbeddings(a       )
         __lowerCamelCase            =    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   SCREAMING_SNAKE_CASE__  (					self						:						Optional[int]    ,							a						:						Tensor    ,							a						:						Optional[bool] = None    ,							a						:						Optional[bool] = None       ):





         """simple docstring"""



         __lowerCamelCase            =    return_dict if return_dict is not None else self.config.use_return_dict
         __lowerCamelCase            =    (
             output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         )

         __lowerCamelCase            =    self.embedder(a       )

         __lowerCamelCase            =    self.encoder(a    ,							output_hidden_states=a    ,							return_dict=a       )

         __lowerCamelCase            =    outputs.hidden_states

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

         if not return_dict:
             __lowerCamelCase            =    (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'''




def __lowerCAmelCase					(				UpperCamelCase__							,    UpperCamelCase__							)      ->       float:
    return base * power(UpperCamelCase__							,    (exponent - 1)							) if exponent else 1


if __name__ == "__main__":
  print("Raise base to the power of exponent using recursion...")
  __UpperCAmelCase					=int(input("Enter the base: ").strip())
  __UpperCAmelCase					=int(input("Enter the exponent: ").strip())
  __UpperCAmelCase					=power(base, abs(exponent))
  if exponent < 0:  # power() does not properly deal w/ negative exponents
    __UpperCAmelCase					=1 / result
  print(f'{base} to the power of {exponent} is {result}')
