




"""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__     						=						logging.get_logger(__name__)

# General docstring
lowercase__     						=						"""RegNetConfig"""

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

# Image classification docstring
lowercase__     						=						"""facebook/regnet-y-040"""
lowercase__     						=						"""tabby, tabby cat"""

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






class lowerCAmelCase__	(     nn.Module						):






			'''simple docstring'''



			def __init__(  self  ,      lowercase  ,      lowercase  ,      lowercase = 3  ,      lowercase = 1  ,      lowercase = 1  ,      lowercase = "relu"  ,      ):
							super().__init__()
							_lowerCamelCase     :			str    =    nn.Convad(
							    lowercase  ,      lowercase  ,      kernel_size=lowercase  ,      stride=lowercase  ,      padding=kernel_size // 2  ,      groups=lowercase  ,      bias=lowercase  ,      )
							_lowerCamelCase     :			Dict    =    nn.BatchNormad(lowercase  )
							_lowerCamelCase     :			Union[str, Any]    =    ACTaFN[activation] if activation is not None else nn.Identity()






			def 					A_    (  self  ,      lowercase  ):
							_lowerCamelCase     :			int    =    self.convolution(lowercase  )
							_lowerCamelCase     :			Any    =    self.normalization(lowercase  )
							_lowerCamelCase     :			Optional[Any]    =    self.activation(lowercase  )
							return hidden_state






class lowerCAmelCase__	(     nn.Module						):






			'''simple docstring'''



			def __init__(  self  ,      lowercase  ):
							super().__init__()
							_lowerCamelCase     :			Dict    =    RegNetConvLayer(
							    config.num_channels  ,      config.embedding_size  ,      kernel_size=3  ,      stride=2  ,      activation=config.hidden_act  )
							_lowerCamelCase     :			Optional[int]    =    config.num_channels






			def 					A_    (  self  ,      lowercase  ):
							_lowerCamelCase     :			List[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.'  )
							_lowerCamelCase     :			int    =    self.embedder(lowercase  )
							return hidden_state






class lowerCAmelCase__	(     nn.Module						):






			'''simple docstring'''



			def __init__(  self  ,      lowercase  ,      lowercase  ,      lowercase = 2  ):
							super().__init__()
							_lowerCamelCase     :			Dict    =    nn.Convad(lowercase  ,      lowercase  ,      kernel_size=1  ,      stride=lowercase  ,      bias=lowercase  )
							_lowerCamelCase     :			Dict    =    nn.BatchNormad(lowercase  )






			def 					A_    (  self  ,      lowercase  ):
							_lowerCamelCase     :			int    =    self.convolution(lowercase  )
							_lowerCamelCase     :			List[Any]    =    self.normalization(lowercase  )
							return hidden_state






class lowerCAmelCase__	(     nn.Module						):






			'''simple docstring'''



			def __init__(  self  ,      lowercase  ,      lowercase  ):
							super().__init__()

							_lowerCamelCase     :			List[str]    =    nn.AdaptiveAvgPoolad((1, 1)  )
							_lowerCamelCase     :			Tuple    =    nn.Sequential(
							    nn.Convad(lowercase  ,      lowercase  ,      kernel_size=1  )  ,      nn.ReLU()  ,      nn.Convad(lowercase  ,      lowercase  ,      kernel_size=1  )  ,      nn.Sigmoid()  ,      )






			def 					A_    (  self  ,      lowercase  ):
							# b c h w -> b c 1 1
							_lowerCamelCase     :			List[Any]    =    self.pooler(lowercase  )
							_lowerCamelCase     :			List[Any]    =    self.attention(lowercase  )
							_lowerCamelCase     :			Dict    =    hidden_state * attention
							return hidden_state






class lowerCAmelCase__	(     nn.Module						):






			'''simple docstring'''



			def __init__(  self  ,      lowercase  ,      lowercase  ,      lowercase  ,      lowercase = 1  ):
							super().__init__()
							_lowerCamelCase     :			Union[str, Any]    =    in_channels != out_channels or stride != 1
							_lowerCamelCase     :			List[Any]    =    max(1  ,      out_channels // config.groups_width  )
							_lowerCamelCase     :			Any    =    (
							    RegNetShortCut(lowercase  ,      lowercase  ,      stride=lowercase  ) if should_apply_shortcut else nn.Identity()
							)
							_lowerCamelCase     :			int    =    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  )  ,      )
							_lowerCamelCase     :			Union[str, Any]    =    ACTaFN[config.hidden_act]






			def 					A_    (  self  ,      lowercase  ):
							_lowerCamelCase     :			Union[str, Any]    =    hidden_state
							_lowerCamelCase     :			Optional[int]    =    self.layer(lowercase  )
							_lowerCamelCase     :			str    =    self.shortcut(lowercase  )
							hidden_state += residual
							_lowerCamelCase     :			Union[str, Any]    =    self.activation(lowercase  )
							return hidden_state






class lowerCAmelCase__	(     nn.Module						):






			'''simple docstring'''



			def __init__(  self  ,      lowercase  ,      lowercase  ,      lowercase  ,      lowercase = 1  ):
							super().__init__()
							_lowerCamelCase     :			Union[str, Any]    =    in_channels != out_channels or stride != 1
							_lowerCamelCase     :			Union[str, Any]    =    max(1  ,      out_channels // config.groups_width  )
							_lowerCamelCase     :			int    =    (
							    RegNetShortCut(lowercase  ,      lowercase  ,      stride=lowercase  ) if should_apply_shortcut else nn.Identity()
							)
							_lowerCamelCase     :			int    =    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  )  ,      )
							_lowerCamelCase     :			List[Any]    =    ACTaFN[config.hidden_act]






			def 					A_    (  self  ,      lowercase  ):
							_lowerCamelCase     :			Tuple    =    hidden_state
							_lowerCamelCase     :			Optional[Any]    =    self.layer(lowercase  )
							_lowerCamelCase     :			Dict    =    self.shortcut(lowercase  )
							hidden_state += residual
							_lowerCamelCase     :			Dict    =    self.activation(lowercase  )
							return hidden_state






class lowerCAmelCase__	(     nn.Module						):






			'''simple docstring'''



			def __init__(  self  ,      lowercase  ,      lowercase  ,      lowercase  ,      lowercase = 2  ,      lowercase = 2  ,      ):
							super().__init__()

							_lowerCamelCase     :			Dict    =    RegNetXLayer if config.layer_type == 'x' else RegNetYLayer

							_lowerCamelCase     :			Dict    =    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 					A_    (  self  ,      lowercase  ):
							_lowerCamelCase     :			Any    =    self.layers(lowercase  )
							return hidden_state






class lowerCAmelCase__	(     nn.Module						):






			'''simple docstring'''



			def __init__(  self  ,      lowercase  ):
							super().__init__()
							_lowerCamelCase     :			Union[str, 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(
							        lowercase  ,      config.embedding_size  ,      config.hidden_sizes[0]  ,      stride=2 if config.downsample_in_first_stage else 1  ,      depth=config.depths[0]  ,      )  )
							_lowerCamelCase     :			Optional[int]    =    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 					A_    (  self  ,      lowercase  ,      lowercase = False  ,      lowercase = True  ):
							_lowerCamelCase     :			Optional[Any]    =    () if output_hidden_states else None

							for stage_module in self.stages:
											if output_hidden_states:
															_lowerCamelCase     :			Union[str, Any]    =    hidden_states + (hidden_state,)

											_lowerCamelCase     :			Tuple    =    stage_module(lowercase  )

							if output_hidden_states:
											_lowerCamelCase     :			Tuple    =    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 lowerCAmelCase__	(     lowercase						):






			'''simple docstring'''



			lowerCamelCase__      =			RegNetConfig
			lowerCamelCase__      =			"""regnet"""
			lowerCamelCase__      =			"""pixel_values"""
			lowerCamelCase__      =			True
			def 					A_    (  self  ,      lowercase  ):
							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 					A_    (  self  ,      lowercase  ,      lowercase=False  ):
							if isinstance(lowercase  ,      lowercase  ):
											_lowerCamelCase     :			List[Any]    =    value

lowercase__     						=						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__     						=						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.""",	lowercase,	)
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class lowerCAmelCase__	(     lowercase						):






			'''simple docstring'''



			def __init__(  self  ,      lowercase  ):
							super().__init__(lowercase  )
							_lowerCamelCase     :			List[str]    =    config
							_lowerCamelCase     :			Optional[int]    =    RegNetEmbeddings(lowercase  )
							_lowerCamelCase     :			str    =    RegNetEncoder(lowercase  )
							_lowerCamelCase     :			str    =    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 					A_    (  self  ,      lowercase  ,      lowercase = None  ,      lowercase = None  ):
							_lowerCamelCase     :			Dict    =    (
							    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
							)
							_lowerCamelCase     :			Optional[int]    =    return_dict if return_dict is not None else self.config.use_return_dict

							_lowerCamelCase     :			Any    =    self.embedder(lowercase  )

							_lowerCamelCase     :			Tuple    =    self.encoder(
							    lowercase  ,      output_hidden_states=lowercase  ,      return_dict=lowercase  )

							_lowerCamelCase     :			Union[str, Any]    =    encoder_outputs[0]

							_lowerCamelCase     :			Dict    =    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.
    """,	lowercase,	)
# Copied from transformers.models.resnet.modeling_resnet.ResNetForImageClassification with RESNET->REGNET,ResNet->RegNet,resnet->regnet
class lowerCAmelCase__	(     lowercase						):






			'''simple docstring'''



			def __init__(  self  ,      lowercase  ):
							super().__init__(lowercase  )
							_lowerCamelCase     :			int    =    config.num_labels
							_lowerCamelCase     :			Optional[Any]    =    RegNetModel(lowercase  )
							# classification head
							_lowerCamelCase     :			str    =    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 					A_    (  self  ,      lowercase = None  ,      lowercase = None  ,      lowercase = None  ,      lowercase = None  ,      ):
							_lowerCamelCase     :			Optional[int]    =    return_dict if return_dict is not None else self.config.use_return_dict

							_lowerCamelCase     :			Dict    =    self.regnet(lowercase  ,      output_hidden_states=lowercase  ,      return_dict=lowercase  )

							_lowerCamelCase     :			Tuple    =    outputs.pooler_output if return_dict else outputs[1]

							_lowerCamelCase     :			Optional[Any]    =    self.classifier(lowercase  )

							_lowerCamelCase     :			Optional[Any]    =    None

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

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

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





"""simple docstring"""






from __future__ import annotations

import math

import numpy as np
from numpy.linalg import norm







def      _snake_case			(				lowercase__							,    lowercase__		):
				return math.sqrt(sum(pow(a - b							,    2		) for a, b in zip(lowercase__							,    lowercase__		)		)		)







def      _snake_case			(				lowercase__							,    lowercase__		):

				if dataset.ndim != value_array.ndim:
								_lowerCamelCase     :			Tuple    =    (
								    'Wrong input data\'s dimensions... '
								    f'''dataset : {dataset.ndim}, value_array : {value_array.ndim}'''
								)
								raise ValueError(lowercase__		)

				try:
								if dataset.shape[1] != value_array.shape[1]:
												_lowerCamelCase     :			Optional[int]    =    (
												    'Wrong input data\'s shape... '
												    f'''dataset : {dataset.shape[1]}, value_array : {value_array.shape[1]}'''
												)
												raise ValueError(lowercase__		)
				except IndexError:
								if dataset.ndim != value_array.ndim:
												raise TypeError('Wrong shape'		)

				if dataset.dtype != value_array.dtype:
								_lowerCamelCase     :			int    =    (
								    'Input data have different datatype... '
								    f'''dataset : {dataset.dtype}, value_array : {value_array.dtype}'''
								)
								raise TypeError(lowercase__		)

				_lowerCamelCase     :			Optional[int]    =    []

				for value in value_array:
								_lowerCamelCase     :			Tuple    =    euclidean(lowercase__							,    dataset[0]		)
								_lowerCamelCase     :			Union[str, Any]    =    dataset[0].tolist()

								for dataset_value in dataset[1:]:
												_lowerCamelCase     :			Optional[Any]    =    euclidean(lowercase__							,    lowercase__		)

												if dist > temp_dist:
																_lowerCamelCase     :			List[Any]    =    temp_dist
																_lowerCamelCase     :			List[str]    =    dataset_value.tolist()

								answer.append([vector, dist]		)

				return answer







def      _snake_case			(				lowercase__							,    lowercase__		):
				return np.dot(lowercase__							,    lowercase__		) / (norm(lowercase__		) * norm(lowercase__		))


if __name__ == "__main__":
			import doctest

			doctest.testmod()