





import bza
import gzip
import lzma
import os
import shutil
import struct
import tarfile
import warnings
import zipfile
from abc import ABC, abstractmethod
from pathlib import Path
from typing import Dict, List, Optional, Type, Union

from .. import config
from .filelock import FileLock
from .logging import get_logger


_lowerCAmelCase 				=     get_logger(__name__)

class    _UpperCAmelCase							:
      def __init__(		self      ,       a__ = None       ):
         A_     :				Tuple			      =	(
             os.path.join(a__      ,       config.EXTRACTED_DATASETS_DIR       ) if cache_dir else config.EXTRACTED_DATASETS_PATH
         )
         A_     :				str			      =	Extractor
      def 		_lowerCamelCase      (		self      ,       a__       ):
         from .file_utils import hash_url_to_filename

         # Path where we extract compressed archives
         # We extract in the cache dir, and get the extracted path name by hashing the original path"
         A_     :				Dict			      =	os.path.abspath(a__       )
         return os.path.join(self.extract_dir      ,       hash_url_to_filename(a__       )       )
      def 		_lowerCamelCase      (		self      ,       a__      ,       a__       ):
         return force_extract or (
             not os.path.isfile(a__       ) and not (os.path.isdir(a__       ) and os.listdir(a__       ))
         )






      def 		_lowerCamelCase      (		self      ,       a__      ,       a__ = False       ):
         A_     :				Optional[Any]			      =	self.extractor.infer_extractor_format(a__       )
         if not extractor_format:
            return input_path
         A_     :				Dict			      =	self._get_output_path(a__       )
         if self._do_extract(a__      ,       a__       ):
            self.extractor.extract(a__      ,       a__      ,       a__       )
         return output_path






class    _UpperCAmelCase							(		UpperCamelCase__     ):
      @classmethod
      @abstractmethod
      def 		_lowerCamelCase      (		cls      ,       a__      ,       **a__       ):
         ...






      @staticmethod
      @abstractmethod
      def 		_lowerCamelCase      (		a__      ,       a__       ):
         ...






class    _UpperCAmelCase							(		UpperCamelCase__			,       UpperCamelCase__     ):
      a						       =							[]
      @staticmethod
      def 		_lowerCamelCase      (		a__      ,       a__       ):
         with open(a__      ,       """rb"""       ) as f:
            return f.read(a__       )






      @classmethod
      def 		_lowerCamelCase      (		cls      ,       a__      ,       a__ = b""       ):
         if not magic_number:
            A_     :				List[Any]			      =	max(len(a__       ) for cls_magic_number in cls.magic_numbers       )
            try:
               A_     :				int			      =	cls.read_magic_number(a__      ,       a__       )
            except OSError:
               return False
         return any(magic_number.startswith(a__       ) for cls_magic_number in cls.magic_numbers       )






class    _UpperCAmelCase							(		UpperCamelCase__     ):
      @classmethod
      def 		_lowerCamelCase      (		cls      ,       a__      ,       **a__       ):
         return tarfile.is_tarfile(a__       )
      @staticmethod
      def 		_lowerCamelCase      (		a__      ,       a__       ):

         def resolved(a__       ) -> str:
            return os.path.realpath(os.path.abspath(a__       )       )

         def badpath(a__      ,       a__       ) -> bool:
            # joinpath will ignore base if path is absolute
            return not resolved(os.path.join(a__      ,       a__       )       ).startswith(a__       )

         def badlink(a__      ,       a__       ) -> bool:
            # Links are interpreted relative to the directory containing the link
            A_     :				str			      =	resolved(os.path.join(a__      ,       os.path.dirname(info.name       )       )       )
            return badpath(info.linkname      ,       base=a__       )

         A_     :				Optional[Any]			      =	resolved(a__       )

         for finfo in members:
            if badpath(finfo.name      ,       a__       ):
               logger.error(F"""Extraction of {finfo.name} is blocked (illegal path)"""       )
            elif finfo.issym() and badlink(a__      ,       a__       ):
               logger.error(F"""Extraction of {finfo.name} is blocked: Symlink to {finfo.linkname}"""       )
            elif finfo.islnk() and badlink(a__      ,       a__       ):
               logger.error(F"""Extraction of {finfo.name} is blocked: Hard link to {finfo.linkname}"""       )
            else:
               yield finfo






      @staticmethod
      def 		_lowerCamelCase      (		a__      ,       a__       ):
         os.makedirs(a__      ,       exist_ok=a__       )
         A_     :				int			      =	tarfile.open(a__       )
         tar_file.extractall(a__      ,       members=TarExtractor.safemembers(a__      ,       a__       )       )
         tar_file.close()






class    _UpperCAmelCase							(		UpperCamelCase__     ):
      a						       =							[B"""\x1F\x8B"""]
      @staticmethod
      def 		_lowerCamelCase      (		a__      ,       a__       ):
         with gzip.open(a__      ,       """rb"""       ) as gzip_file:
            with open(a__      ,       """wb"""       ) as extracted_file:
               shutil.copyfileobj(a__      ,       a__       )






class    _UpperCAmelCase							(		UpperCamelCase__     ):
      a						       =							[
          B"""PK\x03\x04""",
          B"""PK\x05\x06""",  # empty archive
          B"""PK\x07\x08""",  # spanned archive
      ]
      @classmethod
      def 		_lowerCamelCase      (		cls      ,       a__      ,       a__ = b""       ):
         if super().is_extractable(a__      ,       magic_number=a__       ):
            return True
         try:
            # Alternative version of zipfile.is_zipfile that has less false positives, but misses executable zip archives.
            # From: https://github.com/python/cpython/pull/5053
            from zipfile import (
                _CD_SIGNATURE,
                _ECD_DISK_NUMBER,
                _ECD_DISK_START,
                _ECD_ENTRIES_TOTAL,
                _ECD_OFFSET,
                _ECD_SIZE,
                _EndRecData,
                sizeCentralDir,
                stringCentralDir,
                structCentralDir,
            )

            with open(a__      ,       """rb"""       ) as fp:
               A_     :				Dict			      =	_EndRecData(a__       )
               if endrec:
                  if endrec[_ECD_ENTRIES_TOTAL] == 0 and endrec[_ECD_SIZE] == 0 and endrec[_ECD_OFFSET] == 0:
                     return True  # Empty zipfiles are still zipfiles
                  elif endrec[_ECD_DISK_NUMBER] == endrec[_ECD_DISK_START]:
                     fp.seek(endrec[_ECD_OFFSET]       )  # Central directory is on the same disk
                     if fp.tell() == endrec[_ECD_OFFSET] and endrec[_ECD_SIZE] >= sizeCentralDir:
                        A_     :				int			      =	fp.read(a__       )  # CD is where we expect it to be
                        if len(a__       ) == sizeCentralDir:
                           A_     :				Optional[int]			      =	struct.unpack(a__      ,       a__       )  # CD is the right size
                           if centdir[_CD_SIGNATURE] == stringCentralDir:
                              return True  # First central directory entry  has correct magic number
            return False
         except Exception:  # catch all errors in case future python versions change the zipfile internals
            return False






      @staticmethod
      def 		_lowerCamelCase      (		a__      ,       a__       ):
         os.makedirs(a__      ,       exist_ok=a__       )
         with zipfile.ZipFile(a__      ,       """r"""       ) as zip_file:
            zip_file.extractall(a__       )
            zip_file.close()






class    _UpperCAmelCase							(		UpperCamelCase__     ):
      a						       =							[B"""\xFD\x37\x7A\x58\x5A\x00"""]
      @staticmethod
      def 		_lowerCamelCase      (		a__      ,       a__       ):
         with lzma.open(a__       ) as compressed_file:
            with open(a__      ,       """wb"""       ) as extracted_file:
               shutil.copyfileobj(a__      ,       a__       )






class    _UpperCAmelCase							(		UpperCamelCase__     ):
      a						       =							[B"""Rar!\x1a\x07\x00""", B"""Rar!\x1a\x07\x01\x00"""]  # RAR_ID  # RAR5_ID
      @staticmethod
      def 		_lowerCamelCase      (		a__      ,       a__       ):
         if not config.RARFILE_AVAILABLE:
            raise ImportError("""Please pip install rarfile"""       )
         import rarfile

         os.makedirs(a__      ,       exist_ok=a__       )
         A_     :				int			      =	rarfile.RarFile(a__       )
         rf.extractall(a__       )
         rf.close()






class    _UpperCAmelCase							(		UpperCamelCase__     ):
      a						       =							[B"""\x28\xb5\x2F\xFD"""]
      @staticmethod
      def 		_lowerCamelCase      (		a__      ,       a__       ):
         if not config.ZSTANDARD_AVAILABLE:
            raise ImportError("""Please pip install zstandard"""       )
         import zstandard as zstd

         A_     :				Any			      =	zstd.ZstdDecompressor()
         with open(a__      ,       """rb"""       ) as ifh, open(a__      ,       """wb"""       ) as ofh:
            dctx.copy_stream(a__      ,       a__       )






class    _UpperCAmelCase							(		UpperCamelCase__     ):
      a						       =							[B"""\x42\x5A\x68"""]
      @staticmethod
      def 		_lowerCamelCase      (		a__      ,       a__       ):
         with bza.open(a__      ,       """rb"""       ) as compressed_file:
            with open(a__      ,       """wb"""       ) as extracted_file:
               shutil.copyfileobj(a__      ,       a__       )






class    _UpperCAmelCase							(		UpperCamelCase__     ):
      a						       =							[B"""\x37\x7A\xBC\xAF\x27\x1C"""]
      @staticmethod
      def 		_lowerCamelCase      (		a__      ,       a__       ):
         if not config.PY7ZR_AVAILABLE:
            raise ImportError("""Please pip install py7zr"""       )
         import pyazr

         os.makedirs(a__      ,       exist_ok=a__       )
         with pyazr.SevenZipFile(a__      ,       """r"""       ) as archive:
            archive.extractall(a__       )






class    _UpperCAmelCase							(		UpperCamelCase__     ):
      a						       =							[B"""\x04\x22\x4D\x18"""]
      @staticmethod
      def 		_lowerCamelCase      (		a__      ,       a__       ):
         if not config.LZ4_AVAILABLE:
            raise ImportError("""Please pip install lz4"""       )
         import lza.frame

         with lza.frame.open(a__      ,       """rb"""       ) as compressed_file:
            with open(a__      ,       """wb"""       ) as extracted_file:
               shutil.copyfileobj(a__      ,       a__       )






class    _UpperCAmelCase							:
      #  Put zip file to the last, b/c it is possible wrongly detected as zip (I guess it means: as tar or gzip)
      a						       =							{
          "tar": TarExtractor,
          "gzip": GzipExtractor,
          "zip": ZipExtractor,
          "xz": XzExtractor,
          "rar": RarExtractor,
          "zstd": ZstdExtractor,
          "bz2": BzipaExtractor,
          "7z": SevenZipExtractor,  # <Added version="2.4.0"/>
          "lz4": LzaExtractor,  # <Added version="2.4.0"/>
      }
      @classmethod
      def 		_lowerCamelCase      (		cls       ):
         return max(
             len(a__       )
             for extractor in cls.extractors.values()
             if issubclass(a__      ,       a__       )
             for extractor_magic_number in extractor.magic_numbers       )
      @staticmethod
      def 		_lowerCamelCase      (		a__      ,       a__       ):
         try:
            return MagicNumberBaseExtractor.read_magic_number(a__      ,       magic_number_length=a__       )
         except OSError:
            return b""
      @classmethod
      def 		_lowerCamelCase      (		cls      ,       a__      ,       a__ = False       ):
         warnings.warn(
             """Method 'is_extractable' was deprecated in version 2.4.0 and will be removed in 3.0.0. """
             """Use 'infer_extractor_format' instead."""      ,       category=a__      ,       )
         A_     :				Dict			      =	cls.infer_extractor_format(a__       )
         if extractor_format:
            return True if not return_extractor else (True, cls.extractors[extractor_format])
         return False if not return_extractor else (False, None)
      @classmethod
      def 		_lowerCamelCase      (		cls      ,       a__       ):  # <Added version="2.4.0"/>
         A_     :				Optional[Any]			      =	cls._get_magic_number_max_length()
         A_     :				Tuple			      =	cls._read_magic_number(a__      ,       a__       )
         for extractor_format, extractor in cls.extractors.items():
            if extractor.is_extractable(a__      ,       magic_number=a__       ):
               return extractor_format






      @classmethod
      def 		_lowerCamelCase      (		cls      ,       a__      ,       a__      ,       a__ = None      ,       a__ = "deprecated"      ,       ):
         os.makedirs(os.path.dirname(a__       )      ,       exist_ok=a__       )
         # Prevent parallel extractions
         A_     :				List[Any]			      =	str(Path(a__       ).with_suffix(""".lock"""       )       )
         with FileLock(a__       ):
            shutil.rmtree(a__      ,       ignore_errors=a__       )
            if extractor_format or extractor != "deprecated":
               if extractor != "deprecated" or not isinstance(a__      ,       a__       ):  # passed as positional arg
                  warnings.warn(
                      """Parameter 'extractor' was deprecated in version 2.4.0 and will be removed in 3.0.0. """
                      """Use 'extractor_format' instead."""      ,       category=a__      ,       )
                  A_     :				Union[str, Any]			      =	extractor if extractor != """deprecated""" else extractor_format
               else:
                  A_     :				Optional[int]			      =	cls.extractors[extractor_format]
               return extractor.extract(a__      ,       a__       )
            else:
               warnings.warn(
                   """Parameter 'extractor_format' was made required in version 2.4.0 and not passing it will raise an """
                   """exception in 3.0.0."""      ,       category=a__      ,       )
               for extractor in cls.extractors.values():
                  if extractor.is_extractable(a__       ):
                     return extractor.extract(a__      ,       a__       )













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__      ,       )






