



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   UpperCAmelCase_    (       nn.Module):







							def __init__(   self,			__a,			__a,			__a = 3,			__a = 1,			__a = "relu"):

														'''simple docstring'''

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







							def    snake_case__      (   self,			__a):

														'''simple docstring'''

														_lowerCAmelCase     :							List[Any]    =    self.convolution(__a)
														_lowerCAmelCase     :							Dict    =    self.normalization(__a)
														_lowerCAmelCase     :							List[Any]    =    self.activation(__a)
														return hidden_state



class   UpperCAmelCase_    (       nn.Module):







							def __init__(   self,			__a):

														'''simple docstring'''

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







							def    snake_case__      (   self,			__a):

														'''simple docstring'''

														_lowerCAmelCase     :							Optional[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.")
														_lowerCAmelCase     :							int    =    self.embedder(__a)
														_lowerCAmelCase     :							Tuple    =    self.pooler(__a)
														return embedding



class   UpperCAmelCase_    (       nn.Module):







							def __init__(   self,			__a,			__a,			__a = 2):

														'''simple docstring'''

														super().__init__()
														_lowerCAmelCase     :							Union[str, Any]    =    nn.Convad(__a,			__a,			kernel_size=1,			stride=__a,			bias=__a)
														_lowerCAmelCase     :							int    =    nn.BatchNormad(__a)







							def    snake_case__      (   self,			__a):

														'''simple docstring'''

														_lowerCAmelCase     :							Optional[Any]    =    self.convolution(__a)
														_lowerCAmelCase     :							Dict    =    self.normalization(__a)
														return hidden_state



class   UpperCAmelCase_    (       nn.Module):







							def __init__(   self,			__a,			__a,			__a = 1,			__a = "relu"):

														'''simple docstring'''

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







							def    snake_case__      (   self,			__a):

														'''simple docstring'''

														_lowerCAmelCase     :							int    =    hidden_state
														_lowerCAmelCase     :							Dict    =    self.layer(__a)
														_lowerCAmelCase     :							Optional[int]    =    self.shortcut(__a)
														hidden_state += residual
														_lowerCAmelCase     :							Tuple    =    self.activation(__a)
														return hidden_state



class   UpperCAmelCase_    (       nn.Module):







							def __init__(   self,			__a,			__a,			__a = 1,			__a = "relu",			__a = 4):

														'''simple docstring'''

														super().__init__()
														_lowerCAmelCase     :							int    =    in_channels != out_channels or stride != 1
														_lowerCAmelCase     :							str    =    out_channels // reduction
														_lowerCAmelCase     :							Optional[int]    =    (
														    ResNetShortCut(__a,			__a,			stride=__a) if should_apply_shortcut else nn.Identity()
														)
														_lowerCAmelCase     :							Tuple    =    nn.Sequential(
														    ResNetConvLayer(__a,			__a,			kernel_size=1),			ResNetConvLayer(__a,			__a,			stride=__a),			ResNetConvLayer(__a,			__a,			kernel_size=1,			activation=__a),			)
														_lowerCAmelCase     :							Optional[int]    =    ACTaFN[activation]







							def    snake_case__      (   self,			__a):

														'''simple docstring'''

														_lowerCAmelCase     :							Any    =    hidden_state
														_lowerCAmelCase     :							Any    =    self.layer(__a)
														_lowerCAmelCase     :							str    =    self.shortcut(__a)
														hidden_state += residual
														_lowerCAmelCase     :							int    =    self.activation(__a)
														return hidden_state



class   UpperCAmelCase_    (       nn.Module):







							def __init__(   self,			__a,			__a,			__a,			__a = 2,			__a = 2,			):

														'''simple docstring'''

														super().__init__()

														_lowerCAmelCase     :							List[str]    =    ResNetBottleNeckLayer if config.layer_type == "bottleneck" else ResNetBasicLayer

														_lowerCAmelCase     :							Dict    =    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    snake_case__      (   self,			__a):

														'''simple docstring'''

														_lowerCAmelCase     :							Tuple    =    input
														for layer in self.layers:
																					_lowerCAmelCase     :							Tuple    =    layer(__a)
														return hidden_state



class   UpperCAmelCase_    (       nn.Module):







							def __init__(   self,			__a):

														'''simple docstring'''

														super().__init__()
														_lowerCAmelCase     :							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(
														        __a,			config.embedding_size,			config.hidden_sizes[0],			stride=2 if config.downsample_in_first_stage else 1,			depth=config.depths[0],			))
														_lowerCAmelCase     :							Union[str, Any]    =    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    snake_case__      (   self,			__a,			__a = False,			__a = True):

														'''simple docstring'''

														_lowerCAmelCase     :							Optional[int]    =    () if output_hidden_states else None

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

																					_lowerCAmelCase     :							List[str]    =    stage_module(__a)

														if output_hidden_states:
																					_lowerCAmelCase     :							str    =    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   UpperCAmelCase_    (       a):
							lowerCamelCase__   			=		ResNetConfig
							lowerCamelCase__   			=		'resnet'
							lowerCamelCase__   			=		'pixel_values'
							lowerCamelCase__   			=		True







							def    snake_case__      (   self,			__a):

														'''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    snake_case__      (   self,			__a,			__a=False):

														'''simple docstring'''

														if isinstance(__a,			__a):
																					_lowerCAmelCase     :							Tuple    =    value



_snake_case		=  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"

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







							def __init__(   self,			__a):

														'''simple docstring'''

														super().__init__(__a)
														_lowerCAmelCase     :							Tuple    =    config
														_lowerCAmelCase     :							List[str]    =    ResNetEmbeddings(__a)
														_lowerCAmelCase     :							List[str]    =    ResNetEncoder(__a)
														_lowerCAmelCase     :							Any    =    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    snake_case__      (   self,			__a,			__a = None,			__a = None):

														'''simple docstring'''

														_lowerCAmelCase     :							Union[str, Any]    =    (
														    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
														)
														_lowerCAmelCase     :							List[str]    =    return_dict if return_dict is not None else self.config.use_return_dict

														_lowerCAmelCase     :							List[str]    =    self.embedder(__a)

														_lowerCAmelCase     :							int    =    self.encoder(
														    __a,			output_hidden_states=__a,			return_dict=__a)

														_lowerCAmelCase     :							int    =    encoder_outputs[0]

														_lowerCAmelCase     :							List[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(
    '\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   UpperCAmelCase_    (       a):







							def __init__(   self,			__a):

														'''simple docstring'''

														super().__init__(__a)
														_lowerCAmelCase     :							Tuple    =    config.num_labels
														_lowerCAmelCase     :							str    =    ResNetModel(__a)
														# classification head
														_lowerCAmelCase     :							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(__a)
							@add_code_sample_docstrings(
							    checkpoint=_IMAGE_CLASS_CHECKPOINT,			output_type=__a,			config_class=_CONFIG_FOR_DOC,			expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT,			)
							def    snake_case__      (   self,			__a = None,			__a = None,			__a = None,			__a = None,			):

														'''simple docstring'''

														_lowerCAmelCase     :							List[Any]    =    return_dict if return_dict is not None else self.config.use_return_dict

														_lowerCAmelCase     :							List[Any]    =    self.resnet(__a,			output_hidden_states=__a,			return_dict=__a)

														_lowerCAmelCase     :							Tuple    =    outputs.pooler_output if return_dict else outputs[1]

														_lowerCAmelCase     :							int    =    self.classifier(__a)

														_lowerCAmelCase     :							Optional[Any]    =    None

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

														if not return_dict:
																					_lowerCAmelCase     :							Dict    =    (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    '   ,					a   ,					)
class   UpperCAmelCase_    (       a   ,					a):







							def __init__(   self,			__a):

														'''simple docstring'''

														super().__init__(__a)
														super()._init_backbone(__a)

														_lowerCAmelCase     :							Dict    =    [config.embedding_size] + config.hidden_sizes
														_lowerCAmelCase     :							List[Any]    =    ResNetEmbeddings(__a)
														_lowerCAmelCase     :							Union[str, 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    snake_case__      (   self,			__a,			__a = None,			__a = None):

														'''simple docstring'''

														_lowerCAmelCase     :							Tuple    =    return_dict if return_dict is not None else self.config.use_return_dict
														_lowerCAmelCase     :							Optional[Any]    =    (
														    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
														)

														_lowerCAmelCase     :							Union[str, Any]    =    self.embedder(__a)

														_lowerCAmelCase     :							Union[str, Any]    =    self.encoder(__a,			output_hidden_states=__a,			return_dict=__a)

														_lowerCAmelCase     :							Tuple    =    outputs.hidden_states

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

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




import json
from typing import List, Optional, Tuple

from tokenizers import normalizers

from ...tokenization_utils_fast import PreTrainedTokenizerFast
from ...utils import logging
from .tokenization_distilbert import DistilBertTokenizer


__SCREAMING_SNAKE_CASE       :     str     =  logging.get_logger(__name__)

__SCREAMING_SNAKE_CASE       :     str     =  {"""vocab_file""": """vocab.txt""", """tokenizer_file""": """tokenizer.json"""}

__SCREAMING_SNAKE_CASE       :     Dict     =  {
    """vocab_file""": {
        """distilbert-base-uncased""": """https://huggingface.co/distilbert-base-uncased/resolve/main/vocab.txt""",
        """distilbert-base-uncased-distilled-squad""": (
            """https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/vocab.txt"""
        ),
        """distilbert-base-cased""": """https://huggingface.co/distilbert-base-cased/resolve/main/vocab.txt""",
        """distilbert-base-cased-distilled-squad""": (
            """https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/vocab.txt"""
        ),
        """distilbert-base-german-cased""": """https://huggingface.co/distilbert-base-german-cased/resolve/main/vocab.txt""",
        """distilbert-base-multilingual-cased""": (
            """https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/vocab.txt"""
        ),
    },
    """tokenizer_file""": {
        """distilbert-base-uncased""": """https://huggingface.co/distilbert-base-uncased/resolve/main/tokenizer.json""",
        """distilbert-base-uncased-distilled-squad""": (
            """https://huggingface.co/distilbert-base-uncased-distilled-squad/resolve/main/tokenizer.json"""
        ),
        """distilbert-base-cased""": """https://huggingface.co/distilbert-base-cased/resolve/main/tokenizer.json""",
        """distilbert-base-cased-distilled-squad""": (
            """https://huggingface.co/distilbert-base-cased-distilled-squad/resolve/main/tokenizer.json"""
        ),
        """distilbert-base-german-cased""": (
            """https://huggingface.co/distilbert-base-german-cased/resolve/main/tokenizer.json"""
        ),
        """distilbert-base-multilingual-cased""": (
            """https://huggingface.co/distilbert-base-multilingual-cased/resolve/main/tokenizer.json"""
        ),
    },
}

__SCREAMING_SNAKE_CASE       :     Optional[Any]     =  {
    """distilbert-base-uncased""": 512,
    """distilbert-base-uncased-distilled-squad""": 512,
    """distilbert-base-cased""": 512,
    """distilbert-base-cased-distilled-squad""": 512,
    """distilbert-base-german-cased""": 512,
    """distilbert-base-multilingual-cased""": 512,
}


__SCREAMING_SNAKE_CASE       :     List[Any]     =  {
    """distilbert-base-uncased""": {"""do_lower_case""": True},
    """distilbert-base-uncased-distilled-squad""": {"""do_lower_case""": True},
    """distilbert-base-cased""": {"""do_lower_case""": False},
    """distilbert-base-cased-distilled-squad""": {"""do_lower_case""": False},
    """distilbert-base-german-cased""": {"""do_lower_case""": False},
    """distilbert-base-multilingual-cased""": {"""do_lower_case""": False},
}

class 	lowerCamelCase_	(snake_case__    ):
      '''simple docstring'''

      __UpperCamelCase:  Union[str, Any]						=						VOCAB_FILES_NAMES
      __UpperCamelCase:  str						=						PRETRAINED_VOCAB_FILES_MAP
      __UpperCamelCase:  Optional[Any]						=						PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      __UpperCamelCase:  Any						=						PRETRAINED_INIT_CONFIGURATION
      __UpperCamelCase:  str						=						["input_ids", "attention_mask"]
      __UpperCamelCase:  List[str]						=						DistilBertTokenizer




      def __init__(       self						:				str						,					A						:				int=None						,					A						:				Tuple=None						,					A						:				Tuple=True						,					A						:				Dict="[UNK]"						,					A						:				List[Any]="[SEP]"						,					A						:				Optional[Any]="[PAD]"						,					A						:				Dict="[CLS]"						,					A						:				Tuple="[MASK]"						,					A						:				str=True						,					A						:				Dict=None						,					**A						:				List[Any]						,					):
             super().__init__(
                 A						,					tokenizer_file=A						,					do_lower_case=A						,					unk_token=A						,					sep_token=A						,					pad_token=A						,					cls_token=A						,					mask_token=A						,					tokenize_chinese_chars=A						,					strip_accents=A						,					**A						,					)

             _UpperCAmelCase     :  str							      =    json.loads(self.backend_tokenizer.normalizer.__getstate__()       )
             if (
                 normalizer_state.get("lowercase"						,					A       ) != do_lower_case
                 or normalizer_state.get("strip_accents"						,					A       ) != strip_accents
                 or normalizer_state.get("handle_chinese_chars"						,					A       ) != tokenize_chinese_chars
             ):
                    _UpperCAmelCase     :  Dict							      =    getattr(A						,					normalizer_state.pop("type"       )       )
                    _UpperCAmelCase     :  int							      =    do_lower_case
                    _UpperCAmelCase     :  Optional[int]							      =    strip_accents
                    _UpperCAmelCase     :  str							      =    tokenize_chinese_chars
                    _UpperCAmelCase     :  List[Any]							      =    normalizer_class(**A       )

             _UpperCAmelCase     :  Dict							      =    do_lower_case




      def      _A	(       self						:				List[Any]						,					A						:				Tuple						,					A						:				Any=None       ):
             _UpperCAmelCase     :  Optional[int]							      =    [self.cls_token_id] + token_ids_a + [self.sep_token_id]

             if token_ids_a:
                    output += token_ids_a + [self.sep_token_id]

             return output




      def      _A	(       self						:				int						,					A						:				List[int]						,					A						:				Optional[List[int]] = None       ):
             _UpperCAmelCase     :  Any							      =    [self.sep_token_id]
             _UpperCAmelCase     :  str							      =    [self.cls_token_id]
             if token_ids_a is None:
                    return len(cls + token_ids_a + sep       ) * [0]
             return len(cls + token_ids_a + sep       ) * [0] + len(token_ids_a + sep       ) * [1]





      def      _A	(       self						:				Dict						,					A						:				str						,					A						:				Optional[str] = None       ):
             _UpperCAmelCase     :  Any							      =    self._tokenizer.model.save(A						,					name=A       )
             return tuple(A       )

