



'''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 ...modeling_outputs import (
    BackboneOutput,
    BaseModelOutputWithNoAttention,
    BaseModelOutputWithPoolingAndNoAttention,
    ImageClassifierOutputWithNoAttention,
)
from ...modeling_utils import PreTrainedModel
from ...utils import (
    add_code_sample_docstrings,
    add_start_docstrings,
    add_start_docstrings_to_model_forward,
    logging,
    replace_return_docstrings,
)
from ...utils.backbone_utils import BackboneMixin
from .configuration_resnet import ResNetConfig


_UpperCamelCase											=		logging.get_logger(__name__)

# General docstring
_UpperCamelCase											=		'ResNetConfig'

# Base docstring
_UpperCamelCase											=		'microsoft/resnet-50'
_UpperCamelCase											=		[1, 2048, 7, 7]

# Image classification docstring
_UpperCamelCase											=		'microsoft/resnet-50'
_UpperCamelCase											=		'tiger cat'

_UpperCamelCase											=		[
    'microsoft/resnet-50',
    # See all resnet models at https://huggingface.co/models?filter=resnet
]






class    lowerCamelCase_       (							nn.Module	):
  """simple docstring"""




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




  def 		_lowercase	(					self :      Tuple     ,      _a :      Tensor  )   ->   Tensor:
    __lowerCamelCase			:			Dict       			=					self.convolution(_a  )
    __lowerCamelCase			:			Any       			=					self.normalization(_a  )
    __lowerCamelCase			:			Any       			=					self.activation(_a  )
    return hidden_state






class    lowerCamelCase_       (							nn.Module	):
  """simple docstring"""




  def __init__(					self :      Tuple     ,      _a :      ResNetConfig  )   ->   Optional[int]:
    super().__init__()
    __lowerCamelCase			:			Any       			=					ResNetConvLayer(
        config.num_channels     ,      config.embedding_size     ,      kernel_size=7     ,      stride=2     ,      activation=config.hidden_act  )
    __lowerCamelCase			:			str       			=					nn.MaxPoolad(kernel_size=3     ,      stride=2     ,      padding=1  )
    __lowerCamelCase			:			Optional[Any]       			=					config.num_channels




  def 		_lowercase	(					self :      Tuple     ,      _a :      Tensor  )   ->   Tensor:
    __lowerCamelCase			:			int       			=					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			:			List[str]       			=					self.embedder(_a  )
    __lowerCamelCase			:			Dict       			=					self.pooler(_a  )
    return embedding






class    lowerCamelCase_       (							nn.Module	):
  """simple docstring"""




  def __init__(					self :      Optional[int]     ,      _a :      int     ,      _a :      int     ,      _a :      int = 2  )   ->   Dict:
    super().__init__()
    __lowerCamelCase			:			int       			=					nn.Convad(_a     ,      _a     ,      kernel_size=1     ,      stride=_a     ,      bias=_a  )
    __lowerCamelCase			:			Optional[int]       			=					nn.BatchNormad(_a  )




  def 		_lowercase	(					self :      Tuple     ,      _a :      Tensor  )   ->   Tensor:
    __lowerCamelCase			:			Optional[Any]       			=					self.convolution(_a  )
    __lowerCamelCase			:			Optional[Any]       			=					self.normalization(_a  )
    return hidden_state






class    lowerCamelCase_       (							nn.Module	):
  """simple docstring"""




  def __init__(					self :      List[str]     ,      _a :      int     ,      _a :      int     ,      _a :      int = 1     ,      _a :      str = "relu"  )   ->   Tuple:
    super().__init__()
    __lowerCamelCase			:			List[str]       			=					in_channels != out_channels or stride != 1
    __lowerCamelCase			:			Optional[int]       			=					(
        ResNetShortCut(_a     ,      _a     ,      stride=_a  ) if should_apply_shortcut else nn.Identity()
    )
    __lowerCamelCase			:			List[Any]       			=					nn.Sequential(
        ResNetConvLayer(_a     ,      _a     ,      stride=_a  )     ,      ResNetConvLayer(_a     ,      _a     ,      activation=_a  )     ,      )
    __lowerCamelCase			:			List[Any]       			=					ACTaFN[activation]




  def 		_lowercase	(					self :      List[Any]     ,      _a :      Tuple  )   ->   Optional[Any]:
    __lowerCamelCase			:			Union[str, Any]       			=					hidden_state
    __lowerCamelCase			:			Union[str, Any]       			=					self.layer(_a  )
    __lowerCamelCase			:			List[Any]       			=					self.shortcut(_a  )
    hidden_state += residual
    __lowerCamelCase			:			Any       			=					self.activation(_a  )
    return hidden_state






class    lowerCamelCase_       (							nn.Module	):
  """simple docstring"""




  def __init__(					self :      List[Any]     ,      _a :      int     ,      _a :      int     ,      _a :      int = 1     ,      _a :      str = "relu"     ,      _a :      int = 4  )   ->   List[str]:
    super().__init__()
    __lowerCamelCase			:			Tuple       			=					in_channels != out_channels or stride != 1
    __lowerCamelCase			:			Optional[int]       			=					out_channels // reduction
    __lowerCamelCase			:			List[Any]       			=					(
        ResNetShortCut(_a     ,      _a     ,      stride=_a  ) if should_apply_shortcut else nn.Identity()
    )
    __lowerCamelCase			:			int       			=					nn.Sequential(
        ResNetConvLayer(_a     ,      _a     ,      kernel_size=1  )     ,      ResNetConvLayer(_a     ,      _a     ,      stride=_a  )     ,      ResNetConvLayer(_a     ,      _a     ,      kernel_size=1     ,      activation=_a  )     ,      )
    __lowerCamelCase			:			int       			=					ACTaFN[activation]




  def 		_lowercase	(					self :      Tuple     ,      _a :      Optional[int]  )   ->   str:
    __lowerCamelCase			:			Optional[Any]       			=					hidden_state
    __lowerCamelCase			:			Dict       			=					self.layer(_a  )
    __lowerCamelCase			:			Union[str, Any]       			=					self.shortcut(_a  )
    hidden_state += residual
    __lowerCamelCase			:			str       			=					self.activation(_a  )
    return hidden_state






class    lowerCamelCase_       (							nn.Module	):
  """simple docstring"""




  def __init__(					self :      Tuple     ,      _a :      ResNetConfig     ,      _a :      int     ,      _a :      int     ,      _a :      int = 2     ,      _a :      int = 2     ,      )   ->   Any:
    super().__init__()

    __lowerCamelCase			:			int       			=					ResNetBottleNeckLayer if config.layer_type == 'bottleneck' else ResNetBasicLayer

    __lowerCamelCase			:			int       			=					nn.Sequential(
        # downsampling is done in the first layer with stride of 2
        layer(_a     ,      _a     ,      stride=_a     ,      activation=config.hidden_act  )     ,      *[layer(_a     ,      _a     ,      activation=config.hidden_act  ) for _ in range(depth - 1  )]     ,      )




  def 		_lowercase	(					self :      Tuple     ,      _a :      Tensor  )   ->   Tensor:
    __lowerCamelCase			:			Any       			=					input
    for layer in self.layers:
      __lowerCamelCase			:			str       			=					layer(_a  )
    return hidden_state






class    lowerCamelCase_       (							nn.Module	):
  """simple docstring"""




  def __init__(					self :      Union[str, Any]     ,      _a :      ResNetConfig  )   ->   Union[str, Any]:
    super().__init__()
    __lowerCamelCase			:			Optional[int]       			=					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(
        ResNetStage(
            _a     ,      config.embedding_size     ,      config.hidden_sizes[0]     ,      stride=2 if config.downsample_in_first_stage else 1     ,      depth=config.depths[0]     ,      )  )
    __lowerCamelCase			:			Any       			=					zip(config.hidden_sizes     ,      config.hidden_sizes[1:]  )
    for (in_channels, out_channels), depth in zip(_a     ,      config.depths[1:]  ):
      self.stages.append(ResNetStage(_a     ,      _a     ,      _a     ,      depth=_a  )  )




  def 		_lowercase	(					self :      Union[str, Any]     ,      _a :      Tensor     ,      _a :      bool = False     ,      _a :      bool = True  )   ->   BaseModelOutputWithNoAttention:
    __lowerCamelCase			:			Any       			=					() if output_hidden_states else None

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

      __lowerCamelCase			:			Dict       			=					stage_module(_a  )

    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=_a     ,      hidden_states=_a     ,      )






class    lowerCamelCase_       (							SCREAMING_SNAKE_CASE_	):
  """simple docstring"""




  a_				   =ResNetConfig
  a_				   ="""resnet"""
  a_				   ="""pixel_values"""
  a_				   =True




  def 		_lowercase	(					self :      List[Any]     ,      _a :      Union[str, Any]  )   ->   Tuple:
    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 		_lowercase	(					self :      int     ,      _a :      Tuple     ,      _a :      Optional[int]=False  )   ->   List[Any]:
    if isinstance(_a     ,      _a  ):
      __lowerCamelCase			:			Dict       			=					value




_UpperCamelCase											=		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 ([`ResNetConfig`]): 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'

_UpperCamelCase											=		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 [`~utils.ModelOutput`] instead of a plain tuple.\n'






@add_start_docstrings(
    """The bare ResNet model outputting raw features without any specific head on top."""  ,  SCREAMING_SNAKE_CASE_  ,  )
class    lowerCamelCase_       (							SCREAMING_SNAKE_CASE_	):
  """simple docstring"""




  def __init__(					self :      Any     ,      _a :      Union[str, Any]  )   ->   List[str]:
    super().__init__(_a  )
    __lowerCamelCase			:			List[str]       			=					config
    __lowerCamelCase			:			Tuple       			=					ResNetEmbeddings(_a  )
    __lowerCamelCase			:			List[str]       			=					ResNetEncoder(_a  )
    __lowerCamelCase			:			Union[str, Any]       			=					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 		_lowercase	(					self :      Any     ,      _a :      Tensor     ,      _a :      Optional[bool] = None     ,      _a :      Optional[bool] = None  )   ->   BaseModelOutputWithPoolingAndNoAttention:
    __lowerCamelCase			:			Dict       			=					(
        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    )
    __lowerCamelCase			:			List[Any]       			=					return_dict if return_dict is not None else self.config.use_return_dict

    __lowerCamelCase			:			List[str]       			=					self.embedder(_a  )

    __lowerCamelCase			:			Tuple       			=					self.encoder(
        _a     ,      output_hidden_states=_a     ,      return_dict=_a  )

    __lowerCamelCase			:			List[str]       			=					encoder_outputs[0]

    __lowerCamelCase			:			Union[str, Any]       			=					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(
    """
    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    """  ,  SCREAMING_SNAKE_CASE_  ,  )
class    lowerCamelCase_       (							SCREAMING_SNAKE_CASE_	):
  """simple docstring"""




  def __init__(					self :      Optional[Any]     ,      _a :      List[str]  )   ->   List[Any]:
    super().__init__(_a  )
    __lowerCamelCase			:			Tuple       			=					config.num_labels
    __lowerCamelCase			:			str       			=					ResNetModel(_a  )
    # classification head
    __lowerCamelCase			:			int       			=					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 		_lowercase	(					self :      str     ,      _a :      Optional[torch.FloatTensor] = None     ,      _a :      Optional[torch.LongTensor] = None     ,      _a :      Optional[bool] = None     ,      _a :      Optional[bool] = None     ,      )   ->   ImageClassifierOutputWithNoAttention:
    __lowerCamelCase			:			List[str]       			=					return_dict if return_dict is not None else self.config.use_return_dict

    __lowerCamelCase			:			Optional[int]       			=					self.resnet(_a     ,      output_hidden_states=_a     ,      return_dict=_a  )

    __lowerCamelCase			:			Dict       			=					outputs.pooler_output if return_dict else outputs[1]

    __lowerCamelCase			:			Tuple       			=					self.classifier(_a  )

    __lowerCamelCase			:			Optional[int]       			=					None

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

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

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






@add_start_docstrings(
    """
    ResNet backbone, to be used with frameworks like DETR and MaskFormer.
    """  ,  SCREAMING_SNAKE_CASE_  ,  )
class    lowerCamelCase_       (							SCREAMING_SNAKE_CASE_  ,  SCREAMING_SNAKE_CASE_	):
  """simple docstring"""




  def __init__(					self :      Optional[Any]     ,      _a :      Tuple  )   ->   List[str]:
    super().__init__(_a  )
    super()._init_backbone(_a  )

    __lowerCamelCase			:			Optional[Any]       			=					[config.embedding_size] + config.hidden_sizes
    __lowerCamelCase			:			Tuple       			=					ResNetEmbeddings(_a  )
    __lowerCamelCase			:			List[str]       			=					ResNetEncoder(_a  )

    # initialize weights and apply final processing
    self.post_init()




  @add_start_docstrings_to_model_forward(_a  )
  @replace_return_docstrings(output_type=_a     ,      config_class=_CONFIG_FOR_DOC  )
  def 		_lowercase	(					self :      List[Any]     ,      _a :      Tensor     ,      _a :      Optional[bool] = None     ,      _a :      Optional[bool] = None  )   ->   BackboneOutput:
    __lowerCamelCase			:			Optional[Any]       			=					return_dict if return_dict is not None else self.config.use_return_dict
    __lowerCamelCase			:			Optional[Any]       			=					(
        output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
    )

    __lowerCamelCase			:			Optional[int]       			=					self.embedder(_a  )

    __lowerCamelCase			:			Any       			=					self.encoder(_a     ,      output_hidden_states=_a     ,      return_dict=_a  )

    __lowerCamelCase			:			Tuple       			=					outputs.hidden_states

    __lowerCamelCase			:			Dict       			=					()
    for idx, stage in enumerate(self.stage_names  ):
      if stage in self.out_features:
        feature_maps += (hidden_states[idx],)

    if not return_dict:
      __lowerCamelCase			:			List[Any]       			=					(feature_maps,)
      if output_hidden_states:
        output += (outputs.hidden_states,)
      return output

    return BackboneOutput(
        feature_maps=_a     ,      hidden_states=outputs.hidden_states if output_hidden_states else None     ,      attentions=_a     ,      )











'''simple docstring'''





def 			a_	(				_lowerCAmelCase			,_lowerCAmelCase			) -> tuple[float, float]:

  # Check if the input is valid
  if not len(_lowerCAmelCase			) == len(_lowerCAmelCase			) == 3:
    raise ValueError('Please enter a valid equation.'			)
  if equationa[0] == equationa[1] == equationa[0] == equationa[1] == 0:
    raise ValueError('Both a & b of two equations can\'t be zero.'			)

  # Extract the coefficients
  __lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			:			Union[str, Any]       			=					equationa
  __lowerCamelCase			,__lowerCamelCase			,__lowerCamelCase			:			Any       			=					equationa

  # Calculate the determinants of the matrices
  __lowerCamelCase			:			Union[str, Any]       			=					aa * ba - aa * ba
  __lowerCamelCase			:			Dict       			=					ca * ba - ca * ba
  __lowerCamelCase			:			List[str]       			=					aa * ca - aa * ca

  # Check if the system of linear equations has a solution (using Cramer's rule)
  if determinant == 0:
    if determinant_x == determinant_y == 0:
      raise ValueError('Infinite solutions. (Consistent system)'			)
    else:
      raise ValueError('No solution. (Inconsistent system)'			)
  else:
    if determinant_x == determinant_y == 0:
      # Trivial solution (Inconsistent system)
      return (0.0, 0.0)
    else:
      __lowerCamelCase			:			Tuple       			=					determinant_x / determinant
      __lowerCamelCase			:			Union[str, Any]       			=					determinant_y / determinant
      # Non-Trivial Solution (Consistent system)
      return (x, y)






