
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_											=						logging.get_logger(__name__)

# General docstring
a_											=						"""ResNetConfig"""

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

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

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






class    UpperCAmelCase_				(	nn.Module					):





 def __init__(    self ,       lowercase_ ,       lowercase_ ,       lowercase_ = 3 ,       lowercase_ = 1 ,       lowercase_ = "relu"):
     super().__init__()
     snake_case_ :    Union[str, Any]     			=						nn.Convad(
         lowercase_ ,       lowercase_ ,       kernel_size=lowercase_ ,       stride=lowercase_ ,       padding=kernel_size // 2 ,       bias=lowercase_)
     snake_case_ :    Dict     			=						nn.BatchNormad(lowercase_)
     snake_case_ :    Dict     			=						ACTaFN[activation] if activation is not None else nn.Identity()





 def        snake_case__		(    self ,       lowercase_):
     snake_case_ :    str     			=						self.convolution(lowercase_)
     snake_case_ :    Union[str, Any]     			=						self.normalization(lowercase_)
     snake_case_ :    Optional[Any]     			=						self.activation(lowercase_)
     return hidden_state






class    UpperCAmelCase_				(	nn.Module					):





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





 def        snake_case__		(    self ,       lowercase_):
     snake_case_ :    Optional[int]     			=						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.")
     snake_case_ :    Optional[Any]     			=						self.embedder(lowercase_)
     snake_case_ :    int     			=						self.pooler(lowercase_)
     return embedding






class    UpperCAmelCase_				(	nn.Module					):





 def __init__(    self ,       lowercase_ ,       lowercase_ ,       lowercase_ = 2):
     super().__init__()
     snake_case_ :    List[Any]     			=						nn.Convad(lowercase_ ,       lowercase_ ,       kernel_size=1 ,       stride=lowercase_ ,       bias=lowercase_)
     snake_case_ :    Any     			=						nn.BatchNormad(lowercase_)





 def        snake_case__		(    self ,       lowercase_):
     snake_case_ :    Union[str, Any]     			=						self.convolution(lowercase_)
     snake_case_ :    List[str]     			=						self.normalization(lowercase_)
     return hidden_state






class    UpperCAmelCase_				(	nn.Module					):





 def __init__(    self ,       lowercase_ ,       lowercase_ ,       lowercase_ = 1 ,       lowercase_ = "relu"):
     super().__init__()
     snake_case_ :    str     			=						in_channels != out_channels or stride != 1
     snake_case_ :    Optional[Any]     			=						(
         ResNetShortCut(lowercase_ ,       lowercase_ ,       stride=lowercase_) if should_apply_shortcut else nn.Identity()
     )
     snake_case_ :    Any     			=						nn.Sequential(
         ResNetConvLayer(lowercase_ ,       lowercase_ ,       stride=lowercase_) ,       ResNetConvLayer(lowercase_ ,       lowercase_ ,       activation=lowercase_) ,       )
     snake_case_ :    List[Any]     			=						ACTaFN[activation]





 def        snake_case__		(    self ,       lowercase_):
     snake_case_ :    Dict     			=						hidden_state
     snake_case_ :    int     			=						self.layer(lowercase_)
     snake_case_ :    Tuple     			=						self.shortcut(lowercase_)
     hidden_state += residual
     snake_case_ :    Dict     			=						self.activation(lowercase_)
     return hidden_state






class    UpperCAmelCase_				(	nn.Module					):





 def __init__(    self ,       lowercase_ ,       lowercase_ ,       lowercase_ = 1 ,       lowercase_ = "relu" ,       lowercase_ = 4):
     super().__init__()
     snake_case_ :    Union[str, Any]     			=						in_channels != out_channels or stride != 1
     snake_case_ :    List[str]     			=						out_channels // reduction
     snake_case_ :    Tuple     			=						(
         ResNetShortCut(lowercase_ ,       lowercase_ ,       stride=lowercase_) if should_apply_shortcut else nn.Identity()
     )
     snake_case_ :    List[str]     			=						nn.Sequential(
         ResNetConvLayer(lowercase_ ,       lowercase_ ,       kernel_size=1) ,       ResNetConvLayer(lowercase_ ,       lowercase_ ,       stride=lowercase_) ,       ResNetConvLayer(lowercase_ ,       lowercase_ ,       kernel_size=1 ,       activation=lowercase_) ,       )
     snake_case_ :    Union[str, Any]     			=						ACTaFN[activation]





 def        snake_case__		(    self ,       lowercase_):
     snake_case_ :    Optional[Any]     			=						hidden_state
     snake_case_ :    str     			=						self.layer(lowercase_)
     snake_case_ :    Any     			=						self.shortcut(lowercase_)
     hidden_state += residual
     snake_case_ :    str     			=						self.activation(lowercase_)
     return hidden_state






class    UpperCAmelCase_				(	nn.Module					):





 def __init__(    self ,       lowercase_ ,       lowercase_ ,       lowercase_ ,       lowercase_ = 2 ,       lowercase_ = 2 ,       ):
     super().__init__()

     snake_case_ :    Union[str, Any]     			=						ResNetBottleNeckLayer if config.layer_type == "bottleneck" else ResNetBasicLayer

     snake_case_ :    str     			=						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        snake_case__		(    self ,       lowercase_):
     snake_case_ :    List[Any]     			=						input
     for layer in self.layers:
         snake_case_ :    List[str]     			=						layer(lowercase_)
     return hidden_state






class    UpperCAmelCase_				(	nn.Module					):





 def __init__(    self ,       lowercase_):
     super().__init__()
     snake_case_ :    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(
         ResNetStage(
             lowercase_ ,       config.embedding_size ,       config.hidden_sizes[0] ,       stride=2 if config.downsample_in_first_stage else 1 ,       depth=config.depths[0] ,       ))
     snake_case_ :    Optional[int]     			=						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        snake_case__		(    self ,       lowercase_ ,       lowercase_ = False ,       lowercase_ = True):
     snake_case_ :    str     			=						() if output_hidden_states else None

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

         snake_case_ :    Any     			=						stage_module(lowercase_)

     if output_hidden_states:
         snake_case_ :    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=lowercase_ ,       hidden_states=lowercase_ ,       )






class    UpperCAmelCase_				(	snake_case_					):
 UpperCAmelCase_		    =						ResNetConfig
 UpperCAmelCase_		    =						"""resnet"""
 UpperCAmelCase_		    =						"""pixel_values"""
 UpperCAmelCase_		    =						True





 def        snake_case__		(    self ,       lowercase_):
     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        snake_case__		(    self ,       lowercase_ ,       lowercase_=False):
     if isinstance(lowercase_ ,       lowercase_):
         snake_case_ :    Optional[int]     			=						value


a_											=						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_											=						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."""    ,						snake_case_    ,						)
class    UpperCAmelCase_				(	snake_case_					):





 def __init__(    self ,       lowercase_):
     super().__init__(lowercase_)
     snake_case_ :    List[Any]     			=						config
     snake_case_ :    Tuple     			=						ResNetEmbeddings(lowercase_)
     snake_case_ :    List[Any]     			=						ResNetEncoder(lowercase_)
     snake_case_ :    List[str]     			=						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        snake_case__		(    self ,       lowercase_ ,       lowercase_ = None ,       lowercase_ = None):
     snake_case_ :    Union[str, Any]     			=						(
         output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
     )
     snake_case_ :    str     			=						return_dict if return_dict is not None else self.config.use_return_dict

     snake_case_ :    Optional[Any]     			=						self.embedder(lowercase_)

     snake_case_ :    List[str]     			=						self.encoder(
         lowercase_ ,       output_hidden_states=lowercase_ ,       return_dict=lowercase_)

     snake_case_ :    Optional[Any]     			=						encoder_outputs[0]

     snake_case_ :    List[Any]     			=						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(
    """
    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    """    ,						snake_case_    ,						)
class    UpperCAmelCase_				(	snake_case_					):





 def __init__(    self ,       lowercase_):
     super().__init__(lowercase_)
     snake_case_ :    Tuple     			=						config.num_labels
     snake_case_ :    Dict     			=						ResNetModel(lowercase_)
     # classification head
     snake_case_ :    List[str]     			=						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        snake_case__		(    self ,       lowercase_ = None ,       lowercase_ = None ,       lowercase_ = None ,       lowercase_ = None ,       ):
     snake_case_ :    int     			=						return_dict if return_dict is not None else self.config.use_return_dict

     snake_case_ :    List[str]     			=						self.resnet(lowercase_ ,       output_hidden_states=lowercase_ ,       return_dict=lowercase_)

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

     snake_case_ :    List[str]     			=						self.classifier(lowercase_)

     snake_case_ :    Dict     			=						None

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

     if not return_dict:
         snake_case_ :    str     			=						(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(
    """
    ResNet backbone, to be used with frameworks like DETR and MaskFormer.
    """    ,						snake_case_    ,						)
class    UpperCAmelCase_				(	snake_case_    ,						snake_case_					):





 def __init__(    self ,       lowercase_):
     super().__init__(lowercase_)
     super()._init_backbone(lowercase_)

     snake_case_ :    Dict     			=						[config.embedding_size] + config.hidden_sizes
     snake_case_ :    Dict     			=						ResNetEmbeddings(lowercase_)
     snake_case_ :    Tuple     			=						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        snake_case__		(    self ,       lowercase_ ,       lowercase_ = None ,       lowercase_ = None):
     snake_case_ :    int     			=						return_dict if return_dict is not None else self.config.use_return_dict
     snake_case_ :    List[str]     			=						(
         output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
     )

     snake_case_ :    Optional[int]     			=						self.embedder(lowercase_)

     snake_case_ :    Optional[int]     			=						self.encoder(lowercase_ ,       output_hidden_states=lowercase_ ,       return_dict=lowercase_)

     snake_case_ :    List[Any]     			=						outputs.hidden_states

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

     if not return_dict:
         snake_case_ :    str     			=						(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_ ,       )






'''simple docstring'''
from collections import OrderedDict
from typing import TYPE_CHECKING, Any, List, Mapping, Optional, Union

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import TensorType, logging


if TYPE_CHECKING:
  from ...onnx.config import PatchingSpec
  from ...tokenization_utils_base import PreTrainedTokenizerBase


a_											=						logging.get_logger(__name__)

a_											=						{
    "allenai/longformer-base-4096": "https://huggingface.co/allenai/longformer-base-4096/resolve/main/config.json",
    "allenai/longformer-large-4096": "https://huggingface.co/allenai/longformer-large-4096/resolve/main/config.json",
    "allenai/longformer-large-4096-finetuned-triviaqa": (
        "https://huggingface.co/allenai/longformer-large-4096-finetuned-triviaqa/resolve/main/config.json"
    ),
    "allenai/longformer-base-4096-extra.pos.embd.only": (
        "https://huggingface.co/allenai/longformer-base-4096-extra.pos.embd.only/resolve/main/config.json"
    ),
    "allenai/longformer-large-4096-extra.pos.embd.only": (
        "https://huggingface.co/allenai/longformer-large-4096-extra.pos.embd.only/resolve/main/config.json"
    ),
}






class    UpperCAmelCase_				(	snake_case__					):
 UpperCAmelCase_		    =						"""longformer"""





 def __init__(    self ,       lowercase_ = 5_12 ,       lowercase_ = 2 ,       lowercase_ = 1 ,       lowercase_ = 0 ,       lowercase_ = 2 ,       lowercase_ = 3_05_22 ,       lowercase_ = 7_68 ,       lowercase_ = 12 ,       lowercase_ = 12 ,       lowercase_ = 30_72 ,       lowercase_ = "gelu" ,       lowercase_ = 0.1 ,       lowercase_ = 0.1 ,       lowercase_ = 5_12 ,       lowercase_ = 2 ,       lowercase_ = 0.02 ,       lowercase_ = 1E-12 ,       lowercase_ = False ,       **lowercase_ ,       ):
     super().__init__(pad_token_id=lowercase_ ,       **lowercase_)

     snake_case_ :    Dict     			=						attention_window
     snake_case_ :    Tuple     			=						sep_token_id
     snake_case_ :    Optional[Any]     			=						bos_token_id
     snake_case_ :    str     			=						eos_token_id
     snake_case_ :    Optional[int]     			=						vocab_size
     snake_case_ :    Dict     			=						hidden_size
     snake_case_ :    Optional[Any]     			=						num_hidden_layers
     snake_case_ :    int     			=						num_attention_heads
     snake_case_ :    Union[str, Any]     			=						hidden_act
     snake_case_ :    Union[str, Any]     			=						intermediate_size
     snake_case_ :    Union[str, Any]     			=						hidden_dropout_prob
     snake_case_ :    Optional[Any]     			=						attention_probs_dropout_prob
     snake_case_ :    List[str]     			=						max_position_embeddings
     snake_case_ :    str     			=						type_vocab_size
     snake_case_ :    Tuple     			=						initializer_range
     snake_case_ :    List[str]     			=						layer_norm_eps
     snake_case_ :    Tuple     			=						onnx_export






class    UpperCAmelCase_				(	snake_case__					):





 def __init__(    self ,       lowercase_ ,       lowercase_ = "default" ,       lowercase_ = None):
     super().__init__(lowercase_ ,       lowercase_ ,       lowercase_)
     snake_case_ :    Dict     			=						True





 @property
 def        snake_case__		(    self):
     if self.task == "multiple-choice":
         snake_case_ :    Tuple     			=						{0: "batch", 1: "choice", 2: "sequence"}
     else:
         snake_case_ :    int     			=						{0: "batch", 1: "sequence"}
     return OrderedDict(
         [
             ("input_ids", dynamic_axis),
             ("attention_mask", dynamic_axis),
             ("global_attention_mask", dynamic_axis),
         ])





 @property
 def        snake_case__		(    self):
     snake_case_ :    Union[str, Any]     			=						super().outputs
     if self.task == "default":
         snake_case_ :    str     			=						{0: "batch"}
     return outputs





 @property
 def        snake_case__		(    self):
     return 1E-4





 @property
 def        snake_case__		(    self):
     # needs to be >= 14 to support tril operator
     return max(super().default_onnx_opset ,       14)





 def        snake_case__		(    self ,       lowercase_ ,       lowercase_ = -1 ,       lowercase_ = -1 ,       lowercase_ = False ,       lowercase_ = None ,       ):
     snake_case_ :    Optional[Any]     			=						super().generate_dummy_inputs(
         preprocessor=lowercase_ ,       batch_size=lowercase_ ,       seq_length=lowercase_ ,       is_pair=lowercase_ ,       framework=lowercase_)
     import torch

     # for some reason, replacing this code by inputs["global_attention_mask"] = torch.randint(2, inputs["input_ids"].shape, dtype=torch.int64)
     # makes the export fail randomly
     snake_case_ :    Any     			=						torch.zeros_like(inputs["input_ids"])
     # make every second token global
     snake_case_ :    Tuple     			=						1

     return inputs




