






'''simple docstring'''






import argparse
import glob
import inspect
import os
import re
import unittest

from get_test_info import get_test_classes

from tests.test_pipeline_mixin import pipeline_test_mapping


__A     						= {}
for task, _ in pipeline_test_mapping.items():
      __A     						= {'''pt''': None, '''tf''': None}


# DO **NOT** add item to this set (unless the reason is approved)
__A     						= {
    '''tests/models/esm/test_modeling_esmfold.py''',  # The pipeline test mapping is added to `test_modeling_esm.py`
}




def 							_SCREAMING_SNAKE_CASE	(					A	:							Optional[int]	)     ->			Union[str, Any]:







   """simple docstring"""

   if "ModelTesterMixin" in [x.__name__ for x in test_class.__bases__]:
      return "pt"
   elif "TFModelTesterMixin" in [x.__name__ for x in test_class.__bases__]:
      return "tf"
   elif "FlaxModelTesterMixin" in [x.__name__ for x in test_class.__bases__]:
      return "flax"
   else:
      return None




def 							_SCREAMING_SNAKE_CASE	(					A	:							Optional[int]	,		A	:							Union[str, Any]	)     ->			Optional[int]:







   """simple docstring"""
   # Use the cached results
   if PIPELINE_TEST_MAPPING[task].get(A	,		A	) is not None:
      return PIPELINE_TEST_MAPPING[task][framework]

   __snake_case					:   Optional[Any]  				=			pipeline_test_mapping[task]['test']
   __snake_case					:   Dict  				=			None

   if framework == "pt":
      __snake_case					:   Tuple  				=			getattr(A	,		'model_mapping'	,		A	)
   elif framework == "tf":
      __snake_case					:   str  				=			getattr(A	,		'tf_model_mapping'	,		A	)

   if mapping is not None:
      __snake_case					:   Dict  				=			dict(mapping.items()	)

   # cache the results
   __snake_case					:   List[str]  				=			mapping
   return mapping




def 							_SCREAMING_SNAKE_CASE	(					A	:							str	,		A	:							Union[str, Any]	)     ->			List[Any]:







   """simple docstring"""
   __snake_case					:   Dict  				=			get_framework(A	)
   if framework is None:
      return None
   __snake_case					:   int  				=			get_mapping_for_task(A	,		A	)
   if mapping is None:
      return None

   __snake_case					:   List[str]  				=			list({model_class.config_class for model_class in test_class.all_model_classes}	)
   if len(A	) != 1:
      raise ValueError('There should be exactly one configuration class from `test_class.all_model_classes`.'	)

   # This could be a list/tuple of model classes, but it's rare.
   __snake_case					:   Optional[int]  				=			mapping.get(config_classes[0]	,		A	)
   if isinstance(A	,		(tuple, list)	):
      __snake_case					:   Dict  				=			sorted(A	,		key=lambda A	: x.__name__	)

   return model_class




def 							_SCREAMING_SNAKE_CASE	(					A	:							Union[str, Any]	)     ->			Any:







   """simple docstring"""
   __snake_case					:   Tuple  				=			[(task, get_model_for_pipeline_test(A	,		A	)) for task in pipeline_test_mapping]
   __snake_case					:   Union[str, Any]  				=			sorted([(task, model) for task, model in mapping if model is not None]	,		key=lambda A	: x[0]	)

   return dict(A	)




def 							_SCREAMING_SNAKE_CASE	(					A	:							Dict	)     ->			Optional[int]:







   """simple docstring"""
   __snake_case					:   int  				=			get_framework(A	)
   if framework == "pt":
      __snake_case					:   Tuple  				=			'torch'
   __snake_case					:   List[str]  				=			'{}'

   __snake_case					:   List[str]  				=			get_pipeline_model_mapping(A	)
   if len(A	) == 0:
      return ""

   __snake_case					:   str  				=			[]
   for task, model_classes in mapping.items():
      if isinstance(A	,		(tuple, list)	):
         # A list/tuple of model classes
         __snake_case					:   Optional[int]  				=			'(' + ', '.join([x.__name__ for x in model_classes]	) + ')'
      else:
         # A single model class
         __snake_case					:   Optional[Any]  				=			model_classes.__name__
      texts.append(F"""\"{task}\": {value}"""	)
   __snake_case					:   Tuple  				=			'{' + ', '.join(A	) + '}'
   __snake_case					:   str  				=			F"""pipeline_model_mapping = {text} if is_{framework}_available() else {default_value}"""

   return text




def 							_SCREAMING_SNAKE_CASE	(					A	:							List[Any]	)     ->			Optional[Any]:







   """simple docstring"""
   __snake_case					:   int  				=			{'ModelTesterMixin', 'TFModelTesterMixin', 'FlaxModelTesterMixin'}
   if not issubclass(A	,		unittest.TestCase	):
      return False
   return len(base_class_names.intersection([x.__name__ for x in test_class.__bases__]	)	) > 0




def 							_SCREAMING_SNAKE_CASE	(					A	:							Tuple	)     ->			Optional[int]:







   """simple docstring"""
   __snake_case					:   Any  				=			[x for x in get_test_classes(A	) if is_valid_test_class(A	)]

   __snake_case					:   Tuple  				=			None
   for test_class in test_classes:
      # If a test class has defined `pipeline_model_mapping`, let's take it
      if getattr(A	,		'pipeline_model_mapping'	,		A	) is not None:
         __snake_case					:   Optional[int]  				=			test_class
         break
    # Take the test class with the shortest name (just a heuristic)
   if target_test_class is None and len(A	) > 0:
      __snake_case					:   Tuple  				=			sorted(A	,		key=lambda A	: (len(x.__name__	), x.__name__)	)[0]

   return target_test_class




def 							_SCREAMING_SNAKE_CASE	(					A	:							str	,		A	:							Optional[int]	,		A	:							Optional[Any]	)     ->			Union[str, Any]:







   """simple docstring"""
   __snake_case					:   int  				=			start_idx
   for idx, line in enumerate(lines[start_idx:]	):
      __snake_case					:   Tuple  				=			len(A	) - len(line.lstrip()	)
      if idx == 0 or indent > indent_level or (indent == indent_level and line.strip() == ")"):
         __snake_case					:   int  				=			start_idx + idx
      elif idx > 0 and indent <= indent_level:
         # Outside the definition block of `pipeline_model_mapping`
         break

   return end_idx




def 							_SCREAMING_SNAKE_CASE	(					A	:							Tuple	,		A	:							Any=False	)     ->			Tuple:







   """simple docstring"""
   if getattr(A	,		'pipeline_model_mapping'	,		A	) is not None:
      if not overwrite:
         return "", -1

   __snake_case					:   List[str]  				=			get_pipeline_model_mapping_string(A	)
   if len(A	) == 0:
      return "", -1
   __snake_case					:   List[Any]  				=			line_to_add + '\n'

   # The code defined the class `test_class`
   __snake_case				,__snake_case					:   int  				=			inspect.getsourcelines(A	)
   # `inspect` gives the code for an object, including decorator(s) if any.
   # We (only) need the exact line of the class definition.
   for idx, line in enumerate(A	):
      if line.lstrip().startswith('class '	):
         __snake_case					:   Optional[int]  				=			class_lines[idx:]
         class_start_line_no += idx
         break
   __snake_case					:   Tuple  				=			class_start_line_no + len(A	) - 1

   # The index in `class_lines` that starts the definition of `all_model_classes`, `all_generative_model_classes` or
   # `pipeline_model_mapping`. This assumes they are defined in such order, and we take the start index of the last
   # block that appears in a `test_class`.
   __snake_case					:   Dict  				=			None
   # The indent level of the line at `class_lines[start_idx]` (if defined)
   __snake_case					:   str  				=			0
   # To record if `pipeline_model_mapping` is found in `test_class`.
   __snake_case					:   Optional[int]  				=			None
   for idx, line in enumerate(A	):
      if line.strip().startswith('all_model_classes = '	):
         __snake_case					:   Union[str, Any]  				=			len(A	) - len(line.lstrip()	)
         __snake_case					:   Union[str, Any]  				=			idx
      elif line.strip().startswith('all_generative_model_classes = '	):
         __snake_case					:   List[Any]  				=			len(A	) - len(line.lstrip()	)
         __snake_case					:   Union[str, Any]  				=			idx
      elif line.strip().startswith('pipeline_model_mapping = '	):
         __snake_case					:   Optional[int]  				=			len(A	) - len(line.lstrip()	)
         __snake_case					:   int  				=			idx
         __snake_case					:   str  				=			line
         break

   if start_idx is None:
      return "", -1
   # Find the ending index (inclusive) of the above found block.
   __snake_case					:   List[Any]  				=			find_block_ending(A	,		A	,		A	)

   # Extract `is_xxx_available()` from existing blocks: some models require specific libraries like `timm` and use
   # `is_timm_available()` instead of `is_torch_available()`.
   # Keep leading and trailing whitespaces
   __snake_case					:   str  				=			re.compile(R'\s(is_\S+?_available\(\))\s'	)
   for line in class_lines[start_idx : end_idx + 1]:
      __snake_case					:   Tuple  				=			r.search(A	)
      if backend_condition is not None:
         # replace the leading and trailing whitespaces to the space character " ".
         __snake_case					:   Optional[int]  				=			' ' + backend_condition[0][1:-1] + ' '
         __snake_case					:   Union[str, Any]  				=			r.sub(A	,		A	)
         break

   if def_line is None:
      # `pipeline_model_mapping` is not defined. The target index is set to the ending index (inclusive) of
      # `all_model_classes` or `all_generative_model_classes`.
      __snake_case					:   int  				=			end_idx
   else:
      # `pipeline_model_mapping` is defined. The target index is set to be one **BEFORE** its start index.
      __snake_case					:   List[str]  				=			start_idx - 1
      # mark the lines of the currently existing `pipeline_model_mapping` to be removed.
      for idx in range(A	,		end_idx + 1	):
         # These lines are going to be removed before writing to the test file.
         __snake_case					:   List[Any]  				=			None  # noqa

    # Make sure the test class is a subclass of `PipelineTesterMixin`.
   __snake_case					:   Optional[int]  				=			[x.__name__ for x in test_class.__bases__]
   if "PipelineTesterMixin" not in parent_classes:
      # Put `PipelineTesterMixin` just before `unittest.TestCase`
      __snake_case					:   Union[str, Any]  				=			[x for x in parent_classes if x != 'TestCase'] + ['PipelineTesterMixin']
      if "TestCase" in parent_classes:
         # Here we **assume** the original string is always with `unittest.TestCase`.
         _parent_classes.append('unittest.TestCase'	)
      __snake_case					:   Optional[Any]  				=			', '.join(_parent_classes	)
      for idx, line in enumerate(A	):
         # Find the ending of the declaration of `test_class`
         if line.strip().endswith('):'	):
            # mark the lines of the declaration of `test_class` to be removed
            for _idx in range(idx + 1	):
               __snake_case					:   str  				=			None  # noqa
            break
        # Add the new, one-line, class declaration for `test_class`
      __snake_case					:   str  				=			F"""class {test_class.__name__}({parent_classes}):\n"""

   # Add indentation
   __snake_case					:   Dict  				=			' ' * indent_level + line_to_add
   # Insert `pipeline_model_mapping` to `class_lines`.
   # (The line at `target_idx` should be kept by definition!)
   __snake_case					:   Optional[Any]  				=			class_lines[: target_idx + 1] + [line_to_add] + class_lines[target_idx + 1 :]
   # Remove the lines that are marked to be removed
   __snake_case					:   Union[str, Any]  				=			[x for x in class_lines if x is not None]

   # Move from test class to module (in order to write to the test file)
   __snake_case					:   Union[str, Any]  				=			inspect.getsourcelines(inspect.getmodule(A	)	)[0]
   # Be careful with the 1-off between line numbers and array indices
   __snake_case					:   Tuple  				=			module_lines[: class_start_line_no - 1] + class_lines + module_lines[class_end_line_no:]
   __snake_case					:   int  				=			''.join(A	)

   __snake_case					:   str  				=			inspect.getsourcefile(A	)
   with open(A	,		'w'	,		encoding='UTF-8'	,		newline='\n'	) as fp:
      fp.write(A	)

   return line_to_add




def 							_SCREAMING_SNAKE_CASE	(					A	:							Any	,		A	:							Optional[Any]=False	)     ->			List[Any]:







   """simple docstring"""
   __snake_case					:   Optional[int]  				=			find_test_class(A	)
   if test_class:
      add_pipeline_model_mapping(A	,		overwrite=A	)


if __name__ == "__main__":
      __A     						= argparse.ArgumentParser()
      parser.add_argument(
          '''--test_file''', type=str, help='''A path to the test file, starting with the repository\'s `tests` directory.'''
      )
      parser.add_argument(
          '''--all''',
          action='''store_true''',
          help='''If to check and modify all test files.''',
      )
      parser.add_argument(
          '''--overwrite''',
          action='''store_true''',
          help='''If to overwrite a test class if it has already defined `pipeline_model_mapping`.''',
      )
      __A     						= parser.parse_args()

      if not args.all and not args.test_file:
            raise ValueError('''Please specify either `test_file` or pass `--all` to check/modify all test files.''')
      elif args.all and args.test_file:
            raise ValueError('''Only one of `--test_file` and `--all` could be specified.''')

      __A     						= []
      if args.test_file:
            __A     						= [args.test_file]
      else:
            __A     						= os.path.join('''tests''', '''models''', '''**''', '''test_modeling_*.py''')
            for test_file in glob.glob(pattern):
                  # `Flax` is not concerned at this moment
                  if not test_file.startswith('''test_modeling_flax_'''):
                        test_files.append(test_file)

      for test_file in test_files:
            if test_file in TEST_FILE_TO_IGNORE:
                  print(f'''[SKIPPED] {test_file} is skipped as it is in `TEST_FILE_TO_IGNORE` in the file {__file__}.''')
                  continue
            add_pipeline_model_mapping_to_test_file(test_file, overwrite=args.overwrite)







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