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

# General docstring
_lowercase :  Optional[Any]    							=       "RegNetConfig"

# Base docstring
_lowercase :  Optional[int]    							=       "facebook/regnet-y-040"
_lowercase :  Union[str, Any]    							=       [1, 1_0_8_8, 7, 7]

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

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






class  lowerCAmelCase__   (  nn.Module     ):






					def __init__(   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE = 3				,							__SCREAMING_SNAKE_CASE = 1				,							__SCREAMING_SNAKE_CASE = 1				,							__SCREAMING_SNAKE_CASE = "relu"				,							):


											"""simple docstring"""





											super().__init__()
											lowercase_	:     Dict													=       nn.Convad(
											    __SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							kernel_size=__SCREAMING_SNAKE_CASE				,							stride=__SCREAMING_SNAKE_CASE				,							padding=kernel_size // 2				,							groups=__SCREAMING_SNAKE_CASE				,							bias=__SCREAMING_SNAKE_CASE				,							)
											lowercase_	:     int													=       nn.BatchNormad(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     List[Any]													=       ACTaFN[activation] if activation is not None else nn.Identity()






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_	:     Tuple													=       self.convolution(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Dict													=       self.normalization(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Optional[Any]													=       self.activation(__SCREAMING_SNAKE_CASE		)
											return hidden_state







class  lowerCAmelCase__   (  nn.Module     ):






					def __init__(   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											super().__init__()
											lowercase_	:     Dict													=       RegNetConvLayer(
											    config.num_channels				,							config.embedding_size				,							kernel_size=3				,							stride=2				,							activation=config.hidden_act		)
											lowercase_	:     Union[str, Any]													=       config.num_channels






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_	:     Union[str, Any]													=       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.'''		)
											lowercase_	:     Any													=       self.embedder(__SCREAMING_SNAKE_CASE		)
											return hidden_state







class  lowerCAmelCase__   (  nn.Module     ):






					def __init__(   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE = 2		):


											"""simple docstring"""





											super().__init__()
											lowercase_	:     Optional[Any]													=       nn.Convad(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							kernel_size=1				,							stride=__SCREAMING_SNAKE_CASE				,							bias=__SCREAMING_SNAKE_CASE		)
											lowercase_	:     List[str]													=       nn.BatchNormad(__SCREAMING_SNAKE_CASE		)






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_	:     str													=       self.convolution(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     List[Any]													=       self.normalization(__SCREAMING_SNAKE_CASE		)
											return hidden_state







class  lowerCAmelCase__   (  nn.Module     ):






					def __init__(   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											super().__init__()

											lowercase_	:     Any													=       nn.AdaptiveAvgPoolad((1, 1)		)
											lowercase_	:     Tuple													=       nn.Sequential(
											    nn.Convad(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							kernel_size=1		)				,							nn.ReLU()				,							nn.Convad(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							kernel_size=1		)				,							nn.Sigmoid()				,							)






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_	:     Optional[Any]													=       self.pooler(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Optional[Any]													=       self.attention(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Tuple													=       hidden_state * attention
											return hidden_state







class  lowerCAmelCase__   (  nn.Module     ):






					def __init__(   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE = 1		):


											"""simple docstring"""





											super().__init__()
											lowercase_	:     Any													=       in_channels != out_channels or stride != 1
											lowercase_	:     str													=       max(1				,							out_channels // config.groups_width		)
											lowercase_	:     str													=       (
											    RegNetShortCut(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							stride=__SCREAMING_SNAKE_CASE		) if should_apply_shortcut else nn.Identity()
											)
											lowercase_	:     int													=       nn.Sequential(
											    RegNetConvLayer(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							kernel_size=1				,							activation=config.hidden_act		)				,							RegNetConvLayer(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							stride=__SCREAMING_SNAKE_CASE				,							groups=__SCREAMING_SNAKE_CASE				,							activation=config.hidden_act		)				,							RegNetConvLayer(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							kernel_size=1				,							activation=__SCREAMING_SNAKE_CASE		)				,							)
											lowercase_	:     Optional[int]													=       ACTaFN[config.hidden_act]






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_	:     Dict													=       hidden_state
											lowercase_	:     int													=       self.layer(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Optional[int]													=       self.shortcut(__SCREAMING_SNAKE_CASE		)
											hidden_state += residual
											lowercase_	:     str													=       self.activation(__SCREAMING_SNAKE_CASE		)
											return hidden_state







class  lowerCAmelCase__   (  nn.Module     ):






					def __init__(   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE = 1		):


											"""simple docstring"""





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






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_	:     Optional[int]													=       hidden_state
											lowercase_	:     Optional[Any]													=       self.layer(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Tuple													=       self.shortcut(__SCREAMING_SNAKE_CASE		)
											hidden_state += residual
											lowercase_	:     Union[str, Any]													=       self.activation(__SCREAMING_SNAKE_CASE		)
											return hidden_state







class  lowerCAmelCase__   (  nn.Module     ):






					def __init__(   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE = 2				,							__SCREAMING_SNAKE_CASE = 2				,							):


											"""simple docstring"""





											super().__init__()

											lowercase_	:     Any													=       RegNetXLayer if config.layer_type == '''x''' else RegNetYLayer

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






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											lowercase_	:     Dict													=       self.layers(__SCREAMING_SNAKE_CASE		)
											return hidden_state







class  lowerCAmelCase__   (  nn.Module     ):






					def __init__(   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





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






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE = False				,							__SCREAMING_SNAKE_CASE = True		):


											"""simple docstring"""





											lowercase_	:     int													=       () if output_hidden_states else None

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

																	lowercase_	:     List[str]													=       stage_module(__SCREAMING_SNAKE_CASE		)

											if output_hidden_states:
																	lowercase_	:     Optional[int]													=       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=__SCREAMING_SNAKE_CASE				,							hidden_states=__SCREAMING_SNAKE_CASE		)







class  lowerCAmelCase__   (  lowerCamelCase_     ):
					lowerCAmelCase_        =     RegNetConfig
					lowerCAmelCase_        =     '''regnet'''
					lowerCAmelCase_        =     '''pixel_values'''
					lowerCAmelCase_        =     True






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





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






					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE=False		):


											"""simple docstring"""





											if isinstance(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		):
																	lowercase_	:     Union[str, Any]													=       value







_lowercase :  List[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 :  Optional[int]    							=       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.'''    ,						lowerCamelCase_    ,						)
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class  lowerCAmelCase__   (  lowerCamelCase_     ):






					def __init__(   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											super().__init__(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Optional[int]													=       config
											lowercase_	:     Tuple													=       RegNetEmbeddings(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     List[Any]													=       RegNetEncoder(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     Tuple													=       nn.AdaptiveAvgPoolad((1, 1)		)
											# Initialize weights and apply final processing
											self.post_init()






					@add_start_docstrings_to_model_forward(__SCREAMING_SNAKE_CASE		)
					@add_code_sample_docstrings(
					    checkpoint=_CHECKPOINT_FOR_DOC				,							output_type=__SCREAMING_SNAKE_CASE				,							config_class=_CONFIG_FOR_DOC				,							modality='''vision'''				,							expected_output=_EXPECTED_OUTPUT_SHAPE				,							)
					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE = None				,							__SCREAMING_SNAKE_CASE = None		):


											"""simple docstring"""





											lowercase_	:     Tuple													=       (
											    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
											)
											lowercase_	:     str													=       return_dict if return_dict is not None else self.config.use_return_dict

											lowercase_	:     int													=       self.embedder(__SCREAMING_SNAKE_CASE		)

											lowercase_	:     Tuple													=       self.encoder(
											    __SCREAMING_SNAKE_CASE				,							output_hidden_states=__SCREAMING_SNAKE_CASE				,							return_dict=__SCREAMING_SNAKE_CASE		)

											lowercase_	:     Optional[Any]													=       encoder_outputs[0]

											lowercase_	:     List[Any]													=       self.pooler(__SCREAMING_SNAKE_CASE		)

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

											return BaseModelOutputWithPoolingAndNoAttention(
											    last_hidden_state=__SCREAMING_SNAKE_CASE				,							pooler_output=__SCREAMING_SNAKE_CASE				,							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.
    '''    ,						lowerCamelCase_    ,						)
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class  lowerCAmelCase__   (  lowerCamelCase_     ):






					def __init__(   self				,							__SCREAMING_SNAKE_CASE		):


											"""simple docstring"""





											super().__init__(__SCREAMING_SNAKE_CASE		)
											lowercase_	:     str													=       config.num_labels
											lowercase_	:     Optional[int]													=       RegNetModel(__SCREAMING_SNAKE_CASE		)
											# classification head
											lowercase_	:     List[Any]													=       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(__SCREAMING_SNAKE_CASE		)
					@add_code_sample_docstrings(
					    checkpoint=_IMAGE_CLASS_CHECKPOINT				,							output_type=__SCREAMING_SNAKE_CASE				,							config_class=_CONFIG_FOR_DOC				,							expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT				,							)
					def 	_snake_case    (   self				,							__SCREAMING_SNAKE_CASE = None				,							__SCREAMING_SNAKE_CASE = None				,							__SCREAMING_SNAKE_CASE = None				,							__SCREAMING_SNAKE_CASE = None				,							):


											"""simple docstring"""





											lowercase_	:     Optional[int]													=       return_dict if return_dict is not None else self.config.use_return_dict

											lowercase_	:     str													=       self.regnet(__SCREAMING_SNAKE_CASE				,							output_hidden_states=__SCREAMING_SNAKE_CASE				,							return_dict=__SCREAMING_SNAKE_CASE		)

											lowercase_	:     Optional[int]													=       outputs.pooler_output if return_dict else outputs[1]

											lowercase_	:     Any													=       self.classifier(__SCREAMING_SNAKE_CASE		)

											lowercase_	:     Any													=       None

											if labels is not None:
																	if self.config.problem_type is None:
																							if self.num_labels == 1:
																													lowercase_	:     str													=       '''regression'''
																							elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
																													lowercase_	:     List[Any]													=       '''single_label_classification'''
																							else:
																													lowercase_	:     Optional[int]													=       '''multi_label_classification'''
																	if self.config.problem_type == "regression":
																							lowercase_	:     int													=       MSELoss()
																							if self.num_labels == 1:
																													lowercase_	:     Dict													=       loss_fct(logits.squeeze()				,							labels.squeeze()		)
																							else:
																													lowercase_	:     List[str]													=       loss_fct(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		)
																	elif self.config.problem_type == "single_label_classification":
																							lowercase_	:     List[str]													=       CrossEntropyLoss()
																							lowercase_	:     str													=       loss_fct(logits.view(-1				,							self.num_labels		)				,							labels.view(-1		)		)
																	elif self.config.problem_type == "multi_label_classification":
																							lowercase_	:     Union[str, Any]													=       BCEWithLogitsLoss()
																							lowercase_	:     Optional[int]													=       loss_fct(__SCREAMING_SNAKE_CASE				,							__SCREAMING_SNAKE_CASE		)

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

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





'''simple docstring'''







import json
import os
import tempfile

from transformers.testing_utils import check_json_file_has_correct_format






class  lowerCAmelCase__   :
					lowerCAmelCase_        =     None






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     Tuple													=       self.feature_extraction_class(**self.feat_extract_dict		)
											lowercase_	:     Any													=       json.loads(feat_extract.to_json_string()		)
											for key, value in self.feat_extract_dict.items():
																	self.assertEqual(obj[key]				,							__SCREAMING_SNAKE_CASE		)






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     str													=       self.feature_extraction_class(**self.feat_extract_dict		)

											with tempfile.TemporaryDirectory() as tmpdirname:
																	lowercase_	:     str													=       os.path.join(__SCREAMING_SNAKE_CASE				,							'''feat_extract.json'''		)
																	feat_extract_first.to_json_file(__SCREAMING_SNAKE_CASE		)
																	lowercase_	:     str													=       self.feature_extraction_class.from_json_file(__SCREAMING_SNAKE_CASE		)

											self.assertEqual(feat_extract_second.to_dict()				,							feat_extract_first.to_dict()		)






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     Tuple													=       self.feature_extraction_class(**self.feat_extract_dict		)

											with tempfile.TemporaryDirectory() as tmpdirname:
																	lowercase_	:     Union[str, Any]													=       feat_extract_first.save_pretrained(__SCREAMING_SNAKE_CASE		)[0]
																	check_json_file_has_correct_format(__SCREAMING_SNAKE_CASE		)
																	lowercase_	:     str													=       self.feature_extraction_class.from_pretrained(__SCREAMING_SNAKE_CASE		)

											self.assertEqual(feat_extract_second.to_dict()				,							feat_extract_first.to_dict()		)






					def 	_snake_case    (   self		):


											"""simple docstring"""





											lowercase_	:     Optional[Any]													=       self.feature_extraction_class()
											self.assertIsNotNone(__SCREAMING_SNAKE_CASE		)



