


'''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 ...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    :    Optional[Any]			     =  logging.get_logger(__name__)

# General docstring
_lowercase    :    str			     =  """RegNetConfig"""

# Base docstring
_lowercase    :    Optional[int]			     =  """facebook/regnet-y-040"""
_lowercase    :    Tuple			     =  [1, 1088, 7, 7]

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

_lowercase    :    int			     =  [
    """facebook/regnet-y-040""",
    # See all regnet models at https://huggingface.co/models?filter=regnet
]






class  UpperCamelCase__(     nn.Module ):




				def __init__(	self    :				Tuple   ,					lowerCAmelCase    :				List[Any]   ,					lowerCAmelCase    :				List[Any]   ,					lowerCAmelCase    :				Tuple = 3   ,					lowerCAmelCase    :				str = 1   ,					lowerCAmelCase    :				Optional[Any] = 1   ,					lowerCAmelCase    :				Any = "relu"   ,					)->  str:

										"""simple docstring"""




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





				def   a__(	self    :				str   ,					lowerCAmelCase    :				Tuple   )->  int:

										"""simple docstring"""




										UpperCAmelCase         =			self.convolution(_lowerCamelCase   )
										UpperCAmelCase         =			self.normalization(_lowerCamelCase   )
										UpperCAmelCase         =			self.activation(_lowerCamelCase   )
										return hidden_state







class  UpperCamelCase__(     nn.Module ):




				def __init__(	self    :				Optional[int]   ,					lowerCAmelCase    :				Dict   )->  Union[str, Any]:

										"""simple docstring"""




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





				def   a__(	self    :				Any   ,					lowerCAmelCase    :				Tuple   )->  int:

										"""simple docstring"""




										UpperCAmelCase         =			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.'''   )
										UpperCAmelCase         =			self.embedder(_lowerCamelCase   )
										return hidden_state







class  UpperCamelCase__(     nn.Module ):




				def __init__(	self    :				Union[str, Any]   ,					lowerCAmelCase    :				Optional[Any]   ,					lowerCAmelCase    :				Dict   ,					lowerCAmelCase    :				Optional[Any] = 2   )->  Tuple:

										"""simple docstring"""




										super().__init__()
										UpperCAmelCase         =			nn.Convad(_lowerCamelCase   ,					_lowerCamelCase   ,					kernel_size=1   ,					stride=_lowerCamelCase   ,					bias=_lowerCamelCase   )
										UpperCAmelCase         =			nn.BatchNormad(_lowerCamelCase   )





				def   a__(	self    :				List[Any]   ,					lowerCAmelCase    :				int   )->  Tensor:

										"""simple docstring"""




										UpperCAmelCase         =			self.convolution(_lowerCamelCase   )
										UpperCAmelCase         =			self.normalization(_lowerCamelCase   )
										return hidden_state







class  UpperCamelCase__(     nn.Module ):




				def __init__(	self    :				Tuple   ,					lowerCAmelCase    :				Any   ,					lowerCAmelCase    :				Any   )->  Any:

										"""simple docstring"""




										super().__init__()

										UpperCAmelCase         =			nn.AdaptiveAvgPoolad((1, 1)   )
										UpperCAmelCase         =			nn.Sequential(
										    nn.Convad(_lowerCamelCase   ,					_lowerCamelCase   ,					kernel_size=1   )   ,					nn.ReLU()   ,					nn.Convad(_lowerCamelCase   ,					_lowerCamelCase   ,					kernel_size=1   )   ,					nn.Sigmoid()   ,					)





				def   a__(	self    :				Union[str, Any]   ,					lowerCAmelCase    :				int   )->  Dict:

										"""simple docstring"""




										UpperCAmelCase         =			self.pooler(_lowerCamelCase   )
										UpperCAmelCase         =			self.attention(_lowerCamelCase   )
										UpperCAmelCase         =			hidden_state * attention
										return hidden_state







class  UpperCamelCase__(     nn.Module ):




				def __init__(	self    :				List[str]   ,					lowerCAmelCase    :				Dict   ,					lowerCAmelCase    :				Tuple   ,					lowerCAmelCase    :				Tuple   ,					lowerCAmelCase    :				List[str] = 1   )->  List[str]:

										"""simple docstring"""




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





				def   a__(	self    :				Dict   ,					lowerCAmelCase    :				str   )->  int:

										"""simple docstring"""




										UpperCAmelCase         =			hidden_state
										UpperCAmelCase         =			self.layer(_lowerCamelCase   )
										UpperCAmelCase         =			self.shortcut(_lowerCamelCase   )
										hidden_state += residual
										UpperCAmelCase         =			self.activation(_lowerCamelCase   )
										return hidden_state







class  UpperCamelCase__(     nn.Module ):




				def __init__(	self    :				Any   ,					lowerCAmelCase    :				Dict   ,					lowerCAmelCase    :				Optional[int]   ,					lowerCAmelCase    :				List[str]   ,					lowerCAmelCase    :				int = 1   )->  Tuple:

										"""simple docstring"""




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





				def   a__(	self    :				Union[str, Any]   ,					lowerCAmelCase    :				Union[str, Any]   )->  str:

										"""simple docstring"""




										UpperCAmelCase         =			hidden_state
										UpperCAmelCase         =			self.layer(_lowerCamelCase   )
										UpperCAmelCase         =			self.shortcut(_lowerCamelCase   )
										hidden_state += residual
										UpperCAmelCase         =			self.activation(_lowerCamelCase   )
										return hidden_state







class  UpperCamelCase__(     nn.Module ):




				def __init__(	self    :				Optional[Any]   ,					lowerCAmelCase    :				Dict   ,					lowerCAmelCase    :				List[str]   ,					lowerCAmelCase    :				Tuple   ,					lowerCAmelCase    :				Dict = 2   ,					lowerCAmelCase    :				Tuple = 2   ,					)->  List[str]:

										"""simple docstring"""




										super().__init__()

										UpperCAmelCase         =			RegNetXLayer if config.layer_type == '''x''' else RegNetYLayer

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





				def   a__(	self    :				Optional[int]   ,					lowerCAmelCase    :				Optional[Any]   )->  List[Any]:

										"""simple docstring"""




										UpperCAmelCase         =			self.layers(_lowerCamelCase   )
										return hidden_state







class  UpperCamelCase__(     nn.Module ):




				def __init__(	self    :				int   ,					lowerCAmelCase    :				Optional[int]   )->  Union[str, Any]:

										"""simple docstring"""




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





				def   a__(	self    :				Optional[Any]   ,					lowerCAmelCase    :				Dict   ,					lowerCAmelCase    :				List[str] = False   ,					lowerCAmelCase    :				Tuple = True   )->  BaseModelOutputWithNoAttention:

										"""simple docstring"""




										UpperCAmelCase         =			() if output_hidden_states else None

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

																UpperCAmelCase         =			stage_module(_lowerCamelCase   )

										if output_hidden_states:
																UpperCAmelCase         =			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=_lowerCamelCase   ,					hidden_states=_lowerCamelCase   )







class  UpperCamelCase__(     lowerCAmelCase__ ):
				__magic_name__       :   List[str]							= RegNetConfig
				__magic_name__       :   str							= "regnet"
				__magic_name__       :   List[str]							= "pixel_values"
				__magic_name__       :   str							= True




				def   a__(	self    :				Optional[Any]   ,					lowerCAmelCase    :				List[Any]   )->  int:

										"""simple docstring"""




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





				def   a__(	self    :				int   ,					lowerCAmelCase    :				Dict   ,					lowerCAmelCase    :				Optional[int]=False   )->  Dict:

										"""simple docstring"""




										if isinstance(_lowerCamelCase   ,					_lowerCamelCase   ):
																UpperCAmelCase         =			value







_lowercase    :    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 ([`RegNetConfig`]): 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.
"""

_lowercase    :    Optional[int]			     =  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 [`~file_utils.ModelOutput`] instead of a plain tuple.
"""






@add_start_docstrings(
    "The bare RegNet model outputting raw features without any specific head on top."		,       lowerCAmelCase__		,       )
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class  UpperCamelCase__(     lowerCAmelCase__ ):




				def __init__(	self    :				str   ,					lowerCAmelCase    :				Optional[int]   )->  List[str]:

										"""simple docstring"""




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





				@add_start_docstrings_to_model_forward(_lowerCamelCase   )
				@add_code_sample_docstrings(
				    checkpoint=_CHECKPOINT_FOR_DOC   ,					output_type=_lowerCamelCase   ,					config_class=_CONFIG_FOR_DOC   ,					modality='''vision'''   ,					expected_output=_EXPECTED_OUTPUT_SHAPE   ,					)
				def   a__(	self    :				Tuple   ,					lowerCAmelCase    :				Optional[int]   ,					lowerCAmelCase    :				Any = None   ,					lowerCAmelCase    :				Optional[int] = None   )->  BaseModelOutputWithPoolingAndNoAttention:

										"""simple docstring"""




										UpperCAmelCase         =			(
										    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
										)
										UpperCAmelCase         =			return_dict if return_dict is not None else self.config.use_return_dict

										UpperCAmelCase         =			self.embedder(_lowerCamelCase   )

										UpperCAmelCase         =			self.encoder(
										    _lowerCamelCase   ,					output_hidden_states=_lowerCamelCase   ,					return_dict=_lowerCamelCase   )

										UpperCAmelCase         =			encoder_outputs[0]

										UpperCAmelCase         =			self.pooler(_lowerCamelCase   )

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

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







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




				def __init__(	self    :				List[Any]   ,					lowerCAmelCase    :				Any   )->  Tuple:

										"""simple docstring"""




										super().__init__(_lowerCamelCase   )
										UpperCAmelCase         =			config.num_labels
										UpperCAmelCase         =			RegNetModel(_lowerCamelCase   )
										# classification head
										UpperCAmelCase         =			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(_lowerCamelCase   )
				@add_code_sample_docstrings(
				    checkpoint=_IMAGE_CLASS_CHECKPOINT   ,					output_type=_lowerCamelCase   ,					config_class=_CONFIG_FOR_DOC   ,					expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT   ,					)
				def   a__(	self    :				Any   ,					lowerCAmelCase    :				Dict = None   ,					lowerCAmelCase    :				Tuple = None   ,					lowerCAmelCase    :				Tuple = None   ,					lowerCAmelCase    :				Union[str, Any] = None   ,					)->  ImageClassifierOutputWithNoAttention:

										"""simple docstring"""




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

										UpperCAmelCase         =			self.regnet(_lowerCamelCase   ,					output_hidden_states=_lowerCamelCase   ,					return_dict=_lowerCamelCase   )

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

										UpperCAmelCase         =			self.classifier(_lowerCamelCase   )

										UpperCAmelCase         =			None

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

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

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







'''simple docstring'''



# Copyright 2023 The HuggingFace Team. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from typing import TYPE_CHECKING

from ...utils import OptionalDependencyNotAvailable, _LazyModule, is_torch_available


_lowercase    :    int			     =  {
    """configuration_xmod""": [
        """XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP""",
        """XmodConfig""",
        """XmodOnnxConfig""",
    ],
}

try:
	if not is_torch_available():
		raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
	pass
else:
	_lowercase    :    str			     =  [
	    """XMOD_PRETRAINED_MODEL_ARCHIVE_LIST""",
	    """XmodForCausalLM""",
	    """XmodForMaskedLM""",
	    """XmodForMultipleChoice""",
	    """XmodForQuestionAnswering""",
	    """XmodForSequenceClassification""",
	    """XmodForTokenClassification""",
	    """XmodModel""",
	    """XmodPreTrainedModel""",
	]

if TYPE_CHECKING:
	from .configuration_xmod import XMOD_PRETRAINED_CONFIG_ARCHIVE_MAP, XmodConfig, XmodOnnxConfig

	try:
		if not is_torch_available():
			raise OptionalDependencyNotAvailable()
	except OptionalDependencyNotAvailable:
		pass
	else:
		from .modeling_xmod import (
		    XMOD_PRETRAINED_MODEL_ARCHIVE_LIST,
		    XmodForCausalLM,
		    XmodForMaskedLM,
		    XmodForMultipleChoice,
		    XmodForQuestionAnswering,
		    XmodForSequenceClassification,
		    XmodForTokenClassification,
		    XmodModel,
		    XmodPreTrainedModel,
		)

else:
	import sys

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





