





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, 1_088, 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     SCREAMING_SNAKE_CASE       (nn.Module				):


   def __init__(   self      :    int      ,					a      :    int      ,					a      :    int      ,					a      :    int = 3      ,					a      :    int = 1      ,					a      :    int = 1      ,					a      :    Optional[str] = "relu"      ,					)->       Optional[Any]:





     """simple docstring"""







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


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Optional[Any]      ,					a      :    Optional[Any]	)->       Any:





     """simple docstring"""







     lowercase__           =  self.convolution(a	)
     lowercase__           =  self.normalization(a	)
     lowercase__           =  self.activation(a	)
     return hidden_state






class     SCREAMING_SNAKE_CASE       (nn.Module				):


   def __init__(   self      :    List[Any]      ,					a      :    RegNetConfig	)->       Dict:





     """simple docstring"""







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


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Tuple      ,					a      :    Tuple	)->       int:





     """simple docstring"""







     lowercase__           =  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__           =  self.embedder(a	)
     return hidden_state






class     SCREAMING_SNAKE_CASE       (nn.Module				):


   def __init__(   self      :    Dict      ,					a      :    int      ,					a      :    int      ,					a      :    int = 2	)->       Dict:





     """simple docstring"""







     super().__init__()
     lowercase__           =  nn.Convad(a      ,					a      ,					kernel_size=1      ,					stride=a      ,					bias=a	)
     lowercase__           =  nn.BatchNormad(a	)


   def 	SCREAMING_SNAKE_CASE_							(   self      :    List[str]      ,					a      :    Tensor	)->       Tensor:





     """simple docstring"""







     lowercase__           =  self.convolution(a	)
     lowercase__           =  self.normalization(a	)
     return hidden_state






class     SCREAMING_SNAKE_CASE       (nn.Module				):


   def __init__(   self      :    Optional[int]      ,					a      :    int      ,					a      :    int	)->       int:





     """simple docstring"""







     super().__init__()

     lowercase__           =  nn.AdaptiveAvgPoolad((1, 1)	)
     lowercase__           =  nn.Sequential(
         nn.Convad(a      ,					a      ,					kernel_size=1	)      ,					nn.ReLU()      ,					nn.Convad(a      ,					a      ,					kernel_size=1	)      ,					nn.Sigmoid()      ,					)


   def 	SCREAMING_SNAKE_CASE_							(   self      :    List[str]      ,					a      :    Tuple	)->       str:





     """simple docstring"""







     lowercase__           =  self.pooler(a	)
     lowercase__           =  self.attention(a	)
     lowercase__           =  hidden_state * attention
     return hidden_state






class     SCREAMING_SNAKE_CASE       (nn.Module				):


   def __init__(   self      :    Dict      ,					a      :    RegNetConfig      ,					a      :    int      ,					a      :    int      ,					a      :    int = 1	)->       Optional[int]:





     """simple docstring"""







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


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Optional[Any]      ,					a      :    List[str]	)->       Optional[int]:





     """simple docstring"""







     lowercase__           =  hidden_state
     lowercase__           =  self.layer(a	)
     lowercase__           =  self.shortcut(a	)
     hidden_state += residual
     lowercase__           =  self.activation(a	)
     return hidden_state






class     SCREAMING_SNAKE_CASE       (nn.Module				):


   def __init__(   self      :    Optional[int]      ,					a      :    RegNetConfig      ,					a      :    int      ,					a      :    int      ,					a      :    int = 1	)->       str:





     """simple docstring"""







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


   def 	SCREAMING_SNAKE_CASE_							(   self      :    str      ,					a      :    Optional[Any]	)->       Tuple:





     """simple docstring"""







     lowercase__           =  hidden_state
     lowercase__           =  self.layer(a	)
     lowercase__           =  self.shortcut(a	)
     hidden_state += residual
     lowercase__           =  self.activation(a	)
     return hidden_state






class     SCREAMING_SNAKE_CASE       (nn.Module				):


   def __init__(   self      :    Any      ,					a      :    RegNetConfig      ,					a      :    int      ,					a      :    int      ,					a      :    int = 2      ,					a      :    int = 2      ,					)->       Optional[int]:





     """simple docstring"""







     super().__init__()

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

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


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Dict      ,					a      :    Union[str, Any]	)->       Union[str, Any]:





     """simple docstring"""







     lowercase__           =  self.layers(a	)
     return hidden_state






class     SCREAMING_SNAKE_CASE       (nn.Module				):


   def __init__(   self      :    List[Any]      ,					a      :    RegNetConfig	)->       Dict:





     """simple docstring"""







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


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Optional[Any]      ,					a      :    Tensor      ,					a      :    bool = False      ,					a      :    bool = True	)->       BaseModelOutputWithNoAttention:





     """simple docstring"""







     lowercase__           =  () if output_hidden_states else None

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

       lowercase__           =  stage_module(a	)

     if output_hidden_states:
       lowercase__           =  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=a      ,					hidden_states=a	)






class     SCREAMING_SNAKE_CASE       (UpperCAmelCase				):
   _UpperCamelCase   :		Dict			 =	RegNetConfig
   _UpperCamelCase   :		int			 =	'regnet'
   _UpperCamelCase   :		Optional[int]			 =	'pixel_values'
   _UpperCamelCase   :		str			 =	True


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Optional[int]      ,					a      :    Any	)->       List[str]:





     """simple docstring"""







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


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Any      ,					a      :    Any      ,					a      :    Optional[int]=False	)->       Any:





     """simple docstring"""







     if isinstance(a      ,					a	):
       lowercase__           =  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.'      ,     UpperCAmelCase      ,     )
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class     SCREAMING_SNAKE_CASE       (UpperCAmelCase				):


   def __init__(   self      :    Optional[Any]      ,					a      :    Tuple	)->       Tuple:





     """simple docstring"""







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


   @add_start_docstrings_to_model_forward(a	)
   @add_code_sample_docstrings(
       checkpoint=_CHECKPOINT_FOR_DOC      ,					output_type=a      ,					config_class=_CONFIG_FOR_DOC      ,					modality='vision'      ,					expected_output=_EXPECTED_OUTPUT_SHAPE      ,					)
   def 	SCREAMING_SNAKE_CASE_							(   self      :    Optional[Any]      ,					a      :    Tensor      ,					a      :    Optional[bool] = None      ,					a      :    Optional[bool] = None	)->       BaseModelOutputWithPoolingAndNoAttention:





     """simple docstring"""







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

     lowercase__           =  self.embedder(a	)

     lowercase__           =  self.encoder(
         a      ,					output_hidden_states=a      ,					return_dict=a	)

     lowercase__           =  encoder_outputs[0]

     lowercase__           =  self.pooler(a	)

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

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


   def __init__(   self      :    Optional[Any]      ,					a      :    int	)->       Dict:





     """simple docstring"""







     super().__init__(a	)
     lowercase__           =  config.num_labels
     lowercase__           =  RegNetModel(a	)
     # classification head
     lowercase__           =  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(a	)
   @add_code_sample_docstrings(
       checkpoint=_IMAGE_CLASS_CHECKPOINT      ,					output_type=a      ,					config_class=_CONFIG_FOR_DOC      ,					expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT      ,					)
   def 	SCREAMING_SNAKE_CASE_							(   self      :    int      ,					a      :    Optional[torch.FloatTensor] = None      ,					a      :    Optional[torch.LongTensor] = None      ,					a      :    Optional[bool] = None      ,					a      :    Optional[bool] = None      ,					)->       ImageClassifierOutputWithNoAttention:





     """simple docstring"""







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

     lowercase__           =  self.regnet(a      ,					output_hidden_states=a      ,					return_dict=a	)

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

     lowercase__           =  self.classifier(a	)

     lowercase__           =  None

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

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

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









import unittest

import numpy as np

from transformers import DistilBertConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
      import jax.numpy as jnp

      from transformers.models.distilbert.modeling_flax_distilbert import (
          FlaxDistilBertForMaskedLM,
          FlaxDistilBertForMultipleChoice,
          FlaxDistilBertForQuestionAnswering,
          FlaxDistilBertForSequenceClassification,
          FlaxDistilBertForTokenClassification,
          FlaxDistilBertModel,
      )
class     SCREAMING_SNAKE_CASE       (unittest.TestCase				):


   def __init__(   self      :    List[str]      ,					a      :    Dict      ,					a      :    Optional[int]=13      ,					a      :    int=7      ,					a      :    List[str]=True      ,					a      :    Any=True      ,					a      :    Dict=True      ,					a      :    List[Any]=True      ,					a      :    List[str]=99      ,					a      :    Dict=32      ,					a      :    List[str]=5      ,					a      :    Tuple=4      ,					a      :    Optional[int]=37      ,					a      :    Union[str, Any]="gelu"      ,					a      :    Optional[Any]=0.1      ,					a      :    Optional[int]=0.1      ,					a      :    Optional[Any]=512      ,					a      :    Dict=16      ,					a      :    Any=2      ,					a      :    Tuple=0.02      ,					a      :    Optional[Any]=4      ,					)->       int:





     """simple docstring"""







     lowercase__           =  parent
     lowercase__           =  batch_size
     lowercase__           =  seq_length
     lowercase__           =  is_training
     lowercase__           =  use_attention_mask
     lowercase__           =  use_token_type_ids
     lowercase__           =  use_labels
     lowercase__           =  vocab_size
     lowercase__           =  hidden_size
     lowercase__           =  num_hidden_layers
     lowercase__           =  num_attention_heads
     lowercase__           =  intermediate_size
     lowercase__           =  hidden_act
     lowercase__           =  hidden_dropout_prob
     lowercase__           =  attention_probs_dropout_prob
     lowercase__           =  max_position_embeddings
     lowercase__           =  type_vocab_size
     lowercase__           =  type_sequence_label_size
     lowercase__           =  initializer_range
     lowercase__           =  num_choices


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





     """simple docstring"""







     lowercase__           =  ids_tensor([self.batch_size, self.seq_length]      ,					self.vocab_size	)

     lowercase__           =  None
     if self.use_attention_mask:
       lowercase__           =  random_attention_mask([self.batch_size, self.seq_length]	)

     lowercase__           =  DistilBertConfig(
         vocab_size=self.vocab_size      ,					dim=self.hidden_size      ,					n_layers=self.num_hidden_layers      ,					n_heads=self.num_attention_heads      ,					hidden_dim=self.intermediate_size      ,					hidden_act=self.hidden_act      ,					dropout=self.hidden_dropout_prob      ,					attention_dropout=self.attention_probs_dropout_prob      ,					max_position_embeddings=self.max_position_embeddings      ,					initializer_range=self.initializer_range      ,					tie_weights_=a      ,					)

     return config, input_ids, attention_mask


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Optional[Any]	)->       Any:





     """simple docstring"""







     lowercase__           =  self.prepare_config_and_inputs()
     lowercase__      ,   lowercase__      ,   lowercase__           =  config_and_inputs
     lowercase__           =  {'input_ids': input_ids, 'attention_mask': attention_mask}
     return config, inputs_dict






@require_flax
class     SCREAMING_SNAKE_CASE       (UpperCAmelCase      ,     unittest.TestCase				):
   _UpperCamelCase   :		List[Any]			 =	(
       (
           FlaxDistilBertModel,
           FlaxDistilBertForMaskedLM,
           FlaxDistilBertForMultipleChoice,
           FlaxDistilBertForQuestionAnswering,
           FlaxDistilBertForSequenceClassification,
           FlaxDistilBertForTokenClassification,
           FlaxDistilBertForQuestionAnswering,
       )
       if is_flax_available()
       else ()
   )


   def 	SCREAMING_SNAKE_CASE_							(   self      :    Dict	)->       List[str]:





     """simple docstring"""







     lowercase__           =  FlaxDistilBertModelTester(self	)


   @slow
   def 	SCREAMING_SNAKE_CASE_							(   self      :    List[str]	)->       int:





     """simple docstring"""







     for model_class_name in self.all_model_classes:
       lowercase__           =  model_class_name.from_pretrained('distilbert-base-uncased'	)
       lowercase__           =  model(np.ones((1, 1)	)	)
       self.assertIsNotNone(a	)






@require_flax
class     SCREAMING_SNAKE_CASE       (unittest.TestCase				):


   @slow
   def 	SCREAMING_SNAKE_CASE_							(   self      :    List[str]	)->       List[str]:





     """simple docstring"""







     lowercase__           =  FlaxDistilBertModel.from_pretrained('distilbert-base-uncased'	)
     lowercase__           =  np.array([[0, 345, 232, 328, 740, 140, 1_695, 69, 6_078, 1_588, 2]]	)
     lowercase__           =  np.array([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]	)
     lowercase__           =  model(a      ,					attention_mask=a	)[0]
     lowercase__           =  (1, 11, 768)
     self.assertEqual(output.shape      ,					a	)
     lowercase__           =  np.array([[[-0.1639, 0.3299, 0.1648], [-0.1746, 0.3289, 0.1710], [-0.1884, 0.3357, 0.1810]]]	)

     self.assertTrue(jnp.allclose(output[:, 1:4, 1:4]      ,					a      ,					atol=1E-4	)	)


