






'''simple docstring'''






import json
import os
import re
import warnings
from pathlib import Path
from shutil import copyfile
from typing import Any, Dict, List, Optional, Tuple, Union

import sentencepiece

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


__A     						= logging.get_logger(__name__)

__A     						= {
    '''source_spm''': '''source.spm''',
    '''target_spm''': '''target.spm''',
    '''vocab''': '''vocab.json''',
    '''target_vocab_file''': '''target_vocab.json''',
    '''tokenizer_config_file''': '''tokenizer_config.json''',
}

__A     						= {
    '''source_spm''': {
        '''Helsinki-NLP/opus-mt-en-de''': '''https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/source.spm'''
    },
    '''target_spm''': {
        '''Helsinki-NLP/opus-mt-en-de''': '''https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/target.spm'''
    },
    '''vocab''': {
        '''Helsinki-NLP/opus-mt-en-de''': '''https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/vocab.json'''
    },
    '''tokenizer_config_file''': {
        '''Helsinki-NLP/opus-mt-en-de''': (
            '''https://huggingface.co/Helsinki-NLP/opus-mt-en-de/resolve/main/tokenizer_config.json'''
        )
    },
}

__A     						= {'''Helsinki-NLP/opus-mt-en-de''': 5_1_2}
__A     						= {}




class a_     (     UpperCamelCase_				):
   _snake_case	   =				VOCAB_FILES_NAMES
   _snake_case	   =				PRETRAINED_VOCAB_FILES_MAP
   _snake_case	   =				PRETRAINED_INIT_CONFIGURATION
   _snake_case	   =				PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
   _snake_case	   =				["""input_ids""", """attention_mask"""]
   _snake_case	   =				re.compile(""">>.+<<"""				)  # type: re.Pattern







   def __init__(self       , __a       , __a       , __a       , __a=None       , __a=None       , __a=None       , __a="<unk>"       , __a="</s>"       , __a="<pad>"       , __a=5_1_2       , __a = None       , __a=False       , **__a       , )      ->   None:
      """simple docstring"""






      __snake_case					:   str  				=			{} if sp_model_kwargs is None else sp_model_kwargs

      super().__init__(
          # bos_token=bos_token,  unused. Start decoding with config.decoder_start_token_id
          source_lang=__a       , target_lang=__a       , unk_token=__a       , eos_token=__a       , pad_token=__a       , model_max_length=__a       , sp_model_kwargs=self.sp_model_kwargs       , target_vocab_file=__a       , separate_vocabs=__a       , **__a       , )
      assert Path(__a).exists(), F"""cannot find spm source {source_spm}"""

      __snake_case					:   Any  				=			separate_vocabs
      __snake_case					:   Optional[int]  				=			load_json(__a)
      if self.unk_token not in self.encoder:
         raise KeyError('<unk> token must be in vocab')
      assert self.pad_token in self.encoder

      if separate_vocabs:
         __snake_case					:   int  				=			load_json(__a)
         __snake_case					:   str  				=			{v: k for k, v in self.target_encoder.items()}
         __snake_case					:   int  				=			[]
      else:
         __snake_case					:   List[Any]  				=			{v: k for k, v in self.encoder.items()}
         __snake_case					:   list  				=			[k for k in self.encoder if k.startswith('>>') and k.endswith('<<')]

      __snake_case					:   List[Any]  				=			source_lang
      __snake_case					:   Tuple  				=			target_lang
      __snake_case					:   Optional[Any]  				=			[source_spm, target_spm]

      # load SentencePiece model for pre-processing
      __snake_case					:   int  				=			load_spm(__a       , self.sp_model_kwargs)
      __snake_case					:   Dict  				=			load_spm(__a       , self.sp_model_kwargs)
      __snake_case					:   Dict  				=			self.spm_source
      __snake_case					:   Optional[Any]  				=			self.encoder

      # Multilingual target side: default to using first supported language code.

      self._setup_normalizer()







   def      SCREAMING_SNAKE_CASE__       (self)      ->   str:
      """simple docstring"""






      try:
         from sacremoses import MosesPunctNormalizer

         __snake_case					:   str  				=			MosesPunctNormalizer(self.source_lang).normalize
      except (ImportError, FileNotFoundError):
         warnings.warn('Recommended: pip install sacremoses.')
         __snake_case					:   Any  				=			lambda __a: x







   def      SCREAMING_SNAKE_CASE__       (self       , __a)      ->   str:
      """simple docstring"""






      return self.punc_normalizer(__a) if x else ""







   def      SCREAMING_SNAKE_CASE__       (self       , __a)      ->   int:
      """simple docstring"""






      return self.current_encoder.get(__a       , self.current_encoder[self.unk_token])







   def      SCREAMING_SNAKE_CASE__       (self       , __a)      ->   Union[str, Any]:
      """simple docstring"""






      __snake_case					:   Tuple  				=			self.language_code_re.match(__a)
      __snake_case					:   list  				=			[match.group(0)] if match else []
      return code, self.language_code_re.sub(''       , __a)







   def      SCREAMING_SNAKE_CASE__       (self       , __a)      ->   List[str]:
      """simple docstring"""






      __snake_case				,__snake_case					:   List[Any]  				=			self.remove_language_code(__a)
      __snake_case					:   Union[str, Any]  				=			self.current_spm.encode(__a       , out_type=__a)
      return code + pieces







   def      SCREAMING_SNAKE_CASE__       (self       , __a)      ->   str:
      """simple docstring"""






      return self.decoder.get(__a       , self.unk_token)







   def      SCREAMING_SNAKE_CASE__       (self       , __a       , **__a)      ->   Optional[Any]:
      """simple docstring"""






      return super().batch_decode(__a       , **__a)







   def      SCREAMING_SNAKE_CASE__       (self       , __a       , **__a)      ->   Dict:
      """simple docstring"""






      return super().decode(__a       , **__a)







   def      SCREAMING_SNAKE_CASE__       (self       , __a)      ->   str:
      """simple docstring"""






      __snake_case					:   Optional[Any]  				=			self.spm_source if self._decode_use_source_tokenizer else self.spm_target
      __snake_case					:   int  				=			[]
      __snake_case					:   List[str]  				=			''
      for token in tokens:
         # make sure that special tokens are not decoded using sentencepiece model
         if token in self.all_special_tokens:
            out_string += sp_model.decode_pieces(__a) + token + " "
            __snake_case					:   List[str]  				=			[]
         else:
            current_sub_tokens.append(__a)
      out_string += sp_model.decode_pieces(__a)
      return out_string.strip()







   def      SCREAMING_SNAKE_CASE__       (self       , __a       , __a=None)      ->   List[int]:
      """simple docstring"""






      if token_ids_a is None:
         return token_ids_a + [self.eos_token_id]
      # We don't expect to process pairs, but leave the pair logic for API consistency
      return token_ids_a + token_ids_a + [self.eos_token_id]







   def      SCREAMING_SNAKE_CASE__       (self)      ->   int:
      """simple docstring"""






      __snake_case					:   Optional[Any]  				=			self.spm_source
      __snake_case					:   str  				=			self.encoder







   def      SCREAMING_SNAKE_CASE__       (self)      ->   Optional[Any]:
      """simple docstring"""






      __snake_case					:   List[Any]  				=			self.spm_target
      if self.separate_vocabs:
         __snake_case					:   Optional[Any]  				=			self.target_encoder







   @property
   def      SCREAMING_SNAKE_CASE__       (self)      ->   int:
      """simple docstring"""






      return len(self.encoder)







   def      SCREAMING_SNAKE_CASE__       (self       , __a       , __a = None)      ->   Tuple[str]:
      """simple docstring"""






      if not os.path.isdir(__a):
         logger.error(F"""Vocabulary path ({save_directory}) should be a directory""")
         return
      __snake_case					:   List[Any]  				=			[]

      if self.separate_vocabs:
         __snake_case					:   int  				=			os.path.join(
             __a       , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab']       , )
         __snake_case					:   Union[str, Any]  				=			os.path.join(
             __a       , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['target_vocab_file']       , )
         save_json(self.encoder       , __a)
         save_json(self.target_encoder       , __a)
         saved_files.append(__a)
         saved_files.append(__a)
      else:
         __snake_case					:   Optional[Any]  				=			os.path.join(
             __a       , (filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab'])
         save_json(self.encoder       , __a)
         saved_files.append(__a)

      for spm_save_filename, spm_orig_path, spm_model in zip(
          [VOCAB_FILES_NAMES['source_spm'], VOCAB_FILES_NAMES['target_spm']]       , self.spm_files       , [self.spm_source, self.spm_target]       , ):
         __snake_case					:   str  				=			os.path.join(
             __a       , (filename_prefix + '-' if filename_prefix else '') + spm_save_filename)
         if os.path.abspath(__a) != os.path.abspath(__a) and os.path.isfile(__a):
            copyfile(__a       , __a)
            saved_files.append(__a)
         elif not os.path.isfile(__a):
            with open(__a       , 'wb') as fi:
               __snake_case					:   Optional[Any]  				=			spm_model.serialized_model_proto()
               fi.write(__a)
            saved_files.append(__a)

      return tuple(__a)







   def      SCREAMING_SNAKE_CASE__       (self)      ->   Dict:
      """simple docstring"""






      return self.get_src_vocab()







   def      SCREAMING_SNAKE_CASE__       (self)      ->   Union[str, Any]:
      """simple docstring"""






      return dict(self.encoder       , **self.added_tokens_encoder)







   def      SCREAMING_SNAKE_CASE__       (self)      ->   int:
      """simple docstring"""






      return dict(self.target_encoder       , **self.added_tokens_decoder)







   def __getstate__(self)      ->   Dict:
      """simple docstring"""






      __snake_case					:   Dict  				=			self.__dict__.copy()
      state.update(
          {k: None for k in ['spm_source', 'spm_target', 'current_spm', 'punc_normalizer', 'target_vocab_file']})
      return state







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






      __snake_case					:   Tuple  				=			d

      # for backward compatibility
      if not hasattr(self       , 'sp_model_kwargs'):
         __snake_case					:   List[Any]  				=			{}

      __snake_case				,__snake_case					:   Any  				=			(load_spm(__a       , self.sp_model_kwargs) for f in self.spm_files)
      __snake_case					:   List[str]  				=			self.spm_source
      self._setup_normalizer()







   def      SCREAMING_SNAKE_CASE__       (self       , *__a       , **__a)      ->   Optional[int]:
      """simple docstring"""






      return 1







   def      SCREAMING_SNAKE_CASE__       (self       , __a)      ->   Any:
      """simple docstring"""






      __snake_case					:   Dict  				=			set(self.all_special_ids)  # call it once instead of inside list comp
      all_special_ids.remove(self.unk_token_id)  # <unk> is only sometimes special
      return [1 if x in all_special_ids else 0 for x in seq]







   def      SCREAMING_SNAKE_CASE__       (self       , __a       , __a = None       , __a = False)      ->   List[int]:
      """simple docstring"""






      if already_has_special_tokens:
         return self._special_token_mask(__a)
      elif token_ids_a is None:
         return self._special_token_mask(__a) + [1]
      else:
         return self._special_token_mask(token_ids_a + token_ids_a) + [1]




def 							_SCREAMING_SNAKE_CASE	(					A	:							str	,		A	:							Dict[str, Any]	)     ->			sentencepiece.SentencePieceProcessor:







   """simple docstring"""
   __snake_case					:   int  				=			sentencepiece.SentencePieceProcessor(**A	)
   spm.Load(A	)
   return spm




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







   """simple docstring"""
   with open(A	,		'w'	) as f:
      json.dump(A	,		A	,		indent=2	)





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







   """simple docstring"""
   with open(A	,		'r'	) as f:
      return json.load(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)