



from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
from .modeling_utils import ModelMixin
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block



@dataclass
class 		_lowercase		(							UpperCamelCase_						):
   _UpperCAmelCase  						=      42



class 		_lowercase		(							UpperCamelCase_, UpperCamelCase_						):

   @register_to_config
   def __init__(   self      :							List[str]				, __lowerCAmelCase      :							Union[str, Any] = None				, __lowerCAmelCase      :							Tuple = 3				, __lowerCAmelCase      :							Any = 3				, __lowerCAmelCase      :							Optional[Any] = False				, __lowerCAmelCase      :							Tuple = "positional"				, __lowerCAmelCase      :							List[Any] = 0				, __lowerCAmelCase      :							Union[str, Any] = True				, __lowerCAmelCase      :							Any = ("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D")				, __lowerCAmelCase      :							Dict = ("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D")				, __lowerCAmelCase      :							Tuple = (224, 448, 672, 896)				, __lowerCAmelCase      :							List[Any] = 2				, __lowerCAmelCase      :							Tuple = 1				, __lowerCAmelCase      :							List[str] = 1				, __lowerCAmelCase      :							int = "conv"				, __lowerCAmelCase      :							List[str] = "conv"				, __lowerCAmelCase      :							Any = "silu"				, __lowerCAmelCase      :							Any = 8				, __lowerCAmelCase      :							str = 32				, __lowerCAmelCase      :							Union[str, Any] = 1E-5				, __lowerCAmelCase      :							Any = "default"				, __lowerCAmelCase      :							Any = True				, __lowerCAmelCase      :							List[Any] = None				, __lowerCAmelCase      :							int = None				, )							->					List[str]:


    """simple docstring"""






    super().__init__()

    a							=		sample_size
    a							=		block_out_channels[0] * 4

    # Check inputs
    if len(__a				) != len(__a				):
     raise ValueError(
         f"""Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}."""				)

    if len(__a				) != len(__a				):
     raise ValueError(
         f"""Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."""				)

    # input
    a							=		nn.Convad(__a				, block_out_channels[0]				, kernel_size=3				, padding=(1, 1)				)

    # time
    if time_embedding_type == "fourier":
     a							=		GaussianFourierProjection(embedding_size=block_out_channels[0]				, scale=16				)
     a							=		2 * block_out_channels[0]
    elif time_embedding_type == "positional":
     a							=		Timesteps(block_out_channels[0]				, __a				, __a				)
     a							=		block_out_channels[0]

    a							=		TimestepEmbedding(__a				, __a				)

    # class embedding
    if class_embed_type is None and num_class_embeds is not None:
     a							=		nn.Embedding(__a				, __a				)
    elif class_embed_type == "timestep":
     a							=		TimestepEmbedding(__a				, __a				)
    elif class_embed_type == "identity":
     a							=		nn.Identity(__a				, __a				)
    else:
     a							=		None

    a							=		nn.ModuleList([]				)
    a							=		None
    a							=		nn.ModuleList([]				)

    # down
    a							=		block_out_channels[0]
    for i, down_block_type in enumerate(__a				):
     a							=		output_channel
     a							=		block_out_channels[i]
     a							=		i == len(__a				) - 1

     a							=		get_down_block(
         __a				, num_layers=__a				, in_channels=__a				, out_channels=__a				, temb_channels=__a				, add_downsample=not is_final_block				, resnet_eps=__a				, resnet_act_fn=__a				, resnet_groups=__a				, attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel				, downsample_padding=__a				, resnet_time_scale_shift=__a				, downsample_type=__a				, )
     self.down_blocks.append(__a				)

    # mid
    a							=		UNetMidBlockaD(
        in_channels=block_out_channels[-1]				, temb_channels=__a				, resnet_eps=__a				, resnet_act_fn=__a				, output_scale_factor=__a				, resnet_time_scale_shift=__a				, attention_head_dim=attention_head_dim if attention_head_dim is not None else block_out_channels[-1]				, resnet_groups=__a				, add_attention=__a				, )

    # up
    a							=		list(reversed(__a				)				)
    a							=		reversed_block_out_channels[0]
    for i, up_block_type in enumerate(__a				):
     a							=		output_channel
     a							=		reversed_block_out_channels[i]
     a							=		reversed_block_out_channels[min(i + 1				, len(__a				) - 1				)]

     a							=		i == len(__a				) - 1

     a							=		get_up_block(
         __a				, num_layers=layers_per_block + 1				, in_channels=__a				, out_channels=__a				, prev_output_channel=__a				, temb_channels=__a				, add_upsample=not is_final_block				, resnet_eps=__a				, resnet_act_fn=__a				, resnet_groups=__a				, attention_head_dim=attention_head_dim if attention_head_dim is not None else output_channel				, resnet_time_scale_shift=__a				, upsample_type=__a				, )
     self.up_blocks.append(__a				)
     a							=		output_channel

    # out
    a							=		norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4				, 32				)
    a							=		nn.GroupNorm(num_channels=block_out_channels[0]				, num_groups=__a				, eps=__a				)
    a							=		nn.SiLU()
    a							=		nn.Convad(block_out_channels[0]				, __a				, kernel_size=3				, padding=1				)




   def 		A				(   self      :							int				, __lowerCAmelCase      :							Any				, __lowerCAmelCase      :							Union[str, Any]				, __lowerCAmelCase      :							List[Any] = None				, __lowerCAmelCase      :							Optional[Any] = True				, )							->					Union[UNetaDOutput, Tuple]:


    """simple docstring"""






    if self.config.center_input_sample:
     a							=		2 * sample - 1.0

    # 1. time
    a							=		timestep
    if not torch.is_tensor(__a				):
     a							=		torch.tensor([timesteps]				, dtype=torch.long				, device=sample.device				)
    elif torch.is_tensor(__a				) and len(timesteps.shape				) == 0:
     a							=		timesteps[None].to(sample.device				)

    # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
    a							=		timesteps * torch.ones(sample.shape[0]				, dtype=timesteps.dtype				, device=timesteps.device				)

    a							=		self.time_proj(__a				)

    # timesteps does not contain any weights and will always return f32 tensors
    # but time_embedding might actually be running in fp16. so we need to cast here.
    # there might be better ways to encapsulate this.
    a							=		t_emb.to(dtype=self.dtype				)
    a							=		self.time_embedding(__a				)

    if self.class_embedding is not None:
     if class_labels is None:
      raise ValueError("class_labels should be provided when doing class conditioning"				)

     if self.config.class_embed_type == "timestep":
      a							=		self.time_proj(__a				)

     a							=		self.class_embedding(__a				).to(dtype=self.dtype				)
     a							=		emb + class_emb

    # 2. pre-process
    a							=		sample
    a							=		self.conv_in(__a				)

    # 3. down
    a							=		(sample,)
    for downsample_block in self.down_blocks:
     if hasattr(__a				, "skip_conv"				):
      a							=		downsample_block(
          hidden_states=__a				, temb=__a				, skip_sample=__a				)
     else:
      a							=		downsample_block(hidden_states=__a				, temb=__a				)

     down_block_res_samples += res_samples

    # 4. mid
    a							=		self.mid_block(__a				, __a				)

    # 5. up
    a							=		None
    for upsample_block in self.up_blocks:
     a							=		down_block_res_samples[-len(upsample_block.resnets				) :]
     a							=		down_block_res_samples[: -len(upsample_block.resnets				)]

     if hasattr(__a				, "skip_conv"				):
      a							=		upsample_block(__a				, __a				, __a				, __a				)
     else:
      a							=		upsample_block(__a				, __a				, __a				)

        # 6. post-process
    a							=		self.conv_norm_out(__a				)
    a							=		self.conv_act(__a				)
    a							=		self.conv_out(__a				)

    if skip_sample is not None:
     sample += skip_sample

    if self.config.time_embedding_type == "fourier":
     a							=		timesteps.reshape((sample.shape[0], *([1] * len(sample.shape[1:]				)))				)
     a							=		sample / timesteps

    if not return_dict:
     return (sample,)

    return UNetaDOutput(sample=__a				)









'''simple docstring'''






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


__A     						= logging.get_logger(__name__)

# General docstring
__A     						= '''ResNetConfig'''

# Base docstring
__A     						= '''microsoft/resnet-50'''
__A     						= [1, 2_0_4_8, 7, 7]

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

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




class a_     (     tf.keras.layers.Layer				):







   def __init__(self       , __a       , __a = 3       , __a = 1       , __a = "relu"       , **__a)      ->   None:
      """simple docstring"""






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







   def      SCREAMING_SNAKE_CASE__       (self       , __a)      ->   tf.Tensor:
      """simple docstring"""






      __snake_case					:   Union[str, Any]  				=			(self.pad_value, self.pad_value)
      __snake_case					:   int  				=			tf.pad(__a       , [(0, 0), height_pad, width_pad, (0, 0)])
      __snake_case					:   Any  				=			self.conv(__a)
      return hidden_state







   def      SCREAMING_SNAKE_CASE__       (self       , __a       , __a = False)      ->   tf.Tensor:
      """simple docstring"""






      __snake_case					:   List[Any]  				=			self.convolution(__a)
      __snake_case					:   Tuple  				=			self.normalization(__a       , training=__a)
      __snake_case					:   Union[str, Any]  				=			self.activation(__a)
      return hidden_state




class a_     (     tf.keras.layers.Layer				):







   def __init__(self       , __a       , **__a)      ->   None:
      """simple docstring"""






      super().__init__(**__a)
      __snake_case					:   Any  				=			TFResNetConvLayer(
          config.embedding_size       , kernel_size=7       , stride=2       , activation=config.hidden_act       , name='embedder'       , )
      __snake_case					:   Optional[Any]  				=			tf.keras.layers.MaxPoolaD(pool_size=3       , strides=2       , padding='valid'       , name='pooler')
      __snake_case					:   Any  				=			config.num_channels







   def      SCREAMING_SNAKE_CASE__       (self       , __a       , __a = False)      ->   tf.Tensor:
      """simple docstring"""






      __snake_case				,__snake_case				,__snake_case				,__snake_case					:   Dict  				=			shape_list(__a)
      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.')
      __snake_case					:   Optional[int]  				=			pixel_values
      __snake_case					:   int  				=			self.embedder(__a)
      __snake_case					:   Any  				=			tf.pad(__a       , [[0, 0], [1, 1], [1, 1], [0, 0]])
      __snake_case					:   Tuple  				=			self.pooler(__a)
      return hidden_state




class a_     (     tf.keras.layers.Layer				):







   def __init__(self       , __a       , __a = 2       , **__a)      ->   None:
      """simple docstring"""






      super().__init__(**__a)
      __snake_case					:   List[str]  				=			tf.keras.layers.ConvaD(
          __a       , kernel_size=1       , strides=__a       , use_bias=__a       , name='convolution')
      # Use same default momentum and epsilon as PyTorch equivalent
      __snake_case					:   Dict  				=			tf.keras.layers.BatchNormalization(epsilon=1E-5       , momentum=0.9       , name='normalization')







   def      SCREAMING_SNAKE_CASE__       (self       , __a       , __a = False)      ->   tf.Tensor:
      """simple docstring"""






      __snake_case					:   List[Any]  				=			x
      __snake_case					:   int  				=			self.convolution(__a)
      __snake_case					:   Tuple  				=			self.normalization(__a       , training=__a)
      return hidden_state




class a_     (     tf.keras.layers.Layer				):







   def __init__(self       , __a       , __a       , __a = 1       , __a = "relu"       , **__a)      ->   None:
      """simple docstring"""






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







   def      SCREAMING_SNAKE_CASE__       (self       , __a       , __a = False)      ->   tf.Tensor:
      """simple docstring"""






      __snake_case					:   Dict  				=			hidden_state
      __snake_case					:   List[str]  				=			self.conva(__a       , training=__a)
      __snake_case					:   List[str]  				=			self.conva(__a       , training=__a)
      __snake_case					:   str  				=			self.shortcut(__a       , training=__a)
      hidden_state += residual
      __snake_case					:   List[Any]  				=			self.activation(__a)
      return hidden_state




class a_     (     tf.keras.layers.Layer				):







   def __init__(self       , __a       , __a       , __a = 1       , __a = "relu"       , __a = 4       , **__a       , )      ->   None:
      """simple docstring"""






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







   def      SCREAMING_SNAKE_CASE__       (self       , __a       , __a = False)      ->   tf.Tensor:
      """simple docstring"""






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




class a_     (     tf.keras.layers.Layer				):







   def __init__(self       , __a       , __a       , __a       , __a = 2       , __a = 2       , **__a)      ->   None:
      """simple docstring"""






      super().__init__(**__a)

      __snake_case					:   List[Any]  				=			TFResNetBottleNeckLayer if config.layer_type == 'bottleneck' else TFResNetBasicLayer

      __snake_case					:   int  				=			[layer(__a       , __a       , stride=__a       , activation=config.hidden_act       , name='layers.0')]
      layers += [
          layer(__a       , __a       , activation=config.hidden_act       , name=F"""layers.{i + 1}""")
          for i in range(depth - 1)
      ]
      __snake_case					:   Optional[int]  				=			layers







   def      SCREAMING_SNAKE_CASE__       (self       , __a       , __a = False)      ->   tf.Tensor:
      """simple docstring"""






      for layer in self.stage_layers:
         __snake_case					:   Tuple  				=			layer(__a       , training=__a)
      return hidden_state




class a_     (     tf.keras.layers.Layer				):







   def __init__(self       , __a       , **__a)      ->   None:
      """simple docstring"""






      super().__init__(**__a)
      # based on `downsample_in_first_stage` the first layer of the first stage may or may not downsample the input
      __snake_case					:   str  				=			[
          TFResNetStage(
              __a       , 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(__a       , __a       , __a       , depth=__a       , name=F"""stages.{i + 1}"""))







   def      SCREAMING_SNAKE_CASE__       (self       , __a       , __a = False       , __a = True       , __a = False       , )      ->   TFBaseModelOutputWithNoAttention:
      """simple docstring"""






      __snake_case					:   Dict  				=			() if output_hidden_states else None

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

         __snake_case					:   Union[str, Any]  				=			stage_module(__a       , training=__a)

      if output_hidden_states:
         __snake_case					:   Dict  				=			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=__a       , hidden_states=__a)




class a_     (     UpperCamelCase_				):
   _snake_case	   =				ResNetConfig
   _snake_case	   =				"""resnet"""
   _snake_case	   =				"""pixel_values"""







   @property
   def      SCREAMING_SNAKE_CASE__       (self)      ->   List[Any]:
      """simple docstring"""






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


__A     						= 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.
'''


__A     						= 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 a_     (     tf.keras.layers.Layer				):
   _snake_case	   =				ResNetConfig







   def __init__(self       , __a       , **__a)      ->   None:
      """simple docstring"""






      super().__init__(**__a)
      __snake_case					:   Tuple  				=			config
      __snake_case					:   Dict  				=			TFResNetEmbeddings(__a       , name='embedder')
      __snake_case					:   Union[str, Any]  				=			TFResNetEncoder(__a       , name='encoder')
      __snake_case					:   int  				=			tf.keras.layers.GlobalAveragePoolingaD(keepdims=__a)







   @unpack_inputs
   def      SCREAMING_SNAKE_CASE__       (self       , __a       , __a = None       , __a = None       , __a = False       , )      ->   Union[Tuple[tf.Tensor], TFBaseModelOutputWithPoolingAndNoAttention]:
      """simple docstring"""






      __snake_case					:   Union[str, Any]  				=			(
          output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
      )
      __snake_case					:   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)
      __snake_case					:   Optional[Any]  				=			tf.transpose(__a       , perm=[0, 2, 3, 1])
      __snake_case					:   Union[str, Any]  				=			self.embedder(__a       , training=__a)

      __snake_case					:   Any  				=			self.encoder(
          __a       , output_hidden_states=__a       , return_dict=__a       , training=__a)

      __snake_case					:   Optional[Any]  				=			encoder_outputs[0]

      __snake_case					:   Any  				=			self.pooler(__a)

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

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

      __snake_case					:   Union[str, Any]  				=			hidden_states if output_hidden_states else None

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




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







   def __init__(self       , __a       , **__a)      ->   None:
      """simple docstring"""






      super().__init__(__a       , **__a)
      __snake_case					:   Union[str, Any]  				=			TFResNetMainLayer(config=__a       , name='resnet')







   @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       , )
   @unpack_inputs
   def      SCREAMING_SNAKE_CASE__       (self       , __a       , __a = None       , __a = None       , __a = False       , )      ->   Union[Tuple[tf.Tensor], TFBaseModelOutputWithPoolingAndNoAttention]:
      """simple docstring"""






      __snake_case					:   Optional[Any]  				=			(
          output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
      )
      __snake_case					:   Optional[int]  				=			return_dict if return_dict is not None else self.config.use_return_dict

      __snake_case					:   int  				=			self.resnet(
          pixel_values=__a       , output_hidden_states=__a       , return_dict=__a       , training=__a       , )
      return resnet_outputs




@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.
    """		,   UpperCamelCase_		,   )
class a_     (     UpperCamelCase_		,   UpperCamelCase_				):







   def __init__(self       , __a       , **__a)      ->   None:
      """simple docstring"""






      super().__init__(__a       , **__a)
      __snake_case					:   Union[str, Any]  				=			config.num_labels
      __snake_case					:   List[str]  				=			TFResNetMainLayer(__a       , name='resnet')
      # classification head
      __snake_case					:   Tuple  				=			(
          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       , __a)      ->   tf.Tensor:
      """simple docstring"""






      __snake_case					:   Dict  				=			tf.keras.layers.Flatten()(__a)
      __snake_case					:   str  				=			self.classifier_layer(__a)
      return logits







   @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       , )
   @unpack_inputs
   def      SCREAMING_SNAKE_CASE__       (self       , __a = None       , __a = None       , __a = None       , __a = None       , __a = False       , )      ->   Union[Tuple[tf.Tensor], TFImageClassifierOutputWithNoAttention]:
      """simple docstring"""






      __snake_case					:   Dict  				=			return_dict if return_dict is not None else self.config.use_return_dict

      __snake_case					:   Optional[int]  				=			self.resnet(
          __a       , output_hidden_states=__a       , return_dict=__a       , training=__a)

      __snake_case					:   Union[str, Any]  				=			outputs.pooler_output if return_dict else outputs[1]

      __snake_case					:   Optional[Any]  				=			self.classifier(__a)

      __snake_case					:   List[str]  				=			None if labels is None else self.hf_compute_loss(__a       , __a)

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

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