





import json
import os
from functools import lru_cache
from typing import Dict, List, Optional, Tuple, Union

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding, EncodedInput
from ...utils import PaddingStrategy, logging


_lowerCAmelCase 				=     logging.get_logger(__name__)


_lowerCAmelCase 				=     {"""vocab_file""": """vocab.json""", """merges_file""": """merges.txt"""}

# See all LED models at https://huggingface.co/models?filter=LED
_lowerCAmelCase 				=     {
    """vocab_file""": {
        """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/vocab.json""",
    },
    """merges_file""": {
        """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/merges.txt""",
    },
    """tokenizer_file""": {
        """allenai/led-base-16384""": """https://huggingface.co/allenai/led-base-16384/resolve/main/tokenizer.json""",
    },
}

_lowerCAmelCase 				=     {
    """allenai/led-base-16384""": 16_384,
}



@lru_cache()
# Copied from transformers.models.bart.tokenization_bart.bytes_to_unicode
def     _lowerCAmelCase		(  ):
   '''simple docstring'''


   A_     :				Optional[Any]			      =	(
       list(range(ord("""!"""     )  ,ord("""~"""     ) + 1     )     ) + list(range(ord("""¡"""     )  ,ord("""¬"""     ) + 1     )     ) + list(range(ord("""®"""     )  ,ord("""ÿ"""     ) + 1     )     )
   )
   A_     :				str			      =	bs[:]
   A_     :				List[str]			      =	0
   for b in range(2**8     ):
      if b not in bs:
         bs.append(_lowerCAmelCase     )
         cs.append(2**8 + n     )
         n += 1
   A_     :				Tuple			      =	[chr(_lowerCAmelCase     ) for n in cs]
   return dict(zip(_lowerCAmelCase  ,_lowerCAmelCase     )     )



def     _lowerCAmelCase		(  _lowerCAmelCase     ):
   '''simple docstring'''


   A_     :				Any			      =	set()
   A_     :				Dict			      =	word[0]
   for char in word[1:]:
      pairs.add((prev_char, char)     )
      A_     :				Optional[int]			      =	char
   return pairs







class    _UpperCAmelCase							(		_lowerCamelCase     ):
      a						       =							VOCAB_FILES_NAMES
      a						       =							PRETRAINED_VOCAB_FILES_MAP
      a						       =							PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
      a						       =							['''input_ids''', '''attention_mask''']
      def __init__(		self      ,       a__      ,       a__      ,       a__="replace"      ,       a__="<s>"      ,       a__="</s>"      ,       a__="</s>"      ,       a__="<s>"      ,       a__="<unk>"      ,       a__="<pad>"      ,       a__="<mask>"      ,       a__=False      ,       **a__      ,       ):
         A_     :				Dict			      =	AddedToken(a__      ,       lstrip=a__      ,       rstrip=a__       ) if isinstance(a__      ,       a__       ) else bos_token
         A_     :				Tuple			      =	AddedToken(a__      ,       lstrip=a__      ,       rstrip=a__       ) if isinstance(a__      ,       a__       ) else eos_token
         A_     :				Dict			      =	AddedToken(a__      ,       lstrip=a__      ,       rstrip=a__       ) if isinstance(a__      ,       a__       ) else sep_token
         A_     :				Tuple			      =	AddedToken(a__      ,       lstrip=a__      ,       rstrip=a__       ) if isinstance(a__      ,       a__       ) else cls_token
         A_     :				Dict			      =	AddedToken(a__      ,       lstrip=a__      ,       rstrip=a__       ) if isinstance(a__      ,       a__       ) else unk_token
         A_     :				Dict			      =	AddedToken(a__      ,       lstrip=a__      ,       rstrip=a__       ) if isinstance(a__      ,       a__       ) else pad_token

         # Mask token behave like a normal word, i.e. include the space before it
         A_     :				Tuple			      =	AddedToken(a__      ,       lstrip=a__      ,       rstrip=a__       ) if isinstance(a__      ,       a__       ) else mask_token

         super().__init__(
             errors=a__      ,       bos_token=a__      ,       eos_token=a__      ,       unk_token=a__      ,       sep_token=a__      ,       cls_token=a__      ,       pad_token=a__      ,       mask_token=a__      ,       add_prefix_space=a__      ,       **a__      ,       )

         with open(a__      ,       encoding="""utf-8"""       ) as vocab_handle:
            A_     :				Optional[Any]			      =	json.load(a__       )
         A_     :				Tuple			      =	{v: k for k, v in self.encoder.items()}
         A_     :				Union[str, Any]			      =	errors  # how to handle errors in decoding
         A_     :				List[Any]			      =	bytes_to_unicode()
         A_     :				Union[str, Any]			      =	{v: k for k, v in self.byte_encoder.items()}
         with open(a__      ,       encoding="""utf-8"""       ) as merges_handle:
            A_     :				Any			      =	merges_handle.read().split("""\n"""       )[1:-1]
         A_     :				Optional[int]			      =	[tuple(merge.split()       ) for merge in bpe_merges]
         A_     :				Union[str, Any]			      =	dict(zip(a__      ,       range(len(a__       )       )       )       )
         A_     :				Optional[int]			      =	{}
         A_     :				Union[str, Any]			      =	add_prefix_space

         # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
         A_     :				List[str]			      =	re.compile(R"""'s|'t|'re|'ve|'m|'ll|'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+"""       )
      @property
      # Copied from transformers.models.bart.tokenization_bart.BartTokenizer.vocab_size
      def 		_lowerCamelCase      (		self       ):
         return len(self.encoder       )
      def 		_lowerCamelCase      (		self       ):
         return dict(self.encoder      ,       **self.added_tokens_encoder       )
      def 		_lowerCamelCase      (		self      ,       a__       ):
         if token in self.cache:
            return self.cache[token]
         A_     :				Any			      =	tuple(a__       )
         A_     :				Union[str, Any]			      =	get_pairs(a__       )

         if not pairs:
            return token

         while True:
            A_     :				List[Any]			      =	min(a__      ,       key=lambda a__       : self.bpe_ranks.get(a__      ,       float("""inf"""       )       )       )
            if bigram not in self.bpe_ranks:
               break
            A_      ,				A_     :				Any			      =	bigram
            A_     :				Optional[Any]			      =	[]
            A_     :				str			      =	0
            while i < len(a__       ):
               try:
                  A_     :				List[Any]			      =	word.index(a__      ,       a__       )
               except ValueError:
                  new_word.extend(word[i:]       )
                  break
               else:
                  new_word.extend(word[i:j]       )
                  A_     :				Tuple			      =	j

               if word[i] == first and i < len(a__       ) - 1 and word[i + 1] == second:
                  new_word.append(first + second       )
                  i += 2
               else:
                  new_word.append(word[i]       )
                  i += 1
            A_     :				Union[str, Any]			      =	tuple(a__       )
            A_     :				Dict			      =	new_word
            if len(a__       ) == 1:
               break
            else:
               A_     :				Any			      =	get_pairs(a__       )
         A_     :				Optional[Any]			      =	""" """.join(a__       )
         A_     :				str			      =	word
         return word
      def 		_lowerCamelCase      (		self      ,       a__       ):
         A_     :				Dict			      =	[]
         for token in re.findall(self.pat      ,       a__       ):
            A_     :				Any			      =	"""""".join(
                self.byte_encoder[b] for b in token.encode("""utf-8"""       )       )  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
            bpe_tokens.extend(bpe_token for bpe_token in self.bpe(a__       ).split(""" """       )       )
         return bpe_tokens
      def 		_lowerCamelCase      (		self      ,       a__       ):
         return self.encoder.get(a__      ,       self.encoder.get(self.unk_token       )       )
      def 		_lowerCamelCase      (		self      ,       a__       ):
         return self.decoder.get(a__       )
      def 		_lowerCamelCase      (		self      ,       a__       ):
         A_     :				str			      =	"""""".join(a__       )
         A_     :				int			      =	bytearray([self.byte_decoder[c] for c in text]       ).decode("""utf-8"""      ,       errors=self.errors       )
         return text
      def 		_lowerCamelCase      (		self      ,       a__      ,       a__ = None       ):
         if not os.path.isdir(a__       ):
            logger.error(F"""Vocabulary path ({save_directory}) should be a directory"""       )
            return
         A_     :				List[Any]			      =	os.path.join(
             a__      ,       (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""vocab_file"""]       )
         A_     :				Union[str, Any]			      =	os.path.join(
             a__      ,       (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""merges_file"""]       )

         with open(a__      ,       """w"""      ,       encoding="""utf-8"""       ) as f:
            f.write(json.dumps(self.encoder      ,       indent=2      ,       sort_keys=a__      ,       ensure_ascii=a__       ) + """\n"""       )

         A_     :				List[str]			      =	0
         with open(a__      ,       """w"""      ,       encoding="""utf-8"""       ) as writer:
            writer.write("""#version: 0.2\n"""       )
            for bpe_tokens, token_index in sorted(self.bpe_ranks.items()      ,       key=lambda a__       : kv[1]       ):
               if index != token_index:
                  logger.warning(
                      F"""Saving vocabulary to {merge_file}: BPE merge indices are not consecutive."""
                      """ Please check that the tokenizer is not corrupted!"""       )
                  A_     :				Optional[Any]			      =	token_index
               writer.write(""" """.join(a__       ) + """\n"""       )
               index += 1

         return vocab_file, merge_file
      def 		_lowerCamelCase      (		self      ,       a__      ,       a__ = None       ):
         if token_ids_a is None:
            return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
         A_     :				Any			      =	[self.cls_token_id]
         A_     :				List[str]			      =	[self.sep_token_id]
         return cls + token_ids_a + sep + sep + token_ids_a + sep
      def 		_lowerCamelCase      (		self      ,       a__      ,       a__ = None      ,       a__ = False       ):
         if already_has_special_tokens:
            return super().get_special_tokens_mask(
                token_ids_a=a__      ,       token_ids_a=a__      ,       already_has_special_tokens=a__       )

         if token_ids_a is None:
            return [1] + ([0] * len(a__       )) + [1]
         return [1] + ([0] * len(a__       )) + [1, 1] + ([0] * len(a__       )) + [1]
      def 		_lowerCamelCase      (		self      ,       a__      ,       a__ = None       ):
         A_     :				List[str]			      =	[self.sep_token_id]
         A_     :				Tuple			      =	[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 + sep + token_ids_a + sep       ) * [0]
      def 		_lowerCamelCase      (		self      ,       a__      ,       a__=False      ,       **a__       ):
         A_     :				Dict			      =	kwargs.pop("""add_prefix_space"""      ,       self.add_prefix_space       )
         if (is_split_into_words or add_prefix_space) and (len(a__       ) > 0 and not text[0].isspace()):
            A_     :				int			      =	""" """ + text
         return (text, kwargs)






      def 		_lowerCamelCase      (		self      ,       a__      ,       a__ = None      ,       a__ = PaddingStrategy.DO_NOT_PAD      ,       a__ = None      ,       a__ = None      ,       ):
         A_     :				Union[str, Any]			      =	super()._pad(
             encoded_inputs=a__      ,       max_length=a__      ,       padding_strategy=a__      ,       pad_to_multiple_of=a__      ,       return_attention_mask=a__      ,       )

         # Load from model defaults
         if return_attention_mask is None:
            A_     :				List[str]			      =	"""attention_mask""" in self.model_input_names

         if return_attention_mask and "global_attention_mask" in encoded_inputs:
            A_     :				Optional[int]			      =	encoded_inputs[self.model_input_names[0]]
            # `global_attention_mask` need to have the same length as other (sequential) inputs.
            A_     :				List[str]			      =	len(encoded_inputs["""global_attention_mask"""]       ) != len(a__       )

            if needs_to_be_padded:
               A_     :				Any			      =	len(a__       ) - len(encoded_inputs["""global_attention_mask"""]       )

               if self.padding_side == "right":
                  # Use `-1` since `0` in `global_attention_mask` means `local attention` instead of `not to attend`
                  A_     :				Optional[int]			      =	(
                      encoded_inputs["""global_attention_mask"""] + [-1] * difference
                  )
               elif self.padding_side == "left":
                  A_     :				Any			      =	[-1] * difference + encoded_inputs[
                      """global_attention_mask"""
                  ]
               else:
                  raise ValueError("""Invalid padding strategy:""" + str(self.padding_side       )       )

         return encoded_inputs













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


_lowerCAmelCase 				=     logging.get_logger(__name__)

# General docstring
_lowerCAmelCase 				=     """ResNetConfig"""

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

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

_lowerCAmelCase 				=     [
    """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"       ):
         super().__init__()
         A_     :				Tuple			      =	nn.Convad(
             a__      ,       a__      ,       kernel_size=a__      ,       stride=a__      ,       padding=kernel_size // 2      ,       bias=a__       )
         A_     :				Optional[Any]			      =	nn.BatchNormad(a__       )
         A_     :				List[Any]			      =	ACTaFN[activation] if activation is not None else nn.Identity()






      def 		_lowerCamelCase      (		self      ,       a__       ):
         A_     :				List[str]			      =	self.convolution(a__       )
         A_     :				Optional[int]			      =	self.normalization(a__       )
         A_     :				int			      =	self.activation(a__       )
         return hidden_state






class    _UpperCAmelCase							(		nn.Module     ):
      def __init__(		self      ,       a__       ):
         super().__init__()
         A_     :				Union[str, Any]			      =	ResNetConvLayer(
             config.num_channels      ,       config.embedding_size      ,       kernel_size=7      ,       stride=2      ,       activation=config.hidden_act       )
         A_     :				Any			      =	nn.MaxPoolad(kernel_size=3      ,       stride=2      ,       padding=1       )
         A_     :				Optional[Any]			      =	config.num_channels






      def 		_lowerCamelCase      (		self      ,       a__       ):
         A_     :				Tuple			      =	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."""       )
         A_     :				str			      =	self.embedder(a__       )
         A_     :				Dict			      =	self.pooler(a__       )
         return embedding






class    _UpperCAmelCase							(		nn.Module     ):
      def __init__(		self      ,       a__      ,       a__      ,       a__ = 2       ):
         super().__init__()
         A_     :				Union[str, Any]			      =	nn.Convad(a__      ,       a__      ,       kernel_size=1      ,       stride=a__      ,       bias=a__       )
         A_     :				int			      =	nn.BatchNormad(a__       )






      def 		_lowerCamelCase      (		self      ,       a__       ):
         A_     :				List[str]			      =	self.convolution(a__       )
         A_     :				List[str]			      =	self.normalization(a__       )
         return hidden_state






class    _UpperCAmelCase							(		nn.Module     ):
      def __init__(		self      ,       a__      ,       a__      ,       a__ = 1      ,       a__ = "relu"       ):
         super().__init__()
         A_     :				Union[str, Any]			      =	in_channels != out_channels or stride != 1
         A_     :				List[Any]			      =	(
             ResNetShortCut(a__      ,       a__      ,       stride=a__       ) if should_apply_shortcut else nn.Identity()
         )
         A_     :				List[str]			      =	nn.Sequential(
             ResNetConvLayer(a__      ,       a__      ,       stride=a__       )      ,       ResNetConvLayer(a__      ,       a__      ,       activation=a__       )      ,       )
         A_     :				Any			      =	ACTaFN[activation]






      def 		_lowerCamelCase      (		self      ,       a__       ):
         A_     :				Any			      =	hidden_state
         A_     :				Optional[Any]			      =	self.layer(a__       )
         A_     :				Any			      =	self.shortcut(a__       )
         hidden_state += residual
         A_     :				Optional[Any]			      =	self.activation(a__       )
         return hidden_state






class    _UpperCAmelCase							(		nn.Module     ):
      def __init__(		self      ,       a__      ,       a__      ,       a__ = 1      ,       a__ = "relu"      ,       a__ = 4       ):
         super().__init__()
         A_     :				int			      =	in_channels != out_channels or stride != 1
         A_     :				List[str]			      =	out_channels // reduction
         A_     :				Optional[Any]			      =	(
             ResNetShortCut(a__      ,       a__      ,       stride=a__       ) if should_apply_shortcut else nn.Identity()
         )
         A_     :				Any			      =	nn.Sequential(
             ResNetConvLayer(a__      ,       a__      ,       kernel_size=1       )      ,       ResNetConvLayer(a__      ,       a__      ,       stride=a__       )      ,       ResNetConvLayer(a__      ,       a__      ,       kernel_size=1      ,       activation=a__       )      ,       )
         A_     :				Dict			      =	ACTaFN[activation]






      def 		_lowerCamelCase      (		self      ,       a__       ):
         A_     :				int			      =	hidden_state
         A_     :				Dict			      =	self.layer(a__       )
         A_     :				Optional[Any]			      =	self.shortcut(a__       )
         hidden_state += residual
         A_     :				Dict			      =	self.activation(a__       )
         return hidden_state






class    _UpperCAmelCase							(		nn.Module     ):
      def __init__(		self      ,       a__      ,       a__      ,       a__      ,       a__ = 2      ,       a__ = 2      ,       ):
         super().__init__()

         A_     :				List[Any]			      =	ResNetBottleNeckLayer if config.layer_type == """bottleneck""" else ResNetBasicLayer

         A_     :				Optional[int]			      =	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 		_lowerCamelCase      (		self      ,       a__       ):
         A_     :				List[Any]			      =	input
         for layer in self.layers:
            A_     :				List[str]			      =	layer(a__       )
         return hidden_state






class    _UpperCAmelCase							(		nn.Module     ):
      def __init__(		self      ,       a__       ):
         super().__init__()
         A_     :				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]      ,       )       )
         A_     :				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 		_lowerCamelCase      (		self      ,       a__      ,       a__ = False      ,       a__ = True       ):
         A_     :				Union[str, Any]			      =	() if output_hidden_states else None

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

            A_     :				str			      =	stage_module(a__       )

         if output_hidden_states:
            A_     :				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=a__      ,       hidden_states=a__      ,       )






class    _UpperCAmelCase							(		_lowerCamelCase     ):
      a						       =							ResNetConfig
      a						       =							'''resnet'''
      a						       =							'''pixel_values'''
      a						       =							True
      def 		_lowerCamelCase      (		self      ,       a__       ):
         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 		_lowerCamelCase      (		self      ,       a__      ,       a__=False       ):
         if isinstance(a__      ,       a__       ):
            A_     :				Dict			      =	value






_lowerCAmelCase 				=     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.
"""

_lowerCAmelCase 				=     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.'''			,       _lowerCamelCase			,       )
class    _UpperCAmelCase							(		_lowerCamelCase     ):
      def __init__(		self      ,       a__       ):
         super().__init__(a__       )
         A_     :				Tuple			      =	config
         A_     :				List[str]			      =	ResNetEmbeddings(a__       )
         A_     :				Optional[int]			      =	ResNetEncoder(a__       )
         A_     :				int			      =	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 		_lowerCamelCase      (		self      ,       a__      ,       a__ = None      ,       a__ = None       ):
         A_     :				str			      =	(
             output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         )
         A_     :				Dict			      =	return_dict if return_dict is not None else self.config.use_return_dict

         A_     :				Any			      =	self.embedder(a__       )

         A_     :				int			      =	self.encoder(
             a__      ,       output_hidden_states=a__      ,       return_dict=a__       )

         A_     :				Optional[Any]			      =	encoder_outputs[0]

         A_     :				List[str]			      =	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(
    '''
    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    '''			,       _lowerCamelCase			,       )
class    _UpperCAmelCase							(		_lowerCamelCase     ):
      def __init__(		self      ,       a__       ):
         super().__init__(a__       )
         A_     :				Optional[Any]			      =	config.num_labels
         A_     :				Tuple			      =	ResNetModel(a__       )
         # classification head
         A_     :				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 		_lowerCamelCase      (		self      ,       a__ = None      ,       a__ = None      ,       a__ = None      ,       a__ = None      ,       ):
         A_     :				Optional[int]			      =	return_dict if return_dict is not None else self.config.use_return_dict

         A_     :				Any			      =	self.resnet(a__      ,       output_hidden_states=a__      ,       return_dict=a__       )

         A_     :				List[Any]			      =	outputs.pooler_output if return_dict else outputs[1]

         A_     :				Dict			      =	self.classifier(a__       )

         A_     :				Optional[int]			      =	None

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

         if not return_dict:
            A_     :				Optional[Any]			      =	(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(
    '''
    ResNet backbone, to be used with frameworks like DETR and MaskFormer.
    '''			,       _lowerCamelCase			,       )
class    _UpperCAmelCase							(		_lowerCamelCase			,       _lowerCamelCase     ):
      def __init__(		self      ,       a__       ):
         super().__init__(a__       )
         super()._init_backbone(a__       )

         A_     :				Optional[Any]			      =	[config.embedding_size] + config.hidden_sizes
         A_     :				Any			      =	ResNetEmbeddings(a__       )
         A_     :				Tuple			      =	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 		_lowerCamelCase      (		self      ,       a__      ,       a__ = None      ,       a__ = None       ):
         A_     :				List[str]			      =	return_dict if return_dict is not None else self.config.use_return_dict
         A_     :				List[str]			      =	(
             output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
         )

         A_     :				Dict			      =	self.embedder(a__       )

         A_     :				Tuple			      =	self.encoder(a__      ,       output_hidden_states=a__      ,       return_dict=a__       )

         A_     :				Dict			      =	outputs.hidden_states

         A_     :				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:
            A_     :				Tuple			      =	(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__      ,       )






