
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


__lowerCAmelCase     :	int       			=  logging.get_logger(__name__)

# General docstring
__lowerCAmelCase     :	Tuple       			=  'RegNetConfig'

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

# Image classification docstring
__lowerCAmelCase     :	Tuple       			=  'facebook/regnet-y-040'
__lowerCAmelCase     :	List[Any]       			=  'tabby, tabby cat'

__lowerCAmelCase     :	List[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     :					int     ,				UpperCamelCase__     :					int     ,				UpperCamelCase__     :					int     ,				UpperCamelCase__     :					int = 3     ,				UpperCamelCase__     :					int = 1     ,				UpperCamelCase__     :					int = 1     ,				UpperCamelCase__     :					Optional[str] = "relu"     ,				)     ->      Any:







    """simple docstring"""






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





  def 				_lowercase				(					self     :					Any     ,				UpperCamelCase__     :					List[str]       )     ->      str:







    """simple docstring"""






    __magic_name__								=			self.convolution(UpperCamelCase__       )
    __magic_name__								=			self.normalization(UpperCamelCase__       )
    __magic_name__								=			self.activation(UpperCamelCase__       )
    return hidden_state







class 			UpperCAmelCase_     (					nn.Module	):


  '''simple docstring'''







  def __init__(					self     :					int     ,				UpperCamelCase__     :					RegNetConfig       )     ->      Union[str, Any]:







    """simple docstring"""






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





  def 				_lowercase				(					self     :					Optional[Any]     ,				UpperCamelCase__     :					Optional[Any]       )     ->      List[str]:







    """simple docstring"""






    __magic_name__								=			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."""       )
    __magic_name__								=			self.embedder(UpperCamelCase__       )
    return hidden_state







class 			UpperCAmelCase_     (					nn.Module	):


  '''simple docstring'''







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







    """simple docstring"""






    super().__init__()
    __magic_name__								=			nn.Convad(UpperCamelCase__     ,				UpperCamelCase__     ,				kernel_size=1     ,				stride=UpperCamelCase__     ,				bias=UpperCamelCase__       )
    __magic_name__								=			nn.BatchNormad(UpperCamelCase__       )





  def 				_lowercase				(					self     :					str     ,				UpperCamelCase__     :					Tensor       )     ->      Tensor:







    """simple docstring"""






    __magic_name__								=			self.convolution(UpperCamelCase__       )
    __magic_name__								=			self.normalization(UpperCamelCase__       )
    return hidden_state







class 			UpperCAmelCase_     (					nn.Module	):


  '''simple docstring'''







  def __init__(					self     :					int     ,				UpperCamelCase__     :					int     ,				UpperCamelCase__     :					int       )     ->      Tuple:







    """simple docstring"""






    super().__init__()

    __magic_name__								=			nn.AdaptiveAvgPoolad((1, 1)       )
    __magic_name__								=			nn.Sequential(
        nn.Convad(UpperCamelCase__     ,				UpperCamelCase__     ,				kernel_size=1       )     ,				nn.ReLU()     ,				nn.Convad(UpperCamelCase__     ,				UpperCamelCase__     ,				kernel_size=1       )     ,				nn.Sigmoid()     ,				)





  def 				_lowercase				(					self     :					List[Any]     ,				UpperCamelCase__     :					Any       )     ->      str:







    """simple docstring"""






    __magic_name__								=			self.pooler(UpperCamelCase__       )
    __magic_name__								=			self.attention(UpperCamelCase__       )
    __magic_name__								=			hidden_state * attention
    return hidden_state







class 			UpperCAmelCase_     (					nn.Module	):


  '''simple docstring'''







  def __init__(					self     :					Union[str, Any]     ,				UpperCamelCase__     :					RegNetConfig     ,				UpperCamelCase__     :					int     ,				UpperCamelCase__     :					int     ,				UpperCamelCase__     :					int = 1       )     ->      List[Any]:







    """simple docstring"""






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





  def 				_lowercase				(					self     :					str     ,				UpperCamelCase__     :					List[str]       )     ->      List[Any]:







    """simple docstring"""






    __magic_name__								=			hidden_state
    __magic_name__								=			self.layer(UpperCamelCase__       )
    __magic_name__								=			self.shortcut(UpperCamelCase__       )
    hidden_state += residual
    __magic_name__								=			self.activation(UpperCamelCase__       )
    return hidden_state







class 			UpperCAmelCase_     (					nn.Module	):


  '''simple docstring'''







  def __init__(					self     :					Tuple     ,				UpperCamelCase__     :					RegNetConfig     ,				UpperCamelCase__     :					int     ,				UpperCamelCase__     :					int     ,				UpperCamelCase__     :					int = 1       )     ->      Any:







    """simple docstring"""






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





  def 				_lowercase				(					self     :					Tuple     ,				UpperCamelCase__     :					Tuple       )     ->      Union[str, Any]:







    """simple docstring"""






    __magic_name__								=			hidden_state
    __magic_name__								=			self.layer(UpperCamelCase__       )
    __magic_name__								=			self.shortcut(UpperCamelCase__       )
    hidden_state += residual
    __magic_name__								=			self.activation(UpperCamelCase__       )
    return hidden_state







class 			UpperCAmelCase_     (					nn.Module	):


  '''simple docstring'''







  def __init__(					self     :					List[Any]     ,				UpperCamelCase__     :					RegNetConfig     ,				UpperCamelCase__     :					int     ,				UpperCamelCase__     :					int     ,				UpperCamelCase__     :					int = 2     ,				UpperCamelCase__     :					int = 2     ,				)     ->      List[str]:







    """simple docstring"""






    super().__init__()

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

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





  def 				_lowercase				(					self     :					List[Any]     ,				UpperCamelCase__     :					str       )     ->      Any:







    """simple docstring"""






    __magic_name__								=			self.layers(UpperCamelCase__       )
    return hidden_state







class 			UpperCAmelCase_     (					nn.Module	):


  '''simple docstring'''







  def __init__(					self     :					Dict     ,				UpperCamelCase__     :					RegNetConfig       )     ->      Tuple:







    """simple docstring"""






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





  def 				_lowercase				(					self     :					Tuple     ,				UpperCamelCase__     :					Tensor     ,				UpperCamelCase__     :					bool = False     ,				UpperCamelCase__     :					bool = True       )     ->      BaseModelOutputWithNoAttention:







    """simple docstring"""






    __magic_name__								=			() if output_hidden_states else None

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

      __magic_name__								=			stage_module(UpperCamelCase__       )

    if output_hidden_states:
      __magic_name__								=			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=UpperCamelCase__     ,				hidden_states=UpperCamelCase__       )







class 			UpperCAmelCase_     (					_A	):


  '''simple docstring'''







  a__       			=						RegNetConfig
  a__       			=						"""regnet"""
  a__       			=						"""pixel_values"""
  a__       			=						True
  def 				_lowercase				(					self     :					Union[str, Any]     ,				UpperCamelCase__     :					List[Any]       )     ->      Optional[Any]:







    """simple docstring"""






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





  def 				_lowercase				(					self     :					List[str]     ,				UpperCamelCase__     :					List[str]     ,				UpperCamelCase__     :					List[Any]=False       )     ->      int:







    """simple docstring"""






    if isinstance(UpperCamelCase__     ,				UpperCamelCase__       ):
      __magic_name__								=			value







__lowerCAmelCase     :	Dict       			=  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'

__lowerCAmelCase     :	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."""    ,			_A    ,			)
# Copied from transformers.models.resnet.modeling_resnet.ResNetModel with RESNET->REGNET,ResNet->RegNet
class 			UpperCAmelCase_     (					_A	):


  '''simple docstring'''







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







    """simple docstring"""






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





  @add_start_docstrings_to_model_forward(UpperCamelCase__       )
  @add_code_sample_docstrings(
      checkpoint=_CHECKPOINT_FOR_DOC     ,				output_type=UpperCamelCase__     ,				config_class=_CONFIG_FOR_DOC     ,				modality="""vision"""     ,				expected_output=_EXPECTED_OUTPUT_SHAPE     ,				)
  def 				_lowercase				(					self     :					Union[str, Any]     ,				UpperCamelCase__     :					Tensor     ,				UpperCamelCase__     :					Optional[bool] = None     ,				UpperCamelCase__     :					Optional[bool] = None       )     ->      BaseModelOutputWithPoolingAndNoAttention:







    """simple docstring"""






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

    __magic_name__								=			self.embedder(UpperCamelCase__       )

    __magic_name__								=			self.encoder(
        UpperCamelCase__     ,				output_hidden_states=UpperCamelCase__     ,				return_dict=UpperCamelCase__       )

    __magic_name__								=			encoder_outputs[0]

    __magic_name__								=			self.pooler(UpperCamelCase__       )

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

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


  '''simple docstring'''







  def __init__(					self     :					str     ,				UpperCamelCase__     :					List[str]       )     ->      Optional[Any]:







    """simple docstring"""






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







    """simple docstring"""






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

    __magic_name__								=			self.regnet(UpperCamelCase__     ,				output_hidden_states=UpperCamelCase__     ,				return_dict=UpperCamelCase__       )

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

    __magic_name__								=			self.classifier(UpperCamelCase__       )

    __magic_name__								=			None

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

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

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



from ...configuration_utils import PretrainedConfig
from ...utils import logging


__lowerCAmelCase     :	Dict       			=  logging.get_logger(__name__)

__lowerCAmelCase     :	int       			=  {
    'microsoft/trocr-base-handwritten': (
        'https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json'
    ),
    # See all TrOCR models at https://huggingface.co/models?filter=trocr
}




class 			UpperCAmelCase_     (					_A	):


  '''simple docstring'''







  a__       			=						"""trocr"""
  a__       			=						["""past_key_values"""]
  a__       			=						{
      """num_attention_heads""": """decoder_attention_heads""",
      """hidden_size""": """d_model""",
      """num_hidden_layers""": """decoder_layers""",
  }
  def __init__(					self     :					Dict     ,				UpperCamelCase__     :					Optional[Any]=5_0265     ,				UpperCamelCase__     :					int=1024     ,				UpperCamelCase__     :					int=12     ,				UpperCamelCase__     :					List[Any]=16     ,				UpperCamelCase__     :					Union[str, Any]=4096     ,				UpperCamelCase__     :					List[Any]="gelu"     ,				UpperCamelCase__     :					Optional[int]=512     ,				UpperCamelCase__     :					Optional[Any]=0.1     ,				UpperCamelCase__     :					int=0.0     ,				UpperCamelCase__     :					str=0.0     ,				UpperCamelCase__     :					Optional[int]=2     ,				UpperCamelCase__     :					List[str]=0.02     ,				UpperCamelCase__     :					Dict=0.0     ,				UpperCamelCase__     :					List[str]=True     ,				UpperCamelCase__     :					str=False     ,				UpperCamelCase__     :					List[str]=True     ,				UpperCamelCase__     :					Tuple=True     ,				UpperCamelCase__     :					str=1     ,				UpperCamelCase__     :					Union[str, Any]=0     ,				UpperCamelCase__     :					List[str]=2     ,				**UpperCamelCase__     :					Tuple     ,				)     ->      Dict:







    """simple docstring"""






    __magic_name__								=			vocab_size
    __magic_name__								=			d_model
    __magic_name__								=			decoder_layers
    __magic_name__								=			decoder_attention_heads
    __magic_name__								=			decoder_ffn_dim
    __magic_name__								=			activation_function
    __magic_name__								=			max_position_embeddings
    __magic_name__								=			dropout
    __magic_name__								=			attention_dropout
    __magic_name__								=			activation_dropout
    __magic_name__								=			init_std
    __magic_name__								=			decoder_layerdrop
    __magic_name__								=			use_cache
    __magic_name__								=			scale_embedding
    __magic_name__								=			use_learned_position_embeddings
    __magic_name__								=			layernorm_embedding

    super().__init__(
        pad_token_id=UpperCamelCase__     ,				bos_token_id=UpperCamelCase__     ,				eos_token_id=UpperCamelCase__     ,				decoder_start_token_id=UpperCamelCase__     ,				**UpperCamelCase__     ,				)

