



from __future__ import annotations

import unittest

from transformers import OpenAIGPTConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import tensorflow as tf

      from transformers.models.openai.modeling_tf_openai import (
          TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
          TFOpenAIGPTDoubleHeadsModel,
          TFOpenAIGPTForSequenceClassification,
          TFOpenAIGPTLMHeadModel,
          TFOpenAIGPTModel,
      )







class       _snake_case				:






   '''simple docstring'''






   def __init__(    self:     Union[str, Any]  ,lowerCamelCase_:     Union[str, Any]  ,)	->      Optional[Any]:
       UpperCAmelCase_     :       List[str]  		=					parent
       UpperCAmelCase_     :       Optional[int]  		=					13
       UpperCAmelCase_     :       Union[str, Any]  		=					7
       UpperCAmelCase_     :       Tuple  		=					True
       UpperCAmelCase_     :       Union[str, Any]  		=					True
       UpperCAmelCase_     :       List[str]  		=					True
       UpperCAmelCase_     :       Optional[Any]  		=					True
       UpperCAmelCase_     :       str  		=					True
       UpperCAmelCase_     :       Union[str, Any]  		=					99
       UpperCAmelCase_     :       List[str]  		=					32
       UpperCAmelCase_     :       int  		=					2
       UpperCAmelCase_     :       Optional[int]  		=					4
       UpperCAmelCase_     :       Dict  		=					37
       UpperCAmelCase_     :       Any  		=					"""gelu"""
       UpperCAmelCase_     :       str  		=					0.1
       UpperCAmelCase_     :       int  		=					0.1
       UpperCAmelCase_     :       List[str]  		=					512
       UpperCAmelCase_     :       List[str]  		=					16
       UpperCAmelCase_     :       List[str]  		=					2
       UpperCAmelCase_     :       Union[str, Any]  		=					0.0_2
       UpperCAmelCase_     :       Union[str, Any]  		=					3
       UpperCAmelCase_     :       Optional[Any]  		=					4
       UpperCAmelCase_     :       Tuple  		=					None
       UpperCAmelCase_     :       Union[str, Any]  		=					self.vocab_size - 1


   def       A__    (    self:     Tuple							)	->      Dict:
       UpperCAmelCase_     :       Optional[int]  		=					ids_tensor([self.batch_size, self.seq_length]  ,self.vocab_size							)

       UpperCAmelCase_     :       str  		=					None
       if self.use_input_mask:
           UpperCAmelCase_     :       str  		=					random_attention_mask([self.batch_size, self.seq_length]							)

       UpperCAmelCase_     :       Any  		=					None
       if self.use_token_type_ids:
           UpperCAmelCase_     :       List[Any]  		=					ids_tensor([self.batch_size, self.seq_length]  ,self.type_vocab_size							)

       UpperCAmelCase_     :       List[str]  		=					None
       if self.use_mc_token_ids:
           UpperCAmelCase_     :       Tuple  		=					ids_tensor([self.batch_size, self.num_choices]  ,self.seq_length							)

       UpperCAmelCase_     :       Tuple  		=					None
       UpperCAmelCase_     :       str  		=					None
       UpperCAmelCase_     :       int  		=					None
       if self.use_labels:
           UpperCAmelCase_     :       List[str]  		=					ids_tensor([self.batch_size]  ,self.type_sequence_label_size							)
           UpperCAmelCase_     :       Dict  		=					ids_tensor([self.batch_size, self.seq_length]  ,self.num_labels							)
           UpperCAmelCase_     :       Union[str, Any]  		=					ids_tensor([self.batch_size]  ,self.num_choices							)

       UpperCAmelCase_     :       Union[str, Any]  		=					OpenAIGPTConfig(
           vocab_size=self.vocab_size  ,n_embd=self.hidden_size  ,n_layer=self.num_hidden_layers  ,n_head=self.num_attention_heads  ,n_positions=self.max_position_embeddings  ,pad_token_id=self.pad_token_id  ,)

       UpperCAmelCase_     :       List[Any]  		=					ids_tensor([self.num_hidden_layers, self.num_attention_heads]  ,2							)

       return (
           config,
           input_ids,
           input_mask,
           head_mask,
           token_type_ids,
           mc_token_ids,
           sequence_labels,
           token_labels,
           choice_labels,
       )


   def       A__    (    self:     str  ,lowerCamelCase_:     int  ,lowerCamelCase_:     str  ,lowerCamelCase_:     Any  ,lowerCamelCase_:     Optional[int]  ,lowerCamelCase_:     Union[str, Any]  ,*lowerCamelCase_:     Dict							)	->      int:
       UpperCAmelCase_     :       Dict  		=					TFOpenAIGPTModel(config=lowerCamelCase_							)
       UpperCAmelCase_     :       Optional[int]  		=					{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
       UpperCAmelCase_     :       Optional[Any]  		=					model(lowerCamelCase_							)

       UpperCAmelCase_     :       Any  		=					[input_ids, input_mask]
       UpperCAmelCase_     :       int  		=					model(lowerCamelCase_							)

       UpperCAmelCase_     :       List[str]  		=					model(lowerCamelCase_							)

       self.parent.assertEqual(result.last_hidden_state.shape  ,(self.batch_size, self.seq_length, self.hidden_size)							)


   def       A__    (    self:     Any  ,lowerCamelCase_:     Optional[Any]  ,lowerCamelCase_:     int  ,lowerCamelCase_:     str  ,lowerCamelCase_:     Union[str, Any]  ,lowerCamelCase_:     str  ,*lowerCamelCase_:     Dict							)	->      List[Any]:
       UpperCAmelCase_     :       Optional[Any]  		=					TFOpenAIGPTLMHeadModel(config=lowerCamelCase_							)
       UpperCAmelCase_     :       Optional[Any]  		=					{"""input_ids""": input_ids, """attention_mask""": input_mask, """token_type_ids""": token_type_ids}
       UpperCAmelCase_     :       Union[str, Any]  		=					model(lowerCamelCase_							)
       self.parent.assertEqual(result.logits.shape  ,(self.batch_size, self.seq_length, self.vocab_size)							)


   def       A__    (    self:     str  ,lowerCamelCase_:     Any  ,lowerCamelCase_:     Optional[Any]  ,lowerCamelCase_:     Tuple  ,lowerCamelCase_:     Optional[Any]  ,lowerCamelCase_:     List[str]  ,lowerCamelCase_:     int  ,*lowerCamelCase_:     str							)	->      int:
       UpperCAmelCase_     :       List[Any]  		=					TFOpenAIGPTDoubleHeadsModel(config=lowerCamelCase_							)

       UpperCAmelCase_     :       str  		=					tf.tile(tf.expand_dims(lowerCamelCase_  ,1							)  ,(1, self.num_choices, 1)							)
       UpperCAmelCase_     :       int  		=					tf.tile(tf.expand_dims(lowerCamelCase_  ,1							)  ,(1, self.num_choices, 1)							)
       UpperCAmelCase_     :       Tuple  		=					tf.tile(tf.expand_dims(lowerCamelCase_  ,1							)  ,(1, self.num_choices, 1)							)

       UpperCAmelCase_     :       Any  		=					{
           """input_ids""": multiple_choice_inputs_ids,
           """mc_token_ids""": mc_token_ids,
           """attention_mask""": multiple_choice_input_mask,
           """token_type_ids""": multiple_choice_token_type_ids,
       }
       UpperCAmelCase_     :       int  		=					model(lowerCamelCase_							)
       self.parent.assertEqual(
           result.logits.shape  ,(self.batch_size, self.num_choices, self.seq_length, self.vocab_size)							)
       self.parent.assertEqual(result.mc_logits.shape  ,(self.batch_size, self.num_choices)							)


   def       A__    (    self:     List[Any]  ,lowerCamelCase_:     Tuple  ,lowerCamelCase_:     int  ,lowerCamelCase_:     Tuple  ,lowerCamelCase_:     int  ,lowerCamelCase_:     Union[str, Any]  ,*lowerCamelCase_:     Dict							)	->      Union[str, Any]:
       UpperCAmelCase_     :       Union[str, Any]  		=					self.num_labels
       UpperCAmelCase_     :       str  		=					ids_tensor([self.batch_size]  ,self.type_sequence_label_size							)
       UpperCAmelCase_     :       List[Any]  		=					{
           """input_ids""": input_ids,
           """attention_mask""": input_mask,
           """token_type_ids""": token_type_ids,
           """labels""": sequence_labels,
       }
       UpperCAmelCase_     :       int  		=					TFOpenAIGPTForSequenceClassification(lowerCamelCase_							)
       UpperCAmelCase_     :       str  		=					model(lowerCamelCase_							)
       self.parent.assertEqual(result.logits.shape  ,(self.batch_size, self.num_labels)							)






   def       A__    (    self:     Dict							)	->      Optional[Any]:
       UpperCAmelCase_     :       Dict  		=					self.prepare_config_and_inputs()

       (
           (
           UpperCAmelCase_
       )		, (
           UpperCAmelCase_
       )		, (
           UpperCAmelCase_
       )		, (
           UpperCAmelCase_
       )		, (
           UpperCAmelCase_
       )		, (
           UpperCAmelCase_
       )		, (
           UpperCAmelCase_
       )		, (
           UpperCAmelCase_
       )		, (
           UpperCAmelCase_
       )		, 
       )     :       List[Any]  		=					config_and_inputs

       UpperCAmelCase_     :       Union[str, Any]  		=					{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": input_mask}
       return config, inputs_dict







@require_tf
class       _snake_case				(     __snake_case ,							__snake_case ,							unittest.TestCase ):






   '''simple docstring'''






   A__      : List[Any]       =						(
       (TFOpenAIGPTModel, TFOpenAIGPTLMHeadModel, TFOpenAIGPTDoubleHeadsModel, TFOpenAIGPTForSequenceClassification)
       if is_tf_available()
       else ()
   )
   A__      : List[Any]       =						(
       (TFOpenAIGPTLMHeadModel,) if is_tf_available() else ()
   )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
   A__      : int       =						(
       {
           "feature-extraction": TFOpenAIGPTModel,
           "text-classification": TFOpenAIGPTForSequenceClassification,
           "text-generation": TFOpenAIGPTLMHeadModel,
           "zero-shot": TFOpenAIGPTForSequenceClassification,
       }
       if is_tf_available()
       else {}
   )
   A__      : List[Any]       =						False
   A__      : Union[str, Any]       =						False


   def       A__    (    self:     str  ,lowerCamelCase_:     Optional[int]  ,lowerCamelCase_:     Union[str, Any]  ,lowerCamelCase_:     Union[str, Any]  ,lowerCamelCase_:     Union[str, Any]  ,lowerCamelCase_:     Tuple							)	->      Tuple:
       if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
           # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
           # `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
           # tiny config could not be created.
           return True

       return False


   def       A__    (    self:     Dict							)	->      str:
       UpperCAmelCase_     :       Any  		=					TFOpenAIGPTModelTester(self							)
       UpperCAmelCase_     :       List[Any]  		=					ConfigTester(self  ,config_class=lowerCamelCase_  ,n_embd=37							)


   def       A__    (    self:     List[Any]							)	->      Union[str, Any]:
       self.config_tester.run_common_tests()


   def       A__    (    self:     int							)	->      Union[str, Any]:
       UpperCAmelCase_     :       Union[str, Any]  		=					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_openai_gpt_model(*lowerCamelCase_							)


   def       A__    (    self:     int							)	->      Tuple:
       UpperCAmelCase_     :       Any  		=					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_openai_gpt_lm_head(*lowerCamelCase_							)


   def       A__    (    self:     Union[str, Any]							)	->      int:
       UpperCAmelCase_     :       Dict  		=					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_openai_gpt_double_head(*lowerCamelCase_							)


   def       A__    (    self:     List[str]							)	->      Optional[Any]:
       UpperCAmelCase_     :       Optional[int]  		=					self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*lowerCamelCase_							)






   @slow
   def       A__    (    self:     List[str]							)	->      str:
       for model_name in TF_OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
           UpperCAmelCase_     :       str  		=					TFOpenAIGPTModel.from_pretrained(lowerCamelCase_							)
           self.assertIsNotNone(lowerCamelCase_							)







@require_tf
class       _snake_case				(     unittest.TestCase ):






   '''simple docstring'''






   @slow
   def       A__    (    self:     Dict							)	->      List[str]:
       UpperCAmelCase_     :       int  		=					TFOpenAIGPTLMHeadModel.from_pretrained("""openai-gpt"""							)
       UpperCAmelCase_     :       List[str]  		=					tf.convert_to_tensor([[481, 4735, 544]]  ,dtype=tf.intaa							)  # the president is
       UpperCAmelCase_     :       Union[str, Any]  		=					[
           481,
           4735,
           544,
           246,
           963,
           870,
           762,
           239,
           244,
           40477,
           244,
           249,
           719,
           881,
           487,
           544,
           240,
           244,
           603,
           481,
       ]  # the president is a very good man. " \n " i\'m sure he is, " said the

       UpperCAmelCase_     :       int  		=					model.generate(lowerCamelCase_  ,do_sample=lowerCamelCase_							)
       self.assertListEqual(output_ids[0].numpy().tolist()  ,lowerCamelCase_							)








'''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)