

from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFImageClassifierOutputWithNoAttention,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward, logging
from .configuration_resnet import ResNetConfig


__UpperCAmelCase      = logging.get_logger(__name__)

# General docstring
__UpperCAmelCase      = """ResNetConfig"""

# Base docstring
__UpperCAmelCase      = """microsoft/resnet-50"""
__UpperCAmelCase      = [1, 2_048, 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 SCREAMING_SNAKE_CASE	(  tf.keras.layers.Layer ):
  """simple docstring"""






  def __init__(			self :    Any       ,							lowerCAmelCase :    int       ,							lowerCAmelCase :    int = 3       ,							lowerCAmelCase :    int = 1       ,							lowerCAmelCase :    str = "relu"       ,							**lowerCAmelCase :    int    )							->	None:






     """simple docstring"""







     super().__init__(**lowerCAmelCase    )
     __lowerCAmelCase  :			Optional[Any]					    =						kernel_size // 2
     __lowerCAmelCase  :			Union[str, Any]					    =						tf.keras.layers.ConvaD(
         lowerCAmelCase       ,							kernel_size=lowerCAmelCase       ,							strides=lowerCAmelCase       ,							padding="""valid"""       ,							use_bias=lowerCAmelCase       ,							name="""convolution"""    )
     # Use same default momentum and epsilon as PyTorch equivalent
     __lowerCAmelCase  :			str					    =						tf.keras.layers.BatchNormalization(epsilon=1e-5       ,							momentum=0.9       ,							name="""normalization"""    )
     __lowerCAmelCase  :			Tuple					    =						ACTaFN[activation] if activation is not None else tf.keras.layers.Activation("""linear"""    )







  def        SCREAMING_SNAKE_CASE    (			self :    Dict       ,							lowerCAmelCase :    tf.Tensor    )							->	tf.Tensor:






     """simple docstring"""







     __lowerCAmelCase  :			List[Any]					    =						(self.pad_value, self.pad_value)
     __lowerCAmelCase  :			Optional[Any]					    =						tf.pad(lowerCAmelCase       ,							[(0, 0), height_pad, width_pad, (0, 0)]    )
     __lowerCAmelCase  :			Tuple					    =						self.conv(lowerCAmelCase    )
     return hidden_state







  def        SCREAMING_SNAKE_CASE    (			self :    int       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    bool = False    )							->	tf.Tensor:






     """simple docstring"""







     __lowerCAmelCase  :			Union[str, Any]					    =						self.convolution(lowerCAmelCase    )
     __lowerCAmelCase  :			Dict					    =						self.normalization(lowerCAmelCase       ,							training=lowerCAmelCase    )
     __lowerCAmelCase  :			Optional[int]					    =						self.activation(lowerCAmelCase    )
     return hidden_state






class SCREAMING_SNAKE_CASE	(  tf.keras.layers.Layer ):
  """simple docstring"""






  def __init__(			self :    str       ,							lowerCAmelCase :    ResNetConfig       ,							**lowerCAmelCase :    Union[str, Any]    )							->	None:






     """simple docstring"""







     super().__init__(**lowerCAmelCase    )
     __lowerCAmelCase  :			List[Any]					    =						TFResNetConvLayer(
         config.embedding_size       ,							kernel_size=7       ,							stride=2       ,							activation=config.hidden_act       ,							name="""embedder"""       ,							)
     __lowerCAmelCase  :			List[Any]					    =						tf.keras.layers.MaxPoolaD(pool_size=3       ,							strides=2       ,							padding="""valid"""       ,							name="""pooler"""    )
     __lowerCAmelCase  :			List[str]					    =						config.num_channels







  def        SCREAMING_SNAKE_CASE    (			self :    Dict       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    bool = False    )							->	tf.Tensor:






     """simple docstring"""







     __lowerCAmelCase    ,__lowerCAmelCase    ,__lowerCAmelCase    ,__lowerCAmelCase  :			Any					    =						shape_list(lowerCAmelCase    )
     if tf.executing_eagerly() and 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  :			Union[str, Any]					    =						pixel_values
     __lowerCAmelCase  :			int					    =						self.embedder(lowerCAmelCase    )
     __lowerCAmelCase  :			Any					    =						tf.pad(lowerCAmelCase       ,							[[0, 0], [1, 1], [1, 1], [0, 0]]    )
     __lowerCAmelCase  :			Any					    =						self.pooler(lowerCAmelCase    )
     return hidden_state






class SCREAMING_SNAKE_CASE	(  tf.keras.layers.Layer ):
  """simple docstring"""






  def __init__(			self :    List[Any]       ,							lowerCAmelCase :    int       ,							lowerCAmelCase :    int = 2       ,							**lowerCAmelCase :    Dict    )							->	None:






     """simple docstring"""







     super().__init__(**lowerCAmelCase    )
     __lowerCAmelCase  :			Optional[int]					    =						tf.keras.layers.ConvaD(
         lowerCAmelCase       ,							kernel_size=1       ,							strides=lowerCAmelCase       ,							use_bias=lowerCAmelCase       ,							name="""convolution"""    )
     # Use same default momentum and epsilon as PyTorch equivalent
     __lowerCAmelCase  :			Optional[int]					    =						tf.keras.layers.BatchNormalization(epsilon=1e-5       ,							momentum=0.9       ,							name="""normalization"""    )







  def        SCREAMING_SNAKE_CASE    (			self :    int       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    bool = False    )							->	tf.Tensor:






     """simple docstring"""







     __lowerCAmelCase  :			List[Any]					    =						x
     __lowerCAmelCase  :			int					    =						self.convolution(lowerCAmelCase    )
     __lowerCAmelCase  :			Dict					    =						self.normalization(lowerCAmelCase       ,							training=lowerCAmelCase    )
     return hidden_state






class SCREAMING_SNAKE_CASE	(  tf.keras.layers.Layer ):
  """simple docstring"""






  def __init__(			self :    int       ,							lowerCAmelCase :    int       ,							lowerCAmelCase :    int       ,							lowerCAmelCase :    int = 1       ,							lowerCAmelCase :    str = "relu"       ,							**lowerCAmelCase :    Tuple    )							->	None:






     """simple docstring"""







     super().__init__(**lowerCAmelCase    )
     __lowerCAmelCase  :			Optional[Any]					    =						in_channels != out_channels or stride != 1
     __lowerCAmelCase  :			List[Any]					    =						TFResNetConvLayer(lowerCAmelCase       ,							stride=lowerCAmelCase       ,							name="""layer.0"""    )
     __lowerCAmelCase  :			Optional[int]					    =						TFResNetConvLayer(lowerCAmelCase       ,							activation=lowerCAmelCase       ,							name="""layer.1"""    )
     __lowerCAmelCase  :			Dict					    =						(
         TFResNetShortCut(lowerCAmelCase       ,							stride=lowerCAmelCase       ,							name="""shortcut"""    )
         if should_apply_shortcut
         else tf.keras.layers.Activation("""linear"""       ,							name="""shortcut"""    )
     )
     __lowerCAmelCase  :			List[str]					    =						ACTaFN[activation]







  def        SCREAMING_SNAKE_CASE    (			self :    List[str]       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    bool = False    )							->	tf.Tensor:






     """simple docstring"""







     __lowerCAmelCase  :			Any					    =						hidden_state
     __lowerCAmelCase  :			Tuple					    =						self.conva(lowerCAmelCase       ,							training=lowerCAmelCase    )
     __lowerCAmelCase  :			Optional[int]					    =						self.conva(lowerCAmelCase       ,							training=lowerCAmelCase    )
     __lowerCAmelCase  :			List[Any]					    =						self.shortcut(lowerCAmelCase       ,							training=lowerCAmelCase    )
     hidden_state += residual
     __lowerCAmelCase  :			List[str]					    =						self.activation(lowerCAmelCase    )
     return hidden_state






class SCREAMING_SNAKE_CASE	(  tf.keras.layers.Layer ):
  """simple docstring"""






  def __init__(			self :    Dict       ,							lowerCAmelCase :    int       ,							lowerCAmelCase :    int       ,							lowerCAmelCase :    int = 1       ,							lowerCAmelCase :    str = "relu"       ,							lowerCAmelCase :    int = 4       ,							**lowerCAmelCase :    int       ,							)							->	None:






     """simple docstring"""







     super().__init__(**lowerCAmelCase    )
     __lowerCAmelCase  :			Dict					    =						in_channels != out_channels or stride != 1
     __lowerCAmelCase  :			Tuple					    =						out_channels // reduction
     __lowerCAmelCase  :			Optional[Any]					    =						TFResNetConvLayer(lowerCAmelCase       ,							kernel_size=1       ,							name="""layer.0"""    )
     __lowerCAmelCase  :			Any					    =						TFResNetConvLayer(lowerCAmelCase       ,							stride=lowerCAmelCase       ,							name="""layer.1"""    )
     __lowerCAmelCase  :			Any					    =						TFResNetConvLayer(lowerCAmelCase       ,							kernel_size=1       ,							activation=lowerCAmelCase       ,							name="""layer.2"""    )
     __lowerCAmelCase  :			Optional[int]					    =						(
         TFResNetShortCut(lowerCAmelCase       ,							stride=lowerCAmelCase       ,							name="""shortcut"""    )
         if should_apply_shortcut
         else tf.keras.layers.Activation("""linear"""       ,							name="""shortcut"""    )
     )
     __lowerCAmelCase  :			Dict					    =						ACTaFN[activation]







  def        SCREAMING_SNAKE_CASE    (			self :    Tuple       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    bool = False    )							->	tf.Tensor:






     """simple docstring"""







     __lowerCAmelCase  :			int					    =						hidden_state
     __lowerCAmelCase  :			List[Any]					    =						self.conva(lowerCAmelCase       ,							training=lowerCAmelCase    )
     __lowerCAmelCase  :			Optional[int]					    =						self.conva(lowerCAmelCase       ,							training=lowerCAmelCase    )
     __lowerCAmelCase  :			Dict					    =						self.conva(lowerCAmelCase       ,							training=lowerCAmelCase    )
     __lowerCAmelCase  :			Union[str, Any]					    =						self.shortcut(lowerCAmelCase       ,							training=lowerCAmelCase    )
     hidden_state += residual
     __lowerCAmelCase  :			Optional[Any]					    =						self.activation(lowerCAmelCase    )
     return hidden_state






class SCREAMING_SNAKE_CASE	(  tf.keras.layers.Layer ):
  """simple docstring"""






  def __init__(			self :    Any       ,							lowerCAmelCase :    ResNetConfig       ,							lowerCAmelCase :    int       ,							lowerCAmelCase :    int       ,							lowerCAmelCase :    int = 2       ,							lowerCAmelCase :    int = 2       ,							**lowerCAmelCase :    int    )							->	None:






     """simple docstring"""







     super().__init__(**lowerCAmelCase    )

     __lowerCAmelCase  :			Dict					    =						TFResNetBottleNeckLayer if config.layer_type == """bottleneck""" else TFResNetBasicLayer

     __lowerCAmelCase  :			Dict					    =						[layer(lowerCAmelCase       ,							lowerCAmelCase       ,							stride=lowerCAmelCase       ,							activation=config.hidden_act       ,							name="""layers.0"""    )]
     layers += [
         layer(lowerCAmelCase       ,							lowerCAmelCase       ,							activation=config.hidden_act       ,							name=f'''layers.{i + 1}'''    )
         for i in range(depth - 1    )
     ]
     __lowerCAmelCase  :			Optional[Any]					    =						layers







  def        SCREAMING_SNAKE_CASE    (			self :    Any       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    bool = False    )							->	tf.Tensor:






     """simple docstring"""







     for layer in self.stage_layers:
        __lowerCAmelCase  :			Union[str, Any]					    =						layer(lowerCAmelCase       ,							training=lowerCAmelCase    )
     return hidden_state






class SCREAMING_SNAKE_CASE	(  tf.keras.layers.Layer ):
  """simple docstring"""






  def __init__(			self :    str       ,							lowerCAmelCase :    ResNetConfig       ,							**lowerCAmelCase :    Any    )							->	None:






     """simple docstring"""







     super().__init__(**lowerCAmelCase    )
     # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
     __lowerCAmelCase  :			Dict					    =						[
         TFResNetStage(
             lowerCAmelCase       ,							config.embedding_size       ,							config.hidden_sizes[0]       ,							stride=2 if config.downsample_in_first_stage else 1       ,							depth=config.depths[0]       ,							name="""stages.0"""       ,							)
     ]
     for i, (in_channels, out_channels, depth) in enumerate(
         zip(config.hidden_sizes       ,							config.hidden_sizes[1:]       ,							config.depths[1:]    )    ):
        self.stages.append(TFResNetStage(lowerCAmelCase       ,							lowerCAmelCase       ,							lowerCAmelCase       ,							depth=lowerCAmelCase       ,							name=f'''stages.{i + 1}'''    )    )







  def        SCREAMING_SNAKE_CASE    (			self :    Optional[Any]       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    bool = False       ,							lowerCAmelCase :    bool = True       ,							lowerCAmelCase :    bool = False       ,							)							->	TFBaseModelOutputWithNoAttention:






     """simple docstring"""







     __lowerCAmelCase  :			str					    =						() 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  :			Optional[int]					    =						stage_module(lowerCAmelCase       ,							training=lowerCAmelCase    )

     if output_hidden_states:
        __lowerCAmelCase  :			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 TFBaseModelOutputWithNoAttention(last_hidden_state=lowerCAmelCase       ,							hidden_states=lowerCAmelCase    )






class SCREAMING_SNAKE_CASE	(  a_ ):
  """simple docstring"""






  lowerCamelCase    :			Optional[Any]						      =ResNetConfig
  lowerCamelCase    :			List[Any]						      ="resnet"
  lowerCamelCase    :			List[str]						      ="pixel_values"







  @property
  def        SCREAMING_SNAKE_CASE    (			self :    str    )							->	Union[str, Any]:






     """simple docstring"""







     return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 2_24, 2_24)       ,							dtype=tf.floataa    )}






__UpperCAmelCase      = R"""
    This model is a TensorFlow
    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a
    regular TensorFlow Module and refer to the TensorFlow documentation for all matter related to general usage and
    behavior.

    Parameters:
        config ([`ResNetConfig`]): 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 [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
"""


__UpperCAmelCase      = R"""
    Args:
        pixel_values (`tf.Tensor` 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 [`~utils.ModelOutput`] instead of a plain tuple.
"""



@keras_serializable
class SCREAMING_SNAKE_CASE	(  tf.keras.layers.Layer ):
  """simple docstring"""






  lowerCamelCase    :			int						      =ResNetConfig







  def __init__(			self :    Optional[Any]       ,							lowerCAmelCase :    ResNetConfig       ,							**lowerCAmelCase :    List[str]    )							->	None:






     """simple docstring"""







     super().__init__(**lowerCAmelCase    )
     __lowerCAmelCase  :			str					    =						config
     __lowerCAmelCase  :			List[Any]					    =						TFResNetEmbeddings(lowerCAmelCase       ,							name="""embedder"""    )
     __lowerCAmelCase  :			int					    =						TFResNetEncoder(lowerCAmelCase       ,							name="""encoder"""    )
     __lowerCAmelCase  :			List[Any]					    =						tf.keras.layers.GlobalAveragePoolingaD(keepdims=lowerCAmelCase    )







  @unpack_inputs
  def        SCREAMING_SNAKE_CASE    (			self :    Any       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    Optional[bool] = None       ,							lowerCAmelCase :    Optional[bool] = None       ,							lowerCAmelCase :    bool = False       ,							)							->	Union[Tuple[tf.Tensor], TFBaseModelOutputWithPoolingAndNoAttention]:






     """simple docstring"""







     __lowerCAmelCase  :			Optional[Any]					    =						(
         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

     # TF 2.0 image layers can't use NCHW format when running on CPU.
     # We transpose to NHWC format and then transpose back after the full forward pass.
     # (batch_size, num_channels, height, width) -> (batch_size, height, width, num_channels)
     __lowerCAmelCase  :			Optional[Any]					    =						tf.transpose(lowerCAmelCase       ,							perm=[0, 2, 3, 1]    )
     __lowerCAmelCase  :			Any					    =						self.embedder(lowerCAmelCase       ,							training=lowerCAmelCase    )

     __lowerCAmelCase  :			int					    =						self.encoder(
         lowerCAmelCase       ,							output_hidden_states=lowerCAmelCase       ,							return_dict=lowerCAmelCase       ,							training=lowerCAmelCase    )

     __lowerCAmelCase  :			List[str]					    =						encoder_outputs[0]

     __lowerCAmelCase  :			Dict					    =						self.pooler(lowerCAmelCase    )

     # Transpose all the outputs to the NCHW format
     # (batch_size, height, width, num_channels) -> (batch_size, num_channels, height, width)
     __lowerCAmelCase  :			Dict					    =						tf.transpose(lowerCAmelCase       ,							(0, 3, 1, 2)    )
     __lowerCAmelCase  :			Dict					    =						tf.transpose(lowerCAmelCase       ,							(0, 3, 1, 2)    )
     __lowerCAmelCase  :			Any					    =						()
     for hidden_state in encoder_outputs[1:]:
        __lowerCAmelCase  :			List[Any]					    =						hidden_states + tuple(tf.transpose(lowerCAmelCase       ,							(0, 3, 1, 2)    ) for h in hidden_state    )

     if not return_dict:
        return (last_hidden_state, pooled_output) + hidden_states

     __lowerCAmelCase  :			Dict					    =						hidden_states if output_hidden_states else None

     return TFBaseModelOutputWithPoolingAndNoAttention(
         last_hidden_state=lowerCAmelCase       ,							pooler_output=lowerCAmelCase       ,							hidden_states=lowerCAmelCase       ,							)






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






  def __init__(			self :    Optional[int]       ,							lowerCAmelCase :    ResNetConfig       ,							**lowerCAmelCase :    int    )							->	None:






     """simple docstring"""







     super().__init__(lowerCAmelCase       ,							**lowerCAmelCase    )
     __lowerCAmelCase  :			Optional[int]					    =						TFResNetMainLayer(config=lowerCAmelCase       ,							name="""resnet"""    )







  @add_start_docstrings_to_model_forward(lowerCAmelCase    )
  @add_code_sample_docstrings(
      checkpoint=_CHECKPOINT_FOR_DOC       ,							output_type=lowerCAmelCase       ,							config_class=_CONFIG_FOR_DOC       ,							modality="""vision"""       ,							expected_output=_EXPECTED_OUTPUT_SHAPE       ,							)
  @unpack_inputs
  def        SCREAMING_SNAKE_CASE    (			self :    Any       ,							lowerCAmelCase :    tf.Tensor       ,							lowerCAmelCase :    Optional[bool] = None       ,							lowerCAmelCase :    Optional[bool] = None       ,							lowerCAmelCase :    bool = False       ,							)							->	Union[Tuple[tf.Tensor], TFBaseModelOutputWithPoolingAndNoAttention]:






     """simple docstring"""







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

     __lowerCAmelCase  :			str					    =						self.resnet(
         pixel_values=lowerCAmelCase       ,							output_hidden_states=lowerCAmelCase       ,							return_dict=lowerCAmelCase       ,							training=lowerCAmelCase       ,							)
     return resnet_outputs






@add_start_docstrings(
    "\n    ResNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    "   ,							a_   ,							)
class SCREAMING_SNAKE_CASE	(  a_   ,							a_ ):
  """simple docstring"""






  def __init__(			self :    Dict       ,							lowerCAmelCase :    ResNetConfig       ,							**lowerCAmelCase :    str    )							->	None:






     """simple docstring"""







     super().__init__(lowerCAmelCase       ,							**lowerCAmelCase    )
     __lowerCAmelCase  :			List[str]					    =						config.num_labels
     __lowerCAmelCase  :			List[str]					    =						TFResNetMainLayer(lowerCAmelCase       ,							name="""resnet"""    )
     # classification head
     __lowerCAmelCase  :			Dict					    =						(
         tf.keras.layers.Dense(config.num_labels       ,							name="""classifier.1"""    )
         if config.num_labels > 0
         else tf.keras.layers.Activation("""linear"""       ,							name="""classifier.1"""    )
     )







  def        SCREAMING_SNAKE_CASE    (			self :    Dict       ,							lowerCAmelCase :    tf.Tensor    )							->	tf.Tensor:






     """simple docstring"""







     __lowerCAmelCase  :			List[str]					    =						tf.keras.layers.Flatten()(lowerCAmelCase    )
     __lowerCAmelCase  :			List[str]					    =						self.classifier_layer(lowerCAmelCase    )
     return logits







  @add_start_docstrings_to_model_forward(lowerCAmelCase    )
  @add_code_sample_docstrings(
      checkpoint=_IMAGE_CLASS_CHECKPOINT       ,							output_type=lowerCAmelCase       ,							config_class=_CONFIG_FOR_DOC       ,							expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT       ,							)
  @unpack_inputs
  def        SCREAMING_SNAKE_CASE    (			self :    Optional[Any]       ,							lowerCAmelCase :    tf.Tensor = None       ,							lowerCAmelCase :    tf.Tensor = None       ,							lowerCAmelCase :    bool = None       ,							lowerCAmelCase :    bool = None       ,							lowerCAmelCase :    bool = False       ,							)							->	Union[Tuple[tf.Tensor], TFImageClassifierOutputWithNoAttention]:






     """simple docstring"""







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

     __lowerCAmelCase  :			Tuple					    =						self.resnet(
         lowerCAmelCase       ,							output_hidden_states=lowerCAmelCase       ,							return_dict=lowerCAmelCase       ,							training=lowerCAmelCase    )

     __lowerCAmelCase  :			List[Any]					    =						outputs.pooler_output if return_dict else outputs[1]

     __lowerCAmelCase  :			Optional[Any]					    =						self.classifier(lowerCAmelCase    )

     __lowerCAmelCase  :			int					    =						None if labels is None else self.hf_compute_loss(lowerCAmelCase       ,							lowerCAmelCase    )

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

     return TFImageClassifierOutputWithNoAttention(loss=lowerCAmelCase       ,							logits=lowerCAmelCase       ,							hidden_states=outputs.hidden_states    )









"""simple docstring"""


from typing import TYPE_CHECKING

from ..utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available


lowerCamelCase__      =      {
    "configuration_utils": ["GenerationConfig"],
    "streamers": ["TextIteratorStreamer", "TextStreamer"],
}

try:
  if not is_torch_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowerCamelCase__      =      [
      "Constraint",
      "ConstraintListState",
      "DisjunctiveConstraint",
      "PhrasalConstraint",
  ]
  lowerCamelCase__      =      [
      "BeamHypotheses",
      "BeamScorer",
      "BeamSearchScorer",
      "ConstrainedBeamSearchScorer",
  ]
  lowerCamelCase__      =      [
      "EpsilonLogitsWarper",
      "EtaLogitsWarper",
      "ForcedBOSTokenLogitsProcessor",
      "ForcedEOSTokenLogitsProcessor",
      "HammingDiversityLogitsProcessor",
      "InfNanRemoveLogitsProcessor",
      "LogitsProcessor",
      "LogitsProcessorList",
      "LogitsWarper",
      "MinLengthLogitsProcessor",
      "MinNewTokensLengthLogitsProcessor",
      "NoBadWordsLogitsProcessor",
      "NoRepeatNGramLogitsProcessor",
      "PrefixConstrainedLogitsProcessor",
      "RepetitionPenaltyLogitsProcessor",
      "SequenceBiasLogitsProcessor",
      "EncoderRepetitionPenaltyLogitsProcessor",
      "TemperatureLogitsWarper",
      "TopKLogitsWarper",
      "TopPLogitsWarper",
      "TypicalLogitsWarper",
      "EncoderNoRepeatNGramLogitsProcessor",
      "ExponentialDecayLengthPenalty",
      "LogitNormalization",
  ]
  lowerCamelCase__      =      [
      "MaxNewTokensCriteria",
      "MaxLengthCriteria",
      "MaxTimeCriteria",
      "StoppingCriteria",
      "StoppingCriteriaList",
      "validate_stopping_criteria",
  ]
  lowerCamelCase__      =      [
      "GenerationMixin",
      "top_k_top_p_filtering",
      "GreedySearchEncoderDecoderOutput",
      "GreedySearchDecoderOnlyOutput",
      "SampleEncoderDecoderOutput",
      "SampleDecoderOnlyOutput",
      "BeamSearchEncoderDecoderOutput",
      "BeamSearchDecoderOnlyOutput",
      "BeamSampleEncoderDecoderOutput",
      "BeamSampleDecoderOnlyOutput",
      "ContrastiveSearchEncoderDecoderOutput",
      "ContrastiveSearchDecoderOnlyOutput",
  ]

try:
  if not is_tf_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowerCamelCase__      =      [
      "TFForcedBOSTokenLogitsProcessor",
      "TFForcedEOSTokenLogitsProcessor",
      "TFLogitsProcessor",
      "TFLogitsProcessorList",
      "TFLogitsWarper",
      "TFMinLengthLogitsProcessor",
      "TFNoBadWordsLogitsProcessor",
      "TFNoRepeatNGramLogitsProcessor",
      "TFRepetitionPenaltyLogitsProcessor",
      "TFTemperatureLogitsWarper",
      "TFTopKLogitsWarper",
      "TFTopPLogitsWarper",
      "TFForceTokensLogitsProcessor",
      "TFSuppressTokensAtBeginLogitsProcessor",
      "TFSuppressTokensLogitsProcessor",
  ]
  lowerCamelCase__      =      [
      "TFGenerationMixin",
      "tf_top_k_top_p_filtering",
      "TFGreedySearchDecoderOnlyOutput",
      "TFGreedySearchEncoderDecoderOutput",
      "TFSampleEncoderDecoderOutput",
      "TFSampleDecoderOnlyOutput",
      "TFBeamSearchEncoderDecoderOutput",
      "TFBeamSearchDecoderOnlyOutput",
      "TFBeamSampleEncoderDecoderOutput",
      "TFBeamSampleDecoderOnlyOutput",
      "TFContrastiveSearchEncoderDecoderOutput",
      "TFContrastiveSearchDecoderOnlyOutput",
  ]

try:
  if not is_flax_available():
    raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
  pass
else:
  lowerCamelCase__      =      [
      "FlaxForcedBOSTokenLogitsProcessor",
      "FlaxForcedEOSTokenLogitsProcessor",
      "FlaxLogitsProcessor",
      "FlaxLogitsProcessorList",
      "FlaxLogitsWarper",
      "FlaxMinLengthLogitsProcessor",
      "FlaxTemperatureLogitsWarper",
      "FlaxTopKLogitsWarper",
      "FlaxTopPLogitsWarper",
  ]
  lowerCamelCase__      =      [
      "FlaxGenerationMixin",
      "FlaxGreedySearchOutput",
      "FlaxSampleOutput",
      "FlaxBeamSearchOutput",
  ]

if TYPE_CHECKING:
  from .configuration_utils import GenerationConfig
  from .streamers import TextIteratorStreamer, TextStreamer

  try:
    if not is_torch_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .beam_constraints import Constraint, ConstraintListState, DisjunctiveConstraint, PhrasalConstraint
    from .beam_search import BeamHypotheses, BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer
    from .logits_process import (
        EncoderNoRepeatNGramLogitsProcessor,
        EncoderRepetitionPenaltyLogitsProcessor,
        EpsilonLogitsWarper,
        EtaLogitsWarper,
        ExponentialDecayLengthPenalty,
        ForcedBOSTokenLogitsProcessor,
        ForcedEOSTokenLogitsProcessor,
        HammingDiversityLogitsProcessor,
        InfNanRemoveLogitsProcessor,
        LogitNormalization,
        LogitsProcessor,
        LogitsProcessorList,
        LogitsWarper,
        MinLengthLogitsProcessor,
        MinNewTokensLengthLogitsProcessor,
        NoBadWordsLogitsProcessor,
        NoRepeatNGramLogitsProcessor,
        PrefixConstrainedLogitsProcessor,
        RepetitionPenaltyLogitsProcessor,
        SequenceBiasLogitsProcessor,
        TemperatureLogitsWarper,
        TopKLogitsWarper,
        TopPLogitsWarper,
        TypicalLogitsWarper,
    )
    from .stopping_criteria import (
        MaxLengthCriteria,
        MaxNewTokensCriteria,
        MaxTimeCriteria,
        StoppingCriteria,
        StoppingCriteriaList,
        validate_stopping_criteria,
    )
    from .utils import (
        BeamSampleDecoderOnlyOutput,
        BeamSampleEncoderDecoderOutput,
        BeamSearchDecoderOnlyOutput,
        BeamSearchEncoderDecoderOutput,
        ContrastiveSearchDecoderOnlyOutput,
        ContrastiveSearchEncoderDecoderOutput,
        GenerationMixin,
        GreedySearchDecoderOnlyOutput,
        GreedySearchEncoderDecoderOutput,
        SampleDecoderOnlyOutput,
        SampleEncoderDecoderOutput,
        top_k_top_p_filtering,
    )

  try:
    if not is_tf_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .tf_logits_process import (
        TFForcedBOSTokenLogitsProcessor,
        TFForcedEOSTokenLogitsProcessor,
        TFForceTokensLogitsProcessor,
        TFLogitsProcessor,
        TFLogitsProcessorList,
        TFLogitsWarper,
        TFMinLengthLogitsProcessor,
        TFNoBadWordsLogitsProcessor,
        TFNoRepeatNGramLogitsProcessor,
        TFRepetitionPenaltyLogitsProcessor,
        TFSuppressTokensAtBeginLogitsProcessor,
        TFSuppressTokensLogitsProcessor,
        TFTemperatureLogitsWarper,
        TFTopKLogitsWarper,
        TFTopPLogitsWarper,
    )
    from .tf_utils import (
        TFBeamSampleDecoderOnlyOutput,
        TFBeamSampleEncoderDecoderOutput,
        TFBeamSearchDecoderOnlyOutput,
        TFBeamSearchEncoderDecoderOutput,
        TFContrastiveSearchDecoderOnlyOutput,
        TFContrastiveSearchEncoderDecoderOutput,
        TFGenerationMixin,
        TFGreedySearchDecoderOnlyOutput,
        TFGreedySearchEncoderDecoderOutput,
        TFSampleDecoderOnlyOutput,
        TFSampleEncoderDecoderOutput,
        tf_top_k_top_p_filtering,
    )

  try:
    if not is_flax_available():
      raise OptionalDependencyNotAvailable()
  except OptionalDependencyNotAvailable:
    pass
  else:
    from .flax_logits_process import (
        FlaxForcedBOSTokenLogitsProcessor,
        FlaxForcedEOSTokenLogitsProcessor,
        FlaxLogitsProcessor,
        FlaxLogitsProcessorList,
        FlaxLogitsWarper,
        FlaxMinLengthLogitsProcessor,
        FlaxTemperatureLogitsWarper,
        FlaxTopKLogitsWarper,
        FlaxTopPLogitsWarper,
    )
    from .flax_utils import FlaxBeamSearchOutput, FlaxGenerationMixin, FlaxGreedySearchOutput, FlaxSampleOutput
else:
  import sys

  lowerCamelCase__      =      _LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)
