
'''simple docstring'''
import argparse
import collections
import os
import re
import tempfile

import pandas as pd
from datasets import Dataset
from huggingface_hub import hf_hub_download, upload_folder

from transformers.utils import direct_transformers_import


# All paths are set with the intent you should run this script from the root of the repo with the command
# python utils/update_metadata.py
lowercase__											='src/transformers'


# This is to make sure the transformers module imported is the one in the repo.
lowercase__											=direct_transformers_import(TRANSFORMERS_PATH)


# Regexes that match TF/Flax/PT model names.
lowercase__											=re.compile(r'TF(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
lowercase__											=re.compile(r'Flax(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')
# Will match any TF or Flax model too so need to be in an else branch afterthe two previous regexes.
lowercase__											=re.compile(r'(.*)(?:Model|Encoder|Decoder|ForConditionalGeneration)')


# Fill this with tuples (pipeline_tag, model_mapping, auto_model)
lowercase__											=[
    ('pretraining', 'MODEL_FOR_PRETRAINING_MAPPING_NAMES', 'AutoModelForPreTraining'),
    ('feature-extraction', 'MODEL_MAPPING_NAMES', 'AutoModel'),
    ('audio-classification', 'MODEL_FOR_AUDIO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForAudioClassification'),
    ('text-generation', 'MODEL_FOR_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForCausalLM'),
    ('automatic-speech-recognition', 'MODEL_FOR_CTC_MAPPING_NAMES', 'AutoModelForCTC'),
    ('image-classification', 'MODEL_FOR_IMAGE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForImageClassification'),
    ('image-segmentation', 'MODEL_FOR_IMAGE_SEGMENTATION_MAPPING_NAMES', 'AutoModelForImageSegmentation'),
    ('fill-mask', 'MODEL_FOR_MASKED_LM_MAPPING_NAMES', 'AutoModelForMaskedLM'),
    ('object-detection', 'MODEL_FOR_OBJECT_DETECTION_MAPPING_NAMES', 'AutoModelForObjectDetection'),
    (
        'zero-shot-object-detection',
        'MODEL_FOR_ZERO_SHOT_OBJECT_DETECTION_MAPPING_NAMES',
        'AutoModelForZeroShotObjectDetection',
    ),
    ('question-answering', 'MODEL_FOR_QUESTION_ANSWERING_MAPPING_NAMES', 'AutoModelForQuestionAnswering'),
    ('text2text-generation', 'MODEL_FOR_SEQ_TO_SEQ_CAUSAL_LM_MAPPING_NAMES', 'AutoModelForSeq2SeqLM'),
    ('text-classification', 'MODEL_FOR_SEQUENCE_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForSequenceClassification'),
    ('automatic-speech-recognition', 'MODEL_FOR_SPEECH_SEQ_2_SEQ_MAPPING_NAMES', 'AutoModelForSpeechSeq2Seq'),
    (
        'table-question-answering',
        'MODEL_FOR_TABLE_QUESTION_ANSWERING_MAPPING_NAMES',
        'AutoModelForTableQuestionAnswering',
    ),
    ('token-classification', 'MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForTokenClassification'),
    ('multiple-choice', 'MODEL_FOR_MULTIPLE_CHOICE_MAPPING_NAMES', 'AutoModelForMultipleChoice'),
    (
        'next-sentence-prediction',
        'MODEL_FOR_NEXT_SENTENCE_PREDICTION_MAPPING_NAMES',
        'AutoModelForNextSentencePrediction',
    ),
    (
        'audio-frame-classification',
        'MODEL_FOR_AUDIO_FRAME_CLASSIFICATION_MAPPING_NAMES',
        'AutoModelForAudioFrameClassification',
    ),
    ('audio-xvector', 'MODEL_FOR_AUDIO_XVECTOR_MAPPING_NAMES', 'AutoModelForAudioXVector'),
    (
        'document-question-answering',
        'MODEL_FOR_DOCUMENT_QUESTION_ANSWERING_MAPPING_NAMES',
        'AutoModelForDocumentQuestionAnswering',
    ),
    (
        'visual-question-answering',
        'MODEL_FOR_VISUAL_QUESTION_ANSWERING_MAPPING_NAMES',
        'AutoModelForVisualQuestionAnswering',
    ),
    ('image-to-text', 'MODEL_FOR_FOR_VISION_2_SEQ_MAPPING_NAMES', 'AutoModelForVision2Seq'),
    (
        'zero-shot-image-classification',
        'MODEL_FOR_ZERO_SHOT_IMAGE_CLASSIFICATION_MAPPING_NAMES',
        'AutoModelForZeroShotImageClassification',
    ),
    ('depth-estimation', 'MODEL_FOR_DEPTH_ESTIMATION_MAPPING_NAMES', 'AutoModelForDepthEstimation'),
    ('video-classification', 'MODEL_FOR_VIDEO_CLASSIFICATION_MAPPING_NAMES', 'AutoModelForVideoClassification'),
    ('mask-generation', 'MODEL_FOR_MASK_GENERATION_MAPPING_NAMES', 'AutoModelForMaskGeneration'),
]






def      UpperCamelCase_				(      A__						):
	a_      				=						re.finditer(""".+?(?:(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|$)"""  ,      A__						)
	return [m.group(0						) for m in matches]






def      UpperCamelCase_				(      ):
	a_      				=						transformers_module.models.auto.configuration_auto.CONFIG_MAPPING_NAMES
	a_      				=						{
	    config.replace("""Config"""  ,      """"""						): model_type for model_type, config in config_maping_names.items()
	}

	# Dictionaries flagging if each model prefix has a backend in PT/TF/Flax.
	a_      				=						collections.defaultdict(A__						)
	a_      				=						collections.defaultdict(A__						)
	a_      				=						collections.defaultdict(A__						)

	# Let's lookup through all transformers object (once) and find if models are supported by a given backend.
	for attr_name in dir(A__						):
		a_      				=						None
		if _re_tf_models.match(A__						) is not None:
			a_      				=						tf_models
			a_      				=						_re_tf_models.match(A__						).groups()[0]
		elif _re_flax_models.match(A__						) is not None:
			a_      				=						flax_models
			a_      				=						_re_flax_models.match(A__						).groups()[0]
		elif _re_pt_models.match(A__						) is not None:
			a_      				=						pt_models
			a_      				=						_re_pt_models.match(A__						).groups()[0]

		if lookup_dict is not None:
			while len(A__						) > 0:
				if attr_name in model_prefix_to_model_type:
					a_      				=						True
					break
				# Try again after removing the last word in the name
				a_      				=						"""""".join(camel_case_split(A__						)[:-1]						)

	a_      				=						set(list(pt_models.keys()						) + list(tf_models.keys()						) + list(flax_models.keys()						)						)
	a_      				=						list(A__						)
	all_models.sort()

	a_      				=						{"""model_type""": all_models}
	a_      				=						[pt_models[t] for t in all_models]
	a_      				=						[tf_models[t] for t in all_models]
	a_      				=						[flax_models[t] for t in all_models]

	# Now let's use the auto-mapping names to make sure
	a_      				=						{}
	for t in all_models:
		if t in transformers_module.models.auto.processing_auto.PROCESSOR_MAPPING_NAMES:
			a_      				=						"""AutoProcessor"""
		elif t in transformers_module.models.auto.tokenization_auto.TOKENIZER_MAPPING_NAMES:
			a_      				=						"""AutoTokenizer"""
		elif t in transformers_module.models.auto.feature_extraction_auto.FEATURE_EXTRACTOR_MAPPING_NAMES:
			a_      				=						"""AutoFeatureExtractor"""
		else:
			# Default to AutoTokenizer if a model has nothing, for backward compatibility.
			a_      				=						"""AutoTokenizer"""

	a_      				=						[processors[t] for t in all_models]

	return pd.DataFrame(A__						)






def      UpperCamelCase_				(      A__						):
	a_      				=						[
	    transformers_module.models.auto.modeling_auto,
	    transformers_module.models.auto.modeling_tf_auto,
	    transformers_module.models.auto.modeling_flax_auto,
	]
	for pipeline_tag, model_mapping, auto_class in PIPELINE_TAGS_AND_AUTO_MODELS:
		a_      				=						[model_mapping, F'''TF_{model_mapping}''', F'''FLAX_{model_mapping}''']
		a_      				=						[auto_class, F'''TF_{auto_class}''', F'''Flax_{auto_class}''']
		# Loop through all three frameworks
		for module, cls, mapping in zip(A__  ,      A__  ,      A__						):
			# The type of pipeline may not exist in this framework
			if not hasattr(A__  ,      A__						):
				continue
			# First extract all model_names
			a_      				=						[]
			for name in getattr(A__  ,      A__						).values():
				if isinstance(A__  ,      A__						):
					model_names.append(A__						)
				else:
					model_names.extend(list(A__						)						)

            # Add pipeline tag and auto model class for those models
			table.update({model_name: (pipeline_tag, cls) for model_name in model_names}						)

	return table






def      UpperCamelCase_				(      A__  ,      A__						):
	a_      				=						get_frameworks_table()
	a_      				=						Dataset.from_pandas(A__						)

	a_      				=						hf_hub_download(
	    """huggingface/transformers-metadata"""  ,      """pipeline_tags.json"""  ,      repo_type="""dataset"""  ,      token=A__						)
	a_      				=						Dataset.from_json(A__						)
	a_      				=						{
	    tags_dataset[i]["""model_class"""]: (tags_dataset[i]["""pipeline_tag"""], tags_dataset[i]["""auto_class"""])
	    for i in range(len(A__						)						)
	}
	a_      				=						update_pipeline_and_auto_class_table(A__						)

	# Sort the model classes to avoid some nondeterministic updates to create false update commits.
	a_      				=						sorted(table.keys()						)
	a_      				=						pd.DataFrame(
	    {
	        """model_class""": model_classes,
	        """pipeline_tag""": [table[m][0] for m in model_classes],
	        """auto_class""": [table[m][1] for m in model_classes],
	    }						)
	a_      				=						Dataset.from_pandas(A__						)

	with tempfile.TemporaryDirectory() as tmp_dir:
		frameworks_dataset.to_json(os.path.join(A__  ,      """frameworks.json"""						)						)
		tags_dataset.to_json(os.path.join(A__  ,      """pipeline_tags.json"""						)						)

		if commit_sha is not None:
			a_      				=						(
			    F'''Update with commit {commit_sha}\n\nSee: '''
			    F'''https://github.com/huggingface/transformers/commit/{commit_sha}'''
			)
		else:
			a_      				=						"""Update"""

		upload_folder(
		    repo_id="""huggingface/transformers-metadata"""  ,      folder_path=A__  ,      repo_type="""dataset"""  ,      token=A__  ,      commit_message=A__  ,      )






def      UpperCamelCase_				(      ):
	a_      				=						{tag: cls for tag, _, cls in PIPELINE_TAGS_AND_AUTO_MODELS}
	a_      				=						transformers_module.pipelines.SUPPORTED_TASKS
	a_      				=						[]
	for key in pipeline_tasks:
		if key not in in_table:
			a_      				=						pipeline_tasks[key]["""pt"""]
			if isinstance(A__  ,      (list, tuple)						):
				a_      				=						model[0]
			a_      				=						model.__name__
			if model not in in_table.values():
				missing.append(A__						)

	if len(A__						) > 0:
		a_      				=						""", """.join(A__						)
		raise ValueError(
		    """The following pipeline tags are not present in the `PIPELINE_TAGS_AND_AUTO_MODELS` constant inside """
		    F'''`utils/update_metadata.py`: {msg}. Please add them!'''						)


if __name__ == "__main__":
		lowercase__											=argparse.ArgumentParser()
		parser.add_argument('--token', type=str, help='The token to use to push to the transformers-metadata dataset.')
		parser.add_argument('--commit_sha', type=str, help='The sha of the commit going with this update.')
		parser.add_argument('--check-only', action='store_true', help='Activate to just check all pipelines are present.')
		lowercase__											=parser.parse_args()

		if args.check_only:
				check_pipeline_tags()
		else:
				update_metadata(args.token, args.commit_sha)


'''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


lowercase__											=logging.get_logger(__name__)

# General docstring
lowercase__											='ResNetConfig'

# Base docstring
lowercase__											='microsoft/resnet-50'
lowercase__											=[1, 20_48, 7, 7]

# Image classification docstring
lowercase__											='microsoft/resnet-50'
lowercase__											='tiger cat'

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







class   a_ (      nn.Module					):




			def __init__(       self					,   UpperCAmelCase					,   UpperCAmelCase					,   UpperCAmelCase = 3					,   UpperCAmelCase = 1					,   UpperCAmelCase = "relu"	):
				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 					lowerCAmelCase__					(       self					,   UpperCAmelCase	):
				a_      				=						self.convolution(UpperCAmelCase	)
				a_      				=						self.normalization(UpperCAmelCase	)
				a_      				=						self.activation(UpperCAmelCase	)
				return hidden_state







class   a_ (      nn.Module					):




			def __init__(       self					,   UpperCAmelCase	):
				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 					lowerCAmelCase__					(       self					,   UpperCAmelCase	):
				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   a_ (      nn.Module					):




			def __init__(       self					,   UpperCAmelCase					,   UpperCAmelCase					,   UpperCAmelCase = 2	):
				super().__init__()
				a_      				=						nn.Convad(UpperCAmelCase					,   UpperCAmelCase					,   kernel_size=1					,   stride=UpperCAmelCase					,   bias=UpperCAmelCase	)
				a_      				=						nn.BatchNormad(UpperCAmelCase	)






			def 					lowerCAmelCase__					(       self					,   UpperCAmelCase	):
				a_      				=						self.convolution(UpperCAmelCase	)
				a_      				=						self.normalization(UpperCAmelCase	)
				return hidden_state







class   a_ (      nn.Module					):




			def __init__(       self					,   UpperCAmelCase					,   UpperCAmelCase					,   UpperCAmelCase = 1					,   UpperCAmelCase = "relu"	):
				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 					lowerCAmelCase__					(       self					,   UpperCAmelCase	):
				a_      				=						hidden_state
				a_      				=						self.layer(UpperCAmelCase	)
				a_      				=						self.shortcut(UpperCAmelCase	)
				hidden_state += residual
				a_      				=						self.activation(UpperCAmelCase	)
				return hidden_state







class   a_ (      nn.Module					):




			def __init__(       self					,   UpperCAmelCase					,   UpperCAmelCase					,   UpperCAmelCase = 1					,   UpperCAmelCase = "relu"					,   UpperCAmelCase = 4	):
				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 					lowerCAmelCase__					(       self					,   UpperCAmelCase	):
				a_      				=						hidden_state
				a_      				=						self.layer(UpperCAmelCase	)
				a_      				=						self.shortcut(UpperCAmelCase	)
				hidden_state += residual
				a_      				=						self.activation(UpperCAmelCase	)
				return hidden_state







class   a_ (      nn.Module					):




			def __init__(       self					,   UpperCAmelCase					,   UpperCAmelCase					,   UpperCAmelCase					,   UpperCAmelCase = 2					,   UpperCAmelCase = 2					,   ):
				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 					lowerCAmelCase__					(       self					,   UpperCAmelCase	):
				a_      				=						input
				for layer in self.layers:
					a_      				=						layer(UpperCAmelCase	)
				return hidden_state







class   a_ (      nn.Module					):




			def __init__(       self					,   UpperCAmelCase	):
				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 					lowerCAmelCase__					(       self					,   UpperCAmelCase					,   UpperCAmelCase = False					,   UpperCAmelCase = True	):
				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   a_ (      UpperCamelCase__					):
			lowerCamelCase__	:			List[Any]       =    ResNetConfig
			lowerCamelCase__	:			Dict       =    'resnet'
			lowerCamelCase__	:			Dict       =    'pixel_values'
			lowerCamelCase__	:			str       =    True




			def 					lowerCAmelCase__					(       self					,   UpperCAmelCase	):
				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 					lowerCAmelCase__					(       self					,   UpperCAmelCase					,   UpperCAmelCase=False	):
				if isinstance(UpperCAmelCase					,   UpperCAmelCase	):
					a_      				=						value







lowercase__											=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'

lowercase__											=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.'		,  UpperCamelCase__		,  )
class   a_ (      UpperCamelCase__					):




			def __init__(       self					,   UpperCAmelCase	):
				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 					lowerCAmelCase__					(       self					,   UpperCAmelCase					,   UpperCAmelCase = None					,   UpperCAmelCase = None	):
				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    '		,  UpperCamelCase__		,  )
class   a_ (      UpperCamelCase__					):




			def __init__(       self					,   UpperCAmelCase	):
				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 					lowerCAmelCase__					(       self					,   UpperCAmelCase = None					,   UpperCAmelCase = None					,   UpperCAmelCase = None					,   UpperCAmelCase = None					,   ):
				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    '		,  UpperCamelCase__		,  )
class   a_ (      UpperCamelCase__		,  UpperCamelCase__					):




			def __init__(       self					,   UpperCAmelCase	):
				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 					lowerCAmelCase__					(       self					,   UpperCAmelCase					,   UpperCAmelCase = None					,   UpperCAmelCase = None	):
				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					,   )
