"""simple docstring"""




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						,__UpperCAmelCase = None   )    -> int:
													A__		   =							(
													    os.path.join(__UpperCAmelCase						,config.EXTRACTED_DATASETS_DIR   ) if cache_dir else config.EXTRACTED_DATASETS_PATH
													)
													A__		   =							Extractor





						def  snake_case__		(				self						,__UpperCAmelCase   )    -> str:
													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__		   =							os.path.abspath(__UpperCAmelCase   )
													return os.path.join(self.extract_dir						,hash_url_to_filename(__UpperCAmelCase   )   )





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase   )    -> bool:
													return force_extract or (
													    not os.path.isfile(__UpperCAmelCase   ) and not (os.path.isdir(__UpperCAmelCase   ) and os.listdir(__UpperCAmelCase   ))
													)





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase = False   )    -> str:
													A__		   =							self.extractor.infer_extractor_format(__UpperCAmelCase   )
													if not extractor_format:
																				return input_path
													A__		   =							self._get_output_path(__UpperCAmelCase   )
													if self._do_extract(__UpperCAmelCase						,__UpperCAmelCase   ):
																				self.extractor.extract(__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase   )
													return output_path






class 			UpperCamelCase__(	__A       ):





						@classmethod
						@abstractmethod
						def  snake_case__		(				cls						,__UpperCAmelCase						,**__UpperCAmelCase   )    -> bool:
													...





						@staticmethod
						@abstractmethod
						def  snake_case__		(				__UpperCAmelCase						,__UpperCAmelCase   )    -> None:
													...






class 			UpperCamelCase__(	__A						,  __A       ):
						lowerCAmelCase__     :  List[bytes]  							=						[]





						@staticmethod
						def  snake_case__		(				__UpperCAmelCase						,__UpperCAmelCase   )    -> Optional[int]:
													with open(__UpperCAmelCase						,'rb'   ) as f:
																				return f.read(__UpperCAmelCase   )





						@classmethod
						def  snake_case__		(				cls						,__UpperCAmelCase						,__UpperCAmelCase = b""   )    -> bool:
													if not magic_number:
																				A__		   =							max(len(__UpperCAmelCase   ) for cls_magic_number in cls.magic_numbers   )
																				try:
																											A__		   =							cls.read_magic_number(__UpperCAmelCase						,__UpperCAmelCase   )
																				except OSError:
																											return False
													return any(magic_number.startswith(__UpperCAmelCase   ) for cls_magic_number in cls.magic_numbers   )






class 			UpperCamelCase__(	__A       ):





						@classmethod
						def  snake_case__		(				cls						,__UpperCAmelCase						,**__UpperCAmelCase   )    -> bool:
													return tarfile.is_tarfile(__UpperCAmelCase   )





						@staticmethod
						def  snake_case__		(				__UpperCAmelCase						,__UpperCAmelCase   )    -> List[Any]:

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

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

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

													A__		   =							resolved(__UpperCAmelCase   )

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





						@staticmethod
						def  snake_case__		(				__UpperCAmelCase						,__UpperCAmelCase   )    -> None:
													os.makedirs(__UpperCAmelCase						,exist_ok=__UpperCAmelCase   )
													A__		   =							tarfile.open(__UpperCAmelCase   )
													tar_file.extractall(__UpperCAmelCase						,members=TarExtractor.safemembers(__UpperCAmelCase						,__UpperCAmelCase   )   )
													tar_file.close()






class 			UpperCamelCase__(	__A       ):
						lowerCAmelCase__     :  List[str]  							=						[B'\x1F\x8B']





						@staticmethod
						def  snake_case__		(				__UpperCAmelCase						,__UpperCAmelCase   )    -> None:
													with gzip.open(__UpperCAmelCase						,'rb'   ) as gzip_file:
																				with open(__UpperCAmelCase						,'wb'   ) as extracted_file:
																											shutil.copyfileobj(__UpperCAmelCase						,__UpperCAmelCase   )






class 			UpperCamelCase__(	__A       ):
						lowerCAmelCase__     :  Union[str, Any]  							=						[
						    B'PK\x03\x04',
						    B'PK\x05\x06',  # empty archive
						    B'PK\x07\x08',  # spanned archive
						]





						@classmethod
						def  snake_case__		(				cls						,__UpperCAmelCase						,__UpperCAmelCase = b""   )    -> bool:
													if super().is_extractable(__UpperCAmelCase						,magic_number=__UpperCAmelCase   ):
																				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(__UpperCAmelCase						,'rb'   ) as fp:
																											A__		   =							_EndRecData(__UpperCAmelCase   )
																											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__		   =							fp.read(__UpperCAmelCase   )  # CD is where we expect it to be
																																																if len(__UpperCAmelCase   ) == sizeCentralDir:
																																																							A__		   =							struct.unpack(__UpperCAmelCase						,__UpperCAmelCase   )  # 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  snake_case__		(				__UpperCAmelCase						,__UpperCAmelCase   )    -> None:
													os.makedirs(__UpperCAmelCase						,exist_ok=__UpperCAmelCase   )
													with zipfile.ZipFile(__UpperCAmelCase						,'r'   ) as zip_file:
																				zip_file.extractall(__UpperCAmelCase   )
																				zip_file.close()






class 			UpperCamelCase__(	__A       ):
						lowerCAmelCase__     :  Any  							=						[B'\xFD\x37\x7A\x58\x5A\x00']





						@staticmethod
						def  snake_case__		(				__UpperCAmelCase						,__UpperCAmelCase   )    -> None:
													with lzma.open(__UpperCAmelCase   ) as compressed_file:
																				with open(__UpperCAmelCase						,'wb'   ) as extracted_file:
																											shutil.copyfileobj(__UpperCAmelCase						,__UpperCAmelCase   )






class 			UpperCamelCase__(	__A       ):
						lowerCAmelCase__     :  Optional[int]  							=						[B'Rar!\x1a\x07\x00', B'Rar!\x1a\x07\x01\x00']  # RAR_ID  # RAR5_ID





						@staticmethod
						def  snake_case__		(				__UpperCAmelCase						,__UpperCAmelCase   )    -> None:
													if not config.RARFILE_AVAILABLE:
																				raise ImportError('Please pip install rarfile'   )
													import rarfile

													os.makedirs(__UpperCAmelCase						,exist_ok=__UpperCAmelCase   )
													A__		   =							rarfile.RarFile(__UpperCAmelCase   )
													rf.extractall(__UpperCAmelCase   )
													rf.close()






class 			UpperCamelCase__(	__A       ):
						lowerCAmelCase__     :  Dict  							=						[B'\x28\xb5\x2F\xFD']





						@staticmethod
						def  snake_case__		(				__UpperCAmelCase						,__UpperCAmelCase   )    -> None:
													if not config.ZSTANDARD_AVAILABLE:
																				raise ImportError('Please pip install zstandard'   )
													import zstandard as zstd

													A__		   =							zstd.ZstdDecompressor()
													with open(__UpperCAmelCase						,'rb'   ) as ifh, open(__UpperCAmelCase						,'wb'   ) as ofh:
																				dctx.copy_stream(__UpperCAmelCase						,__UpperCAmelCase   )






class 			UpperCamelCase__(	__A       ):
						lowerCAmelCase__     :  Optional[Any]  							=						[B'\x42\x5A\x68']





						@staticmethod
						def  snake_case__		(				__UpperCAmelCase						,__UpperCAmelCase   )    -> None:
													with bza.open(__UpperCAmelCase						,'rb'   ) as compressed_file:
																				with open(__UpperCAmelCase						,'wb'   ) as extracted_file:
																											shutil.copyfileobj(__UpperCAmelCase						,__UpperCAmelCase   )






class 			UpperCamelCase__(	__A       ):
						lowerCAmelCase__     :  str  							=						[B'\x37\x7A\xBC\xAF\x27\x1C']





						@staticmethod
						def  snake_case__		(				__UpperCAmelCase						,__UpperCAmelCase   )    -> None:
													if not config.PY7ZR_AVAILABLE:
																				raise ImportError('Please pip install py7zr'   )
													import pyazr

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






class 			UpperCamelCase__(	__A       ):
						lowerCAmelCase__     :  int  							=						[B'\x04\x22\x4D\x18']





						@staticmethod
						def  snake_case__		(				__UpperCAmelCase						,__UpperCAmelCase   )    -> None:
													if not config.LZ4_AVAILABLE:
																				raise ImportError('Please pip install lz4'   )
													import lza.frame

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






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)
						lowerCAmelCase__     :  Dict[str, Type[BaseExtractor]]  							=						{
						    "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  snake_case__		(				cls   )    -> List[str]:
													return max(
													    len(__UpperCAmelCase   )
													    for extractor in cls.extractors.values()
													    if issubclass(__UpperCAmelCase						,__UpperCAmelCase   )
													    for extractor_magic_number in extractor.magic_numbers   )





						@staticmethod
						def  snake_case__		(				__UpperCAmelCase						,__UpperCAmelCase   )    -> List[str]:
													try:
																				return MagicNumberBaseExtractor.read_magic_number(__UpperCAmelCase						,magic_number_length=__UpperCAmelCase   )
													except OSError:
																				return b""





						@classmethod
						def  snake_case__		(				cls						,__UpperCAmelCase						,__UpperCAmelCase = False   )    -> bool:
													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=__UpperCAmelCase						,)
													A__		   =							cls.infer_extractor_format(__UpperCAmelCase   )
													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  snake_case__		(				cls						,__UpperCAmelCase   )    -> str:  # <Added version="2.4.0"/>
													A__		   =							cls._get_magic_number_max_length()
													A__		   =							cls._read_magic_number(__UpperCAmelCase						,__UpperCAmelCase   )
													for extractor_format, extractor in cls.extractors.items():
																				if extractor.is_extractable(__UpperCAmelCase						,magic_number=__UpperCAmelCase   ):
																											return extractor_format





						@classmethod
						def  snake_case__		(				cls						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase = None						,__UpperCAmelCase = "deprecated"						,)    -> None:
													os.makedirs(os.path.dirname(__UpperCAmelCase   )						,exist_ok=__UpperCAmelCase   )
													# Prevent parallel extractions
													A__		   =							str(Path(__UpperCAmelCase   ).with_suffix('.lock'   )   )
													with FileLock(__UpperCAmelCase   ):
																				shutil.rmtree(__UpperCAmelCase						,ignore_errors=__UpperCAmelCase   )
																				if extractor_format or extractor != "deprecated":
																											if extractor != "deprecated" or not isinstance(__UpperCAmelCase						,__UpperCAmelCase   ):  # 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=__UpperCAmelCase						,)
																																		A__		   =							extractor if extractor != 'deprecated' else extractor_format
																											else:
																																		A__		   =							cls.extractors[extractor_format]
																											return extractor.extract(__UpperCAmelCase						,__UpperCAmelCase   )
																				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=__UpperCAmelCase						,)
																											for extractor in cls.extractors.values():
																																		if extractor.is_extractable(__UpperCAmelCase   ):
																																									return extractor.extract(__UpperCAmelCase						,__UpperCAmelCase   )






"""simple docstring"""




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, 20_48, 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						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase = 3						,__UpperCAmelCase = 1						,__UpperCAmelCase = "relu"   )    -> Any:
													super().__init__()
													A__		   =							nn.Convad(
													    __UpperCAmelCase						,__UpperCAmelCase						,kernel_size=__UpperCAmelCase						,stride=__UpperCAmelCase						,padding=kernel_size // 2						,bias=__UpperCAmelCase   )
													A__		   =							nn.BatchNormad(__UpperCAmelCase   )
													A__		   =							ACTaFN[activation] if activation is not None else nn.Identity()





						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Tensor:
													A__		   =							self.convolution(__UpperCAmelCase   )
													A__		   =							self.normalization(__UpperCAmelCase   )
													A__		   =							self.activation(__UpperCAmelCase   )
													return hidden_state






class 			UpperCamelCase__(	nn.Module       ):





						def __init__(				self						,__UpperCAmelCase   )    -> Any:
													super().__init__()
													A__		   =							ResNetConvLayer(
													    config.num_channels						,config.embedding_size						,kernel_size=7						,stride=2						,activation=config.hidden_act   )
													A__		   =							nn.MaxPoolad(kernel_size=3						,stride=2						,padding=1   )
													A__		   =							config.num_channels





						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Tensor:
													A__		   =							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__		   =							self.embedder(__UpperCAmelCase   )
													A__		   =							self.pooler(__UpperCAmelCase   )
													return embedding






class 			UpperCamelCase__(	nn.Module       ):





						def __init__(				self						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase = 2   )    -> Optional[Any]:
													super().__init__()
													A__		   =							nn.Convad(__UpperCAmelCase						,__UpperCAmelCase						,kernel_size=1						,stride=__UpperCAmelCase						,bias=__UpperCAmelCase   )
													A__		   =							nn.BatchNormad(__UpperCAmelCase   )





						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Tensor:
													A__		   =							self.convolution(__UpperCAmelCase   )
													A__		   =							self.normalization(__UpperCAmelCase   )
													return hidden_state






class 			UpperCamelCase__(	nn.Module       ):





						def __init__(				self						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase = 1						,__UpperCAmelCase = "relu"   )    -> int:
													super().__init__()
													A__		   =							in_channels != out_channels or stride != 1
													A__		   =							(
													    ResNetShortCut(__UpperCAmelCase						,__UpperCAmelCase						,stride=__UpperCAmelCase   ) if should_apply_shortcut else nn.Identity()
													)
													A__		   =							nn.Sequential(
													    ResNetConvLayer(__UpperCAmelCase						,__UpperCAmelCase						,stride=__UpperCAmelCase   )						,ResNetConvLayer(__UpperCAmelCase						,__UpperCAmelCase						,activation=__UpperCAmelCase   )						,)
													A__		   =							ACTaFN[activation]





						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Union[str, Any]:
													A__		   =							hidden_state
													A__		   =							self.layer(__UpperCAmelCase   )
													A__		   =							self.shortcut(__UpperCAmelCase   )
													hidden_state += residual
													A__		   =							self.activation(__UpperCAmelCase   )
													return hidden_state






class 			UpperCamelCase__(	nn.Module       ):





						def __init__(				self						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase = 1						,__UpperCAmelCase = "relu"						,__UpperCAmelCase = 4   )    -> int:
													super().__init__()
													A__		   =							in_channels != out_channels or stride != 1
													A__		   =							out_channels // reduction
													A__		   =							(
													    ResNetShortCut(__UpperCAmelCase						,__UpperCAmelCase						,stride=__UpperCAmelCase   ) if should_apply_shortcut else nn.Identity()
													)
													A__		   =							nn.Sequential(
													    ResNetConvLayer(__UpperCAmelCase						,__UpperCAmelCase						,kernel_size=1   )						,ResNetConvLayer(__UpperCAmelCase						,__UpperCAmelCase						,stride=__UpperCAmelCase   )						,ResNetConvLayer(__UpperCAmelCase						,__UpperCAmelCase						,kernel_size=1						,activation=__UpperCAmelCase   )						,)
													A__		   =							ACTaFN[activation]





						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Optional[Any]:
													A__		   =							hidden_state
													A__		   =							self.layer(__UpperCAmelCase   )
													A__		   =							self.shortcut(__UpperCAmelCase   )
													hidden_state += residual
													A__		   =							self.activation(__UpperCAmelCase   )
													return hidden_state






class 			UpperCamelCase__(	nn.Module       ):





						def __init__(				self						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase						,__UpperCAmelCase = 2						,__UpperCAmelCase = 2						,)    -> Any:
													super().__init__()

													A__		   =							ResNetBottleNeckLayer if config.layer_type == 'bottleneck' else ResNetBasicLayer

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





						def  snake_case__		(				self						,__UpperCAmelCase   )    -> Tensor:
													A__		   =							input
													for layer in self.layers:
																				A__		   =							layer(__UpperCAmelCase   )
													return hidden_state






class 			UpperCamelCase__(	nn.Module       ):





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





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase = False						,__UpperCAmelCase = True   )    -> BaseModelOutputWithNoAttention:
													A__		   =							() if output_hidden_states else None

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

																				A__		   =							stage_module(__UpperCAmelCase   )

													if output_hidden_states:
																				A__		   =							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=__UpperCAmelCase						,hidden_states=__UpperCAmelCase						,)






class 			UpperCamelCase__(	__A       ):
						lowerCAmelCase__     :  str  							=						ResNetConfig
						lowerCAmelCase__     :  str  							=						'resnet'
						lowerCAmelCase__     :  int  							=						'pixel_values'
						lowerCAmelCase__     :  Any  							=						True





						def  snake_case__		(				self						,__UpperCAmelCase   )    -> List[Any]:
													if isinstance(__UpperCAmelCase						,nn.Convad   ):
																				nn.init.kaiming_normal_(module.weight						,mode='fan_out'						,nonlinearity='relu'   )
													elif isinstance(__UpperCAmelCase						,(nn.BatchNormad, nn.GroupNorm)   ):
																				nn.init.constant_(module.weight						,1   )
																				nn.init.constant_(module.bias						,0   )





						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase=False   )    -> Any:
													if isinstance(__UpperCAmelCase						,__UpperCAmelCase   ):
																				A__		   =							value






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

__lowerCamelCase							 =     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						,__UpperCAmelCase   )    -> Union[str, Any]:
													super().__init__(__UpperCAmelCase   )
													A__		   =							config
													A__		   =							ResNetEmbeddings(__UpperCAmelCase   )
													A__		   =							ResNetEncoder(__UpperCAmelCase   )
													A__		   =							nn.AdaptiveAvgPoolad((1, 1)   )
													# Initialize weights and apply final processing
													self.post_init()





						@add_start_docstrings_to_model_forward(__UpperCAmelCase   )
						@add_code_sample_docstrings(
						    checkpoint=_CHECKPOINT_FOR_DOC						,output_type=__UpperCAmelCase						,config_class=_CONFIG_FOR_DOC						,modality='vision'						,expected_output=_EXPECTED_OUTPUT_SHAPE						,)
						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase = None						,__UpperCAmelCase = None   )    -> BaseModelOutputWithPoolingAndNoAttention:
													A__		   =							(
													    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
													)
													A__		   =							return_dict if return_dict is not None else self.config.use_return_dict

													A__		   =							self.embedder(__UpperCAmelCase   )

													A__		   =							self.encoder(
													    __UpperCAmelCase						,output_hidden_states=__UpperCAmelCase						,return_dict=__UpperCAmelCase   )

													A__		   =							encoder_outputs[0]

													A__		   =							self.pooler(__UpperCAmelCase   )

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

													return BaseModelOutputWithPoolingAndNoAttention(
													    last_hidden_state=__UpperCAmelCase						,pooler_output=__UpperCAmelCase						,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						,__UpperCAmelCase   )    -> Tuple:
													super().__init__(__UpperCAmelCase   )
													A__		   =							config.num_labels
													A__		   =							ResNetModel(__UpperCAmelCase   )
													# classification head
													A__		   =							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(__UpperCAmelCase   )
						@add_code_sample_docstrings(
						    checkpoint=_IMAGE_CLASS_CHECKPOINT						,output_type=__UpperCAmelCase						,config_class=_CONFIG_FOR_DOC						,expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT						,)
						def  snake_case__		(				self						,__UpperCAmelCase = None						,__UpperCAmelCase = None						,__UpperCAmelCase = None						,__UpperCAmelCase = None						,)    -> ImageClassifierOutputWithNoAttention:
													A__		   =							return_dict if return_dict is not None else self.config.use_return_dict

													A__		   =							self.resnet(__UpperCAmelCase						,output_hidden_states=__UpperCAmelCase						,return_dict=__UpperCAmelCase   )

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

													A__		   =							self.classifier(__UpperCAmelCase   )

													A__		   =							None

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

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

													return ImageClassifierOutputWithNoAttention(loss=__UpperCAmelCase						,logits=__UpperCAmelCase						,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						,__UpperCAmelCase   )    -> Optional[Any]:
													super().__init__(__UpperCAmelCase   )
													super()._init_backbone(__UpperCAmelCase   )

													A__		   =							[config.embedding_size] + config.hidden_sizes
													A__		   =							ResNetEmbeddings(__UpperCAmelCase   )
													A__		   =							ResNetEncoder(__UpperCAmelCase   )

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





						@add_start_docstrings_to_model_forward(__UpperCAmelCase   )
						@replace_return_docstrings(output_type=__UpperCAmelCase						,config_class=_CONFIG_FOR_DOC   )
						def  snake_case__		(				self						,__UpperCAmelCase						,__UpperCAmelCase = None						,__UpperCAmelCase = None   )    -> BackboneOutput:
													A__		   =							return_dict if return_dict is not None else self.config.use_return_dict
													A__		   =							(
													    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
													)

													A__		   =							self.embedder(__UpperCAmelCase   )

													A__		   =							self.encoder(__UpperCAmelCase						,output_hidden_states=__UpperCAmelCase						,return_dict=__UpperCAmelCase   )

													A__		   =							outputs.hidden_states

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

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

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





