





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


_snake_case           =			logging.get_logger(__name__)

# General docstring
_snake_case           =			"""ResNetConfig"""

# Base docstring
_snake_case           =			"""microsoft/resnet-50"""
_snake_case           =			[1, 2048, 7, 7]

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

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





class  lowerCAmelCase							(       nn.Module ):







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






     '''simple docstring'''





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







  def   UpperCAmelCase					(      self  :Optional[Any]   ,							_lowercase  :Tensor ):






     '''simple docstring'''





     lowercase__			       =  self.convolution(_lowercase )
     lowercase__			       =  self.normalization(_lowercase )
     lowercase__			       =  self.activation(_lowercase )
     return hidden_state





class  lowerCAmelCase							(       nn.Module ):







  def __init__(      self  :Optional[Any]   ,							_lowercase  :ResNetConfig ):






     '''simple docstring'''





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







  def   UpperCAmelCase					(      self  :Optional[Any]   ,							_lowercase  :Tensor ):






     '''simple docstring'''





     lowercase__			       =  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." )
     lowercase__			       =  self.embedder(_lowercase )
     lowercase__			       =  self.pooler(_lowercase )
     return embedding





class  lowerCAmelCase							(       nn.Module ):







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






     '''simple docstring'''





     super().__init__()
     lowercase__			       =  nn.Convad(_lowercase   ,							_lowercase   ,							kernel_size=1   ,							stride=_lowercase   ,							bias=_lowercase )
     lowercase__			       =  nn.BatchNormad(_lowercase )







  def   UpperCAmelCase					(      self  :List[str]   ,							_lowercase  :Tensor ):






     '''simple docstring'''





     lowercase__			       =  self.convolution(_lowercase )
     lowercase__			       =  self.normalization(_lowercase )
     return hidden_state





class  lowerCAmelCase							(       nn.Module ):







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






     '''simple docstring'''





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







  def   UpperCAmelCase					(      self  :int   ,							_lowercase  :Tuple ):






     '''simple docstring'''





     lowercase__			       =  hidden_state
     lowercase__			       =  self.layer(_lowercase )
     lowercase__			       =  self.shortcut(_lowercase )
     hidden_state += residual
     lowercase__			       =  self.activation(_lowercase )
     return hidden_state





class  lowerCAmelCase							(       nn.Module ):







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






     '''simple docstring'''





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







  def   UpperCAmelCase					(      self  :int   ,							_lowercase  :Tuple ):






     '''simple docstring'''





     lowercase__			       =  hidden_state
     lowercase__			       =  self.layer(_lowercase )
     lowercase__			       =  self.shortcut(_lowercase )
     hidden_state += residual
     lowercase__			       =  self.activation(_lowercase )
     return hidden_state





class  lowerCAmelCase							(       nn.Module ):







  def __init__(      self  :List[str]   ,							_lowercase  :ResNetConfig   ,							_lowercase  :int   ,							_lowercase  :int   ,							_lowercase  :int = 2   ,							_lowercase  :int = 2   ,							):






     '''simple docstring'''





     super().__init__()

     lowercase__			       =  ResNetBottleNeckLayer if config.layer_type == "bottleneck" else ResNetBasicLayer

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







  def   UpperCAmelCase					(      self  :int   ,							_lowercase  :Tensor ):






     '''simple docstring'''





     lowercase__			       =  input
     for layer in self.layers:
        lowercase__			       =  layer(_lowercase )
     return hidden_state





class  lowerCAmelCase							(       nn.Module ):







  def __init__(      self  :List[str]   ,							_lowercase  :ResNetConfig ):






     '''simple docstring'''





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







  def   UpperCAmelCase					(      self  :Optional[Any]   ,							_lowercase  :Tensor   ,							_lowercase  :bool = False   ,							_lowercase  :bool = True ):






     '''simple docstring'''





     lowercase__			       =  () if output_hidden_states else None

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

        lowercase__			       =  stage_module(_lowercase )

     if output_hidden_states:
        lowercase__			       =  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=_lowercase   ,							hidden_states=_lowercase   ,							)





class  lowerCAmelCase							(       lowercase_ ):
  __lowerCamelCase		=      ResNetConfig
  __lowerCamelCase		=      'resnet'
  __lowerCamelCase		=      'pixel_values'
  __lowerCamelCase		=      True







  def   UpperCAmelCase					(      self  :Optional[int]   ,							_lowercase  :Optional[Any] ):






     '''simple docstring'''





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







  def   UpperCAmelCase					(      self  :Optional[Any]   ,							_lowercase  :List[Any]   ,							_lowercase  :str=False ):






     '''simple docstring'''





     if isinstance(_lowercase   ,							_lowercase ):
        lowercase__			       =  value
_snake_case           =			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.
"""

_snake_case           =			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.'							,							lowercase_							,							)
class  lowerCAmelCase							(       lowercase_ ):







  def __init__(      self  :List[str]   ,							_lowercase  :str ):






     '''simple docstring'''





     super().__init__(_lowercase )
     lowercase__			       =  config
     lowercase__			       =  ResNetEmbeddings(_lowercase )
     lowercase__			       =  ResNetEncoder(_lowercase )
     lowercase__			       =  nn.AdaptiveAvgPoolad((1, 1) )
     # Initialize weights and apply final processing
     self.post_init()







  @add_start_docstrings_to_model_forward(_lowercase )
  @add_code_sample_docstrings(
      checkpoint=_CHECKPOINT_FOR_DOC   ,							output_type=_lowercase   ,							config_class=_CONFIG_FOR_DOC   ,							modality="vision"   ,							expected_output=_EXPECTED_OUTPUT_SHAPE   ,							)
  def   UpperCAmelCase					(      self  :Tuple   ,							_lowercase  :Tensor   ,							_lowercase  :Optional[bool] = None   ,							_lowercase  :Optional[bool] = None ):






     '''simple docstring'''





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

     lowercase__			       =  self.embedder(_lowercase )

     lowercase__			       =  self.encoder(
         _lowercase   ,							output_hidden_states=_lowercase   ,							return_dict=_lowercase )

     lowercase__			       =  encoder_outputs[0]

     lowercase__			       =  self.pooler(_lowercase )

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

     return BaseModelOutputWithPoolingAndNoAttention(
         last_hidden_state=_lowercase   ,							pooler_output=_lowercase   ,							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    '							,							lowercase_							,							)
class  lowerCAmelCase							(       lowercase_ ):







  def __init__(      self  :Optional[Any]   ,							_lowercase  :Tuple ):






     '''simple docstring'''





     super().__init__(_lowercase )
     lowercase__			       =  config.num_labels
     lowercase__			       =  ResNetModel(_lowercase )
     # classification head
     lowercase__			       =  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(_lowercase )
  @add_code_sample_docstrings(
      checkpoint=_IMAGE_CLASS_CHECKPOINT   ,							output_type=_lowercase   ,							config_class=_CONFIG_FOR_DOC   ,							expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT   ,							)
  def   UpperCAmelCase					(      self  :List[str]   ,							_lowercase  :Optional[torch.FloatTensor] = None   ,							_lowercase  :Optional[torch.LongTensor] = None   ,							_lowercase  :Optional[bool] = None   ,							_lowercase  :Optional[bool] = None   ,							):






     '''simple docstring'''





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

     lowercase__			       =  self.resnet(_lowercase   ,							output_hidden_states=_lowercase   ,							return_dict=_lowercase )

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

     lowercase__			       =  self.classifier(_lowercase )

     lowercase__			       =  None

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

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

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





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







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






     '''simple docstring'''





     super().__init__(_lowercase )
     super()._init_backbone(_lowercase )

     lowercase__			       =  [config.embedding_size] + config.hidden_sizes
     lowercase__			       =  ResNetEmbeddings(_lowercase )
     lowercase__			       =  ResNetEncoder(_lowercase )

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







  @add_start_docstrings_to_model_forward(_lowercase )
  @replace_return_docstrings(output_type=_lowercase   ,							config_class=_CONFIG_FOR_DOC )
  def   UpperCAmelCase					(      self  :Optional[int]   ,							_lowercase  :Tensor   ,							_lowercase  :Optional[bool] = None   ,							_lowercase  :Optional[bool] = None ):






     '''simple docstring'''





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

     lowercase__			       =  self.embedder(_lowercase )

     lowercase__			       =  self.encoder(_lowercase   ,							output_hidden_states=_lowercase   ,							return_dict=_lowercase )

     lowercase__			       =  outputs.hidden_states

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

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

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













from __future__ import annotations


def _A       (   __magic_name__  , __magic_name__	):
   lowercase__			       =  []
   create_all_state(1  , __magic_name__  , __magic_name__  , []  , __magic_name__	)
   return result


def _A       (   __magic_name__  , __magic_name__  , __magic_name__  , __magic_name__  , __magic_name__  , ):
   if level == 0:
      total_list.append(current_list[:]	)
      return

   for i in range(__magic_name__  , total_number - level + 2	):
      current_list.append(__magic_name__	)
      create_all_state(i + 1  , __magic_name__  , level - 1  , __magic_name__  , __magic_name__	)
      current_list.pop()


def _A       (   __magic_name__	):
   for i in total_list:
      print(*__magic_name__	)


if __name__ == "__main__":
  _snake_case           =			4
  _snake_case           =			2
  _snake_case           =			generate_all_combinations(n, k)
  print_all_state(total_list)






