




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 ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_outputs import (
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import logging
from .configuration_regnet import RegNetConfig


lowercase__							:	List[str]											=		logging.get_logger(__name__)

# General docstring
lowercase__							:	Dict											=		"RegNetConfig"

# Base docstring
lowercase__							:	List[Any]											=		"facebook/regnet-y-040"
lowercase__							:	List[str]											=		[1, 1088, 7, 7]

# Image classification docstring
lowercase__							:	Any											=		"facebook/regnet-y-040"
lowercase__							:	List[Any]											=		"tabby, tabby cat"

lowercase__							:	Optional[Any]											=		[
    "facebook/regnet-y-040",
    # See all regnet models at https://huggingface.co/models?filter=regnet
]
class 						UpperCAmelCase  (							nn.Module     ):







						'''simple docstring'''





						def __init__(		self				:	Dict			,      __lowercase				:	int			,      __lowercase				:	int			,      __lowercase				:	int = 3			,      __lowercase				:	int = 1			,      __lowercase				:	int = 1			,      __lowercase				:	Optional[str] = "relu"			,      ):






							"""simple docstring"""






							super().__init__()
							snake_case_						       =	nn.Convad(
							    __lowercase			,      __lowercase			,      kernel_size=__lowercase			,      stride=__lowercase			,      padding=kernel_size // 2			,      groups=__lowercase			,      bias=__lowercase			,      )
							snake_case_						       =	nn.BatchNormad(__lowercase		)
							snake_case_						       =	ACTaFN[activation] if activation is not None else nn.Identity()






						def 			snake_case__		(		self				:	Optional[int]			,      __lowercase				:	Dict		):






							"""simple docstring"""






							snake_case_						       =	self.convolution(__lowercase		)
							snake_case_						       =	self.normalization(__lowercase		)
							snake_case_						       =	self.activation(__lowercase		)
							return hidden_state







class 						UpperCAmelCase  (							nn.Module     ):







						'''simple docstring'''





						def __init__(		self				:	Optional[Any]			,      __lowercase				:	RegNetConfig		):






							"""simple docstring"""






							super().__init__()
							snake_case_						       =	RegNetConvLayer(
							    config.num_channels			,      config.embedding_size			,      kernel_size=3			,      stride=2			,      activation=config.hidden_act		)
							snake_case_						       =	config.num_channels






						def 			snake_case__		(		self				:	Optional[Any]			,      __lowercase				:	Optional[int]		):






							"""simple docstring"""






							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(__lowercase		)
							return hidden_state







class 						UpperCAmelCase  (							nn.Module     ):







						'''simple docstring'''





						def __init__(		self				:	Tuple			,      __lowercase				:	int			,      __lowercase				:	int			,      __lowercase				:	int = 2		):






							"""simple docstring"""






							super().__init__()
							snake_case_						       =	nn.Convad(__lowercase			,      __lowercase			,      kernel_size=1			,      stride=__lowercase			,      bias=__lowercase		)
							snake_case_						       =	nn.BatchNormad(__lowercase		)






						def 			snake_case__		(		self				:	Union[str, Any]			,      __lowercase				:	Tensor		):






							"""simple docstring"""






							snake_case_						       =	self.convolution(__lowercase		)
							snake_case_						       =	self.normalization(__lowercase		)
							return hidden_state







class 						UpperCAmelCase  (							nn.Module     ):







						'''simple docstring'''





						def __init__(		self				:	Tuple			,      __lowercase				:	int			,      __lowercase				:	int		):






							"""simple docstring"""






							super().__init__()

							snake_case_						       =	nn.AdaptiveAvgPoolad((1, 1)		)
							snake_case_						       =	nn.Sequential(
							    nn.Convad(__lowercase			,      __lowercase			,      kernel_size=1		)			,      nn.ReLU()			,      nn.Convad(__lowercase			,      __lowercase			,      kernel_size=1		)			,      nn.Sigmoid()			,      )






						def 			snake_case__		(		self				:	Any			,      __lowercase				:	List[Any]		):






							"""simple docstring"""






							snake_case_						       =	self.pooler(__lowercase		)
							snake_case_						       =	self.attention(__lowercase		)
							snake_case_						       =	hidden_state * attention
							return hidden_state







class 						UpperCAmelCase  (							nn.Module     ):







						'''simple docstring'''





						def __init__(		self				:	List[Any]			,      __lowercase				:	RegNetConfig			,      __lowercase				:	int			,      __lowercase				:	int			,      __lowercase				:	int = 1		):






							"""simple docstring"""






							super().__init__()
							snake_case_						       =	in_channels != out_channels or stride != 1
							snake_case_						       =	max(1			,      out_channels // config.groups_width		)
							snake_case_						       =	(
							    RegNetShortCut(__lowercase			,      __lowercase			,      stride=__lowercase		) if should_apply_shortcut else nn.Identity()
							)
							snake_case_						       =	nn.Sequential(
							    RegNetConvLayer(__lowercase			,      __lowercase			,      kernel_size=1			,      activation=config.hidden_act		)			,      RegNetConvLayer(__lowercase			,      __lowercase			,      stride=__lowercase			,      groups=__lowercase			,      activation=config.hidden_act		)			,      RegNetConvLayer(__lowercase			,      __lowercase			,      kernel_size=1			,      activation=__lowercase		)			,      )
							snake_case_						       =	ACTaFN[config.hidden_act]






						def 			snake_case__		(		self				:	Optional[int]			,      __lowercase				:	List[Any]		):






							"""simple docstring"""






							snake_case_						       =	hidden_state
							snake_case_						       =	self.layer(__lowercase		)
							snake_case_						       =	self.shortcut(__lowercase		)
							hidden_state += residual
							snake_case_						       =	self.activation(__lowercase		)
							return hidden_state







class 						UpperCAmelCase  (							nn.Module     ):







						'''simple docstring'''





						def __init__(		self				:	Any			,      __lowercase				:	RegNetConfig			,      __lowercase				:	int			,      __lowercase				:	int			,      __lowercase				:	int = 1		):






							"""simple docstring"""






							super().__init__()
							snake_case_						       =	in_channels != out_channels or stride != 1
							snake_case_						       =	max(1			,      out_channels // config.groups_width		)
							snake_case_						       =	(
							    RegNetShortCut(__lowercase			,      __lowercase			,      stride=__lowercase		) if should_apply_shortcut else nn.Identity()
							)
							snake_case_						       =	nn.Sequential(
							    RegNetConvLayer(__lowercase			,      __lowercase			,      kernel_size=1			,      activation=config.hidden_act		)			,      RegNetConvLayer(__lowercase			,      __lowercase			,      stride=__lowercase			,      groups=__lowercase			,      activation=config.hidden_act		)			,      RegNetSELayer(__lowercase			,      reduced_channels=int(round(in_channels / 4		)		)		)			,      RegNetConvLayer(__lowercase			,      __lowercase			,      kernel_size=1			,      activation=__lowercase		)			,      )
							snake_case_						       =	ACTaFN[config.hidden_act]






						def 			snake_case__		(		self				:	Optional[int]			,      __lowercase				:	Union[str, Any]		):






							"""simple docstring"""






							snake_case_						       =	hidden_state
							snake_case_						       =	self.layer(__lowercase		)
							snake_case_						       =	self.shortcut(__lowercase		)
							hidden_state += residual
							snake_case_						       =	self.activation(__lowercase		)
							return hidden_state







class 						UpperCAmelCase  (							nn.Module     ):







						'''simple docstring'''





						def __init__(		self				:	List[str]			,      __lowercase				:	RegNetConfig			,      __lowercase				:	int			,      __lowercase				:	int			,      __lowercase				:	int = 2			,      __lowercase				:	int = 2			,      ):






							"""simple docstring"""






							super().__init__()

							snake_case_						       =	RegNetXLayer if config.layer_type == "x" else RegNetYLayer

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






						def 			snake_case__		(		self				:	Dict			,      __lowercase				:	Union[str, Any]		):






							"""simple docstring"""






							snake_case_						       =	self.layers(__lowercase		)
							return hidden_state







class 						UpperCAmelCase  (							nn.Module     ):







						'''simple docstring'''





						def __init__(		self				:	Dict			,      __lowercase				:	RegNetConfig		):






							"""simple docstring"""






							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(
							    RegNetStage(
							        __lowercase			,      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(__lowercase			,      config.depths[1:]		):
								self.stages.append(RegNetStage(__lowercase			,      __lowercase			,      __lowercase			,      depth=__lowercase		)		)






						def 			snake_case__		(		self				:	Optional[Any]			,      __lowercase				:	Tensor			,      __lowercase				:	bool = False			,      __lowercase				:	bool = True		):






							"""simple docstring"""






							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(__lowercase		)

							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=__lowercase			,      hidden_states=__lowercase		)







class 						UpperCAmelCase  (							UpperCAmelCase__     ):







						'''simple docstring'''





						lowerCAmelCase_							=  RegNetConfig
						lowerCAmelCase_							=  '''regnet'''
						lowerCAmelCase_							=  '''pixel_values'''
						lowerCAmelCase_							=  True






						def 			snake_case__		(		self				:	Optional[Any]			,      __lowercase				:	Union[str, Any]		):






							"""simple docstring"""






							if isinstance(__lowercase			,      nn.Convad		):
								nn.init.kaiming_normal_(module.weight			,      mode="fan_out"			,      nonlinearity="relu"		)
							elif isinstance(__lowercase			,      (nn.BatchNormad, nn.GroupNorm)		):
								nn.init.constant_(module.weight			,      1		)
								nn.init.constant_(module.bias			,      0		)






						def 			snake_case__		(		self				:	Optional[int]			,      __lowercase				:	Optional[Any]			,      __lowercase				:	List[str]=False		):






							"""simple docstring"""






							if isinstance(__lowercase			,      __lowercase		):
								snake_case_						       =	value







lowercase__							:	Union[str, Any]											=		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 ([`RegNetConfig`]): 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__							:	Union[str, Any]											=		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 [`~file_utils.ModelOutput`] instead of a plain tuple.\n"
@add_start_docstrings(
    '''The bare RegNet model outputting raw features without any specific head on top.'''			,  UpperCAmelCase__			,  )
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class 						UpperCAmelCase  (							UpperCAmelCase__     ):







						'''simple docstring'''





						def __init__(		self				:	str			,      __lowercase				:	Optional[int]		):






							"""simple docstring"""






							super().__init__(__lowercase		)
							snake_case_						       =	config
							snake_case_						       =	RegNetEmbeddings(__lowercase		)
							snake_case_						       =	RegNetEncoder(__lowercase		)
							snake_case_						       =	nn.AdaptiveAvgPoolad((1, 1)		)
							# Initialize weights and apply final processing
							self.post_init()






						@add_start_docstrings_to_model_forward(__lowercase		)
						@add_code_sample_docstrings(
						    checkpoint=_CHECKPOINT_FOR_DOC			,      output_type=__lowercase			,      config_class=_CONFIG_FOR_DOC			,      modality="vision"			,      expected_output=_EXPECTED_OUTPUT_SHAPE			,      )
						def 			snake_case__		(		self				:	Optional[Any]			,      __lowercase				:	Tensor			,      __lowercase				:	Optional[bool] = None			,      __lowercase				:	Optional[bool] = None		):






							"""simple docstring"""






							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(__lowercase		)

							snake_case_						       =	self.encoder(
							    __lowercase			,      output_hidden_states=__lowercase			,      return_dict=__lowercase		)

							snake_case_						       =	encoder_outputs[0]

							snake_case_						       =	self.pooler(__lowercase		)

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

							return BaseModelOutputWithPoolingAndNoAttention(
							    last_hidden_state=__lowercase			,      pooler_output=__lowercase			,      hidden_states=encoder_outputs.hidden_states			,      )







@add_start_docstrings(
    '''
    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    '''			,  UpperCAmelCase__			,  )
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class 						UpperCAmelCase  (							UpperCAmelCase__     ):







						'''simple docstring'''





						def __init__(		self				:	Optional[Any]			,      __lowercase				:	Union[str, Any]		):






							"""simple docstring"""






							super().__init__(__lowercase		)
							snake_case_						       =	config.num_labels
							snake_case_						       =	RegNetModel(__lowercase		)
							# 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(__lowercase		)
						@add_code_sample_docstrings(
						    checkpoint=_IMAGE_CLASS_CHECKPOINT			,      output_type=__lowercase			,      config_class=_CONFIG_FOR_DOC			,      expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT			,      )
						def 			snake_case__		(		self				:	Tuple			,      __lowercase				:	Optional[torch.FloatTensor] = None			,      __lowercase				:	Optional[torch.LongTensor] = None			,      __lowercase				:	Optional[bool] = None			,      __lowercase				:	Optional[bool] = None			,      ):






							"""simple docstring"""






							snake_case_						       =	return_dict if return_dict is not None else self.config.use_return_dict

							snake_case_						       =	self.regnet(__lowercase			,      output_hidden_states=__lowercase			,      return_dict=__lowercase		)

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

							snake_case_						       =	self.classifier(__lowercase		)

							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(__lowercase			,      __lowercase		)
								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(__lowercase			,      __lowercase		)

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

							return ImageClassifierOutputWithNoAttention(loss=__lowercase			,      logits=__lowercase			,      hidden_states=outputs.hidden_states		)






from typing import TYPE_CHECKING

from ...file_utils import _LazyModule, is_tokenizers_available, is_torch_available, is_vision_available
from ...utils import OptionalDependencyNotAvailable


lowercase__							:	Union[str, Any]											=		{"configuration_dpt": ["DPT_PRETRAINED_CONFIG_ARCHIVE_MAP", "DPTConfig"]}

try:
		if not is_vision_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase__							:	Tuple											=		["DPTFeatureExtractor"]
		lowercase__							:	Optional[Any]											=		["DPTImageProcessor"]

try:
		if not is_torch_available():
				raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
		pass
else:
		lowercase__							:	Dict											=		[
		    "DPT_PRETRAINED_MODEL_ARCHIVE_LIST",
		    "DPTForDepthEstimation",
		    "DPTForSemanticSegmentation",
		    "DPTModel",
		    "DPTPreTrainedModel",
		]


if TYPE_CHECKING:
		from .configuration_dpt import DPT_PRETRAINED_CONFIG_ARCHIVE_MAP, DPTConfig

		try:
				if not is_vision_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .feature_extraction_dpt import DPTFeatureExtractor
				from .image_processing_dpt import DPTImageProcessor

		try:
				if not is_torch_available():
						raise OptionalDependencyNotAvailable()
		except OptionalDependencyNotAvailable:
				pass
		else:
				from .modeling_dpt import (
				    DPT_PRETRAINED_MODEL_ARCHIVE_LIST,
				    DPTForDepthEstimation,
				    DPTForSemanticSegmentation,
				    DPTModel,
				    DPTPreTrainedModel,
				)


else:
		import sys

		lowercase__							:	List[Any]											=		_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
