






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


__UpperCamelCase					:		Union[str, Any]	  =						logging.get_logger(__name__)

# General docstring
__UpperCamelCase					:		List[Any]	  =						"""ResNetConfig"""

# Base docstring
__UpperCamelCase					:		Optional[int]	  =						"""microsoft/resnet-50"""
__UpperCamelCase					:		List[str]	  =						[1, 2048, 7, 7]

# Image classification docstring
__UpperCamelCase					:		int	  =						"""microsoft/resnet-50"""
__UpperCamelCase					:		List[str]	  =						"""tiger cat"""

__UpperCamelCase					:		List[Any]	  =						[
    """microsoft/resnet-50""",
    # See all resnet models at https://huggingface.co/models?filter=resnet
]


class   __SCREAMING_SNAKE_CASE(	nn.Module	):
							def __init__(     self:      List[Any]       ,	UpperCamelCase:      int       ,	UpperCamelCase:      int       ,	UpperCamelCase:      int = 3       ,	UpperCamelCase:      int = 1       ,	UpperCamelCase:      str = "relu"						)		->		List[Any]:
											super().__init__()
											snake_case__									=     nn.Convad(
											    UpperCamelCase       ,	UpperCamelCase       ,	kernel_size=UpperCamelCase       ,	stride=UpperCamelCase       ,	padding=kernel_size // 2       ,	bias=UpperCamelCase						)
											snake_case__									=     nn.BatchNormad(UpperCamelCase						)
											snake_case__									=     ACTaFN[activation] if activation is not None else nn.Identity()


							def lowerCAmelCase_ (     self:      Any       ,	UpperCamelCase:      Tensor						)		->		Tensor:
											snake_case__									=     self.convolution(UpperCamelCase						)
											snake_case__									=     self.normalization(UpperCamelCase						)
											snake_case__									=     self.activation(UpperCamelCase						)
											return hidden_state


class   __SCREAMING_SNAKE_CASE(	nn.Module	):
							def __init__(     self:      Dict       ,	UpperCamelCase:      ResNetConfig						)		->		Dict:
											super().__init__()
											snake_case__									=     ResNetConvLayer(
											    config.num_channels       ,	config.embedding_size       ,	kernel_size=7       ,	stride=2       ,	activation=config.hidden_act						)
											snake_case__									=     nn.MaxPoolad(kernel_size=3       ,	stride=2       ,	padding=1						)
											snake_case__									=     config.num_channels


							def lowerCAmelCase_ (     self:      Dict       ,	UpperCamelCase:      Tensor						)		->		Tensor:
											snake_case__									=     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.'						)
											snake_case__									=     self.embedder(UpperCamelCase						)
											snake_case__									=     self.pooler(UpperCamelCase						)
											return embedding


class   __SCREAMING_SNAKE_CASE(	nn.Module	):
							def __init__(     self:      Union[str, Any]       ,	UpperCamelCase:      int       ,	UpperCamelCase:      int       ,	UpperCamelCase:      int = 2						)		->		Union[str, Any]:
											super().__init__()
											snake_case__									=     nn.Convad(UpperCamelCase       ,	UpperCamelCase       ,	kernel_size=1       ,	stride=UpperCamelCase       ,	bias=UpperCamelCase						)
											snake_case__									=     nn.BatchNormad(UpperCamelCase						)


							def lowerCAmelCase_ (     self:      Tuple       ,	UpperCamelCase:      Tensor						)		->		Tensor:
											snake_case__									=     self.convolution(UpperCamelCase						)
											snake_case__									=     self.normalization(UpperCamelCase						)
											return hidden_state


class   __SCREAMING_SNAKE_CASE(	nn.Module	):
							def __init__(     self:      Tuple       ,	UpperCamelCase:      int       ,	UpperCamelCase:      int       ,	UpperCamelCase:      int = 1       ,	UpperCamelCase:      str = "relu"						)		->		Tuple:
											super().__init__()
											snake_case__									=     in_channels != out_channels or stride != 1
											snake_case__									=     (
											    ResNetShortCut(UpperCamelCase       ,	UpperCamelCase       ,	stride=UpperCamelCase						) if should_apply_shortcut else nn.Identity()
											)
											snake_case__									=     nn.Sequential(
											    ResNetConvLayer(UpperCamelCase       ,	UpperCamelCase       ,	stride=UpperCamelCase						)       ,	ResNetConvLayer(UpperCamelCase       ,	UpperCamelCase       ,	activation=UpperCamelCase						)       ,	)
											snake_case__									=     ACTaFN[activation]


							def lowerCAmelCase_ (     self:      List[str]       ,	UpperCamelCase:      Optional[Any]						)		->		Any:
											snake_case__									=     hidden_state
											snake_case__									=     self.layer(UpperCamelCase						)
											snake_case__									=     self.shortcut(UpperCamelCase						)
											hidden_state += residual
											snake_case__									=     self.activation(UpperCamelCase						)
											return hidden_state


class   __SCREAMING_SNAKE_CASE(	nn.Module	):
							def __init__(     self:      Tuple       ,	UpperCamelCase:      int       ,	UpperCamelCase:      int       ,	UpperCamelCase:      int = 1       ,	UpperCamelCase:      str = "relu"       ,	UpperCamelCase:      int = 4						)		->		Dict:
											super().__init__()
											snake_case__									=     in_channels != out_channels or stride != 1
											snake_case__									=     out_channels // reduction
											snake_case__									=     (
											    ResNetShortCut(UpperCamelCase       ,	UpperCamelCase       ,	stride=UpperCamelCase						) if should_apply_shortcut else nn.Identity()
											)
											snake_case__									=     nn.Sequential(
											    ResNetConvLayer(UpperCamelCase       ,	UpperCamelCase       ,	kernel_size=1						)       ,	ResNetConvLayer(UpperCamelCase       ,	UpperCamelCase       ,	stride=UpperCamelCase						)       ,	ResNetConvLayer(UpperCamelCase       ,	UpperCamelCase       ,	kernel_size=1       ,	activation=UpperCamelCase						)       ,	)
											snake_case__									=     ACTaFN[activation]


							def lowerCAmelCase_ (     self:      Any       ,	UpperCamelCase:      Tuple						)		->		Tuple:
											snake_case__									=     hidden_state
											snake_case__									=     self.layer(UpperCamelCase						)
											snake_case__									=     self.shortcut(UpperCamelCase						)
											hidden_state += residual
											snake_case__									=     self.activation(UpperCamelCase						)
											return hidden_state


class   __SCREAMING_SNAKE_CASE(	nn.Module	):
							def __init__(     self:      List[Any]       ,	UpperCamelCase:      ResNetConfig       ,	UpperCamelCase:      int       ,	UpperCamelCase:      int       ,	UpperCamelCase:      int = 2       ,	UpperCamelCase:      int = 2       ,	)		->		List[Any]:
											super().__init__()

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

											snake_case__									=     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:      Optional[int]       ,	UpperCamelCase:      Tensor						)		->		Tensor:
											snake_case__									=     input
											for layer in self.layers:
															snake_case__									=     layer(UpperCamelCase						)
											return hidden_state


class   __SCREAMING_SNAKE_CASE(	nn.Module	):
							def __init__(     self:      int       ,	UpperCamelCase:      ResNetConfig						)		->		List[Any]:
											super().__init__()
											snake_case__									=     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]       ,	)						)
											snake_case__									=     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:      Optional[int]       ,	UpperCamelCase:      Tensor       ,	UpperCamelCase:      bool = False       ,	UpperCamelCase:      bool = True						)		->		BaseModelOutputWithNoAttention:
											snake_case__									=     () if output_hidden_states else None

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

															snake_case__									=     stage_module(UpperCamelCase						)

											if output_hidden_states:
															snake_case__									=     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   __SCREAMING_SNAKE_CASE(	a_	):
							_UpperCAmelCase     =       ResNetConfig
							_UpperCAmelCase     =       "resnet"
							_UpperCAmelCase     =       "pixel_values"
							_UpperCAmelCase     =       True
							def lowerCAmelCase_ (     self:      List[Any]       ,	UpperCamelCase:      List[str]						)		->		Tuple:
											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:      str       ,	UpperCamelCase:      str       ,	UpperCamelCase:      int=False						)		->		Tuple:
											if isinstance(UpperCamelCase       ,	UpperCamelCase						):
															snake_case__									=     value


__UpperCamelCase					:		List[Any]	  =						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.
"""

__UpperCamelCase					:		List[Any]	  =						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."    ,  a_    ,  )
class   __SCREAMING_SNAKE_CASE(	a_	):
							def __init__(     self:      List[str]       ,	UpperCamelCase:      str						)		->		Optional[Any]:
											super().__init__(UpperCamelCase						)
											snake_case__									=     config
											snake_case__									=     ResNetEmbeddings(UpperCamelCase						)
											snake_case__									=     ResNetEncoder(UpperCamelCase						)
											snake_case__									=     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:      int       ,	UpperCamelCase:      Tensor       ,	UpperCamelCase:      Optional[bool] = None       ,	UpperCamelCase:      Optional[bool] = None						)		->		BaseModelOutputWithPoolingAndNoAttention:
											snake_case__									=     (
											    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
											)
											snake_case__									=     return_dict if return_dict is not None else self.config.use_return_dict

											snake_case__									=     self.embedder(UpperCamelCase						)

											snake_case__									=     self.encoder(
											    UpperCamelCase       ,	output_hidden_states=UpperCamelCase       ,	return_dict=UpperCamelCase						)

											snake_case__									=     encoder_outputs[0]

											snake_case__									=     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   __SCREAMING_SNAKE_CASE(	a_	):
							def __init__(     self:      Any       ,	UpperCamelCase:      Optional[int]						)		->		Optional[Any]:
											super().__init__(UpperCamelCase						)
											snake_case__									=     config.num_labels
											snake_case__									=     ResNetModel(UpperCamelCase						)
											# classification head
											snake_case__									=     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:      Optional[Any]       ,	UpperCamelCase:      Optional[torch.FloatTensor] = None       ,	UpperCamelCase:      Optional[torch.LongTensor] = None       ,	UpperCamelCase:      Optional[bool] = None       ,	UpperCamelCase:      Optional[bool] = None       ,	)		->		ImageClassifierOutputWithNoAttention:
											snake_case__									=     return_dict if return_dict is not None else self.config.use_return_dict

											snake_case__									=     self.resnet(UpperCamelCase       ,	output_hidden_states=UpperCamelCase       ,	return_dict=UpperCamelCase						)

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

											snake_case__									=     self.classifier(UpperCamelCase						)

											snake_case__									=     None

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

											if not return_dict:
															snake_case__									=     (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   __SCREAMING_SNAKE_CASE(	a_    ,  a_	):
							def __init__(     self:      Union[str, Any]       ,	UpperCamelCase:      Optional[Any]						)		->		List[str]:
											super().__init__(UpperCamelCase						)
											super()._init_backbone(UpperCamelCase						)

											snake_case__									=     [config.embedding_size] + config.hidden_sizes
											snake_case__									=     ResNetEmbeddings(UpperCamelCase						)
											snake_case__									=     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:      Optional[int]       ,	UpperCamelCase:      Tensor       ,	UpperCamelCase:      Optional[bool] = None       ,	UpperCamelCase:      Optional[bool] = None						)		->		BackboneOutput:
											snake_case__									=     return_dict if return_dict is not None else self.config.use_return_dict
											snake_case__									=     (
											    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
											)

											snake_case__									=     self.embedder(UpperCamelCase						)

											snake_case__									=     self.encoder(UpperCamelCase       ,	output_hidden_states=UpperCamelCase       ,	return_dict=UpperCamelCase						)

											snake_case__									=     outputs.hidden_states

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

											if not return_dict:
															snake_case__									=     (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       ,	)








from argparse import ArgumentParser

from .env import EnvironmentCommand
def      a_ (      )			->			Optional[Any]:







				"""simple docstring"""
				snake_case__									=     ArgumentParser('Diffusers CLI tool'      ,   usage='diffusers-cli <command> [<args>]'  )
				snake_case__									=     parser.add_subparsers(help='diffusers-cli command helpers'  )

				# Register commands
				EnvironmentCommand.register_subcommand(_A  )

				# Let's go
				snake_case__									=     parser.parse_args()

				if not hasattr(_A      ,   'func'  ):
								parser.print_help()
								exit(1  )

				# Run
				snake_case__									=     args.func(_A  )
				service.run()


if __name__ == "__main__":
							main()




