import itertools
import random
import unittest

import numpy as np

from transformers import ASTFeatureExtractor
from transformers.testing_utils import require_torch, require_torchaudio
from transformers.utils.import_utils import is_torch_available

from ...test_sequence_feature_extraction_common import SequenceFeatureExtractionTestMixin


lowercase_  : Dict								=					random.Random()

if is_torch_available():
      import torch







def       A__   (						snake_case_			:		int							,					snake_case_			:		Optional[Any]=1.0							,					snake_case_			:		Dict=None							,					snake_case_			:		Dict=None   ):
 if rng is None:
  SCREAMING_SNAKE_CASE__: Tuple=   global_rng

 SCREAMING_SNAKE_CASE__: List[str]=   []
 for batch_idx in range(shape[0]   ):
  values.append([]   )
  for _ in range(shape[1]   ):
   values[-1].append(rng.random() * scale   )

 return values






class 		_lowerCamelCase		( unittest.TestCase     ):
    def __init__(	self			,			lowerCAmelCase			,			lowerCAmelCase=7			,			lowerCAmelCase=400			,			lowerCAmelCase=2000			,			lowerCAmelCase=1			,			lowerCAmelCase=0.0			,			lowerCAmelCase=16000			,			lowerCAmelCase=True			,			lowerCAmelCase=True			,			)							->       List[str]:
     SCREAMING_SNAKE_CASE__: Optional[Any]=   parent
     SCREAMING_SNAKE_CASE__: Dict=   batch_size
     SCREAMING_SNAKE_CASE__: Optional[int]=   min_seq_length
     SCREAMING_SNAKE_CASE__: Dict=   max_seq_length
     SCREAMING_SNAKE_CASE__: Optional[Any]=   (self.max_seq_length - self.min_seq_length) // (self.batch_size - 1)
     SCREAMING_SNAKE_CASE__: Dict=   feature_size
     SCREAMING_SNAKE_CASE__: str=   padding_value
     SCREAMING_SNAKE_CASE__: Dict=   sampling_rate
     SCREAMING_SNAKE_CASE__: List[str]=   return_attention_mask
     SCREAMING_SNAKE_CASE__: str=   do_normalize
    def     UpperCamelCase_					(	self )							->       Optional[Any]:
     return {
         "feature_size": self.feature_size,
         "padding_value": self.padding_value,
         "sampling_rate": self.sampling_rate,
         "return_attention_mask": self.return_attention_mask,
         "do_normalize": self.do_normalize,
     }



    def     UpperCamelCase_					(	self			,			lowerCAmelCase=False			,			lowerCAmelCase=False )							->       Dict:
     def _flatten(lowerCAmelCase ):
      return list(itertools.chain(*lowerCAmelCase ) )

     if equal_length:
      SCREAMING_SNAKE_CASE__: int=   floats_list((self.batch_size, self.max_seq_length) )
     else:
      # make sure that inputs increase in size
      SCREAMING_SNAKE_CASE__: int=   [
          _flatten(floats_list((x, self.feature_size) ) )
          for x in range(self.min_seq_length			,			self.max_seq_length			,			self.seq_length_diff )
      ]

     if numpify:
      SCREAMING_SNAKE_CASE__: Optional[Any]=   [np.asarray(lowerCAmelCase ) for x in speech_inputs]

     return speech_inputs






@require_torch
@require_torchaudio
class 		_lowerCamelCase		( UpperCamelCase_     ,  unittest.TestCase     ):
    __a						=   ASTFeatureExtractor
    def     UpperCamelCase_					(	self )							->       int:
     SCREAMING_SNAKE_CASE__: List[Any]=   ASTFeatureExtractionTester(self )
    def     UpperCamelCase_					(	self )							->       Any:
     # Tests that all call wrap to encode_plus and batch_encode_plus
     SCREAMING_SNAKE_CASE__: Optional[int]=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
     # create three inputs of length 800, 1000, and 1200
     SCREAMING_SNAKE_CASE__: Dict=   [floats_list((1, x) )[0] for x in range(800			,			1400			,			200 )]
     SCREAMING_SNAKE_CASE__: int=   [np.asarray(lowerCAmelCase ) for speech_input in speech_inputs]

     # Test not batched input
     SCREAMING_SNAKE_CASE__: Optional[int]=   feat_extract(speech_inputs[0]			,			return_tensors='''np''' ).input_values
     SCREAMING_SNAKE_CASE__: Optional[int]=   feat_extract(np_speech_inputs[0]			,			return_tensors='''np''' ).input_values
     self.assertTrue(np.allclose(lowerCAmelCase			,			lowerCAmelCase			,			atol=1e-3 ) )

     # Test batched
     SCREAMING_SNAKE_CASE__: Tuple=   feat_extract(lowerCAmelCase			,			padding=lowerCAmelCase			,			return_tensors='''np''' ).input_values
     SCREAMING_SNAKE_CASE__: Union[str, Any]=   feat_extract(lowerCAmelCase			,			padding=lowerCAmelCase			,			return_tensors='''np''' ).input_values
     for enc_seq_a, enc_seq_a in zip(lowerCAmelCase			,			lowerCAmelCase ):
      self.assertTrue(np.allclose(lowerCAmelCase			,			lowerCAmelCase			,			atol=1e-3 ) )

     # Test 2-D numpy arrays are batched.
     SCREAMING_SNAKE_CASE__: Optional[int]=   [floats_list((1, x) )[0] for x in (800, 800, 800)]
     SCREAMING_SNAKE_CASE__: List[Any]=   np.asarray(lowerCAmelCase )
     SCREAMING_SNAKE_CASE__: Optional[int]=   feat_extract(lowerCAmelCase			,			return_tensors='''np''' ).input_values
     SCREAMING_SNAKE_CASE__: Optional[Any]=   feat_extract(lowerCAmelCase			,			return_tensors='''np''' ).input_values
     for enc_seq_a, enc_seq_a in zip(lowerCAmelCase			,			lowerCAmelCase ):
      self.assertTrue(np.allclose(lowerCAmelCase			,			lowerCAmelCase			,			atol=1e-3 ) )
    @require_torch
    def     UpperCamelCase_					(	self )							->       Dict:
     import torch

     SCREAMING_SNAKE_CASE__: Optional[Any]=   self.feature_extraction_class(**self.feat_extract_tester.prepare_feat_extract_dict() )
     SCREAMING_SNAKE_CASE__: List[str]=   np.random.rand(100 ).astype(np.floataa )
     SCREAMING_SNAKE_CASE__: Optional[Any]=   np_speech_inputs.tolist()

     for inputs in [py_speech_inputs, np_speech_inputs]:
      SCREAMING_SNAKE_CASE__: Optional[Any]=   feature_extractor.pad([{'''input_values''': inputs}]			,			return_tensors='''np''' )
      self.assertTrue(np_processed.input_values.dtype == np.floataa )
      SCREAMING_SNAKE_CASE__: Optional[Any]=   feature_extractor.pad([{'''input_values''': inputs}]			,			return_tensors='''pt''' )
      self.assertTrue(pt_processed.input_values.dtype == torch.floataa )
    def     UpperCamelCase_					(	self			,			lowerCAmelCase )							->       Optional[int]:
     from datasets import load_dataset

     SCREAMING_SNAKE_CASE__: Optional[int]=   load_dataset('''hf-internal-testing/librispeech_asr_dummy'''			,			'''clean'''			,			split='''validation''' )
     # automatic decoding with librispeech
     SCREAMING_SNAKE_CASE__: Dict=   ds.sort('''id''' ).select(range(lowerCAmelCase ) )[:num_samples]['''audio''']

     return [x["array"] for x in speech_samples]



    @require_torch
    def     UpperCamelCase_					(	self )							->       str:
     # fmt: off
     SCREAMING_SNAKE_CASE__: str=   torch.tensor(
         [-0.9894, -1.2776, -0.9066, -1.2776, -0.9349, -1.2609, -1.0386, -1.2776,
          -1.1561, -1.2776, -1.2052, -1.2723, -1.2190, -1.2132, -1.2776, -1.1133,
          -1.1953, -1.1343, -1.1584, -1.2203, -1.1770, -1.2474, -1.2381, -1.1936,
          -0.9270, -0.8317, -0.8049, -0.7706, -0.7565, -0.7869] )
     # fmt: on

     SCREAMING_SNAKE_CASE__: Any=   self._load_datasamples(1 )
     SCREAMING_SNAKE_CASE__: Tuple=   ASTFeatureExtractor()
     SCREAMING_SNAKE_CASE__: str=   feature_extractor(lowerCAmelCase			,			return_tensors='''pt''' ).input_values
     self.assertEquals(input_values.shape			,			(1, 1024, 128) )
     self.assertTrue(torch.allclose(input_values[0, 0, :30]			,			lowerCAmelCase			,			atol=1e-4 ) )



'''simple docstring'''





from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFSequenceClassifierOutput,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import logging
from .configuration_regnet import RegNetConfig


SCREAMING_SNAKE_CASE     =       logging.get_logger(__name__)

# General docstring
SCREAMING_SNAKE_CASE     =       """RegNetConfig"""

# Base docstring
SCREAMING_SNAKE_CASE     =       """facebook/regnet-y-040"""
SCREAMING_SNAKE_CASE     =       [1, 1_0_8_8, 7, 7]

# Image classification docstring
SCREAMING_SNAKE_CASE     =       """facebook/regnet-y-040"""
SCREAMING_SNAKE_CASE     =       """tabby, tabby cat"""

SCREAMING_SNAKE_CASE     =       [
    """facebook/regnet-y-040""",
    # See all regnet models at https://huggingface.co/models?filter=regnet
]






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

 '''simple docstring'''







 def __init__(					self		:  str			,				snake_case__		:  int			,				snake_case__		:  int = 3			,				snake_case__		:  int = 1			,				snake_case__		:  int = 1			,				snake_case__		:  Optional[str] = "relu"			,				**snake_case__		:  Dict			,				):



   '''simple docstring'''




   super().__init__(**snake_case__ )
   # The padding and conv has been verified in
   # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb
   UpperCAmelCase__      :					Any				       =							tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2 )
   UpperCAmelCase__      :					Union[str, Any]				       =							tf.keras.layers.ConvaD(
       filters=snake_case__			,				kernel_size=snake_case__			,				strides=snake_case__			,				padding="VALID"			,				groups=snake_case__			,				use_bias=snake_case__			,				name="convolution"			,				)
   UpperCAmelCase__      :					Any				       =							tf.keras.layers.BatchNormalization(epsilon=1e-5			,				momentum=0.9			,				name="normalization" )
   UpperCAmelCase__      :					Tuple				       =							ACTaFN[activation] if activation is not None else tf.identity







 def 							UpperCamelCase  (					self		:  str			,				snake_case__		:  str ):



   '''simple docstring'''




   UpperCAmelCase__      :					str				       =							self.convolution(self.padding(snake_case__ ) )
   UpperCAmelCase__      :					Dict				       =							self.normalization(snake_case__ )
   UpperCAmelCase__      :					Any				       =							self.activation(snake_case__ )
   return hidden_state






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

 '''simple docstring'''







 def __init__(					self		:  List[Any]			,				snake_case__		:  RegNetConfig			,				**snake_case__		:  Optional[int] ):



   '''simple docstring'''




   super().__init__(**snake_case__ )
   UpperCAmelCase__      :					Any				       =							config.num_channels
   UpperCAmelCase__      :					Optional[Any]				       =							TFRegNetConvLayer(
       out_channels=config.embedding_size			,				kernel_size=3			,				stride=2			,				activation=config.hidden_act			,				name="embedder"			,				)







 def 							UpperCamelCase  (					self		:  int			,				snake_case__		:  List[str] ):



   '''simple docstring'''




   UpperCAmelCase__      :					Tuple				       =							shape_list(snake_case__ )[1]
   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." )

   # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format.
   # So change the input format from `NCHW` to `NHWC`.
   # shape = (batch_size, in_height, in_width, in_channels=num_channels)
   UpperCAmelCase__      :					List[str]				       =							tf.transpose(snake_case__			,				perm=(0, 2, 3, 1) )
   UpperCAmelCase__      :					Dict				       =							self.embedder(snake_case__ )
   return hidden_state






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

 '''simple docstring'''







 def __init__(					self		:  Optional[int]			,				snake_case__		:  int			,				snake_case__		:  int = 2			,				**snake_case__		:  Optional[int] ):



   '''simple docstring'''




   super().__init__(**snake_case__ )
   UpperCAmelCase__      :					int				       =							tf.keras.layers.ConvaD(
       filters=snake_case__			,				kernel_size=1			,				strides=snake_case__			,				use_bias=snake_case__			,				name="convolution" )
   UpperCAmelCase__      :					str				       =							tf.keras.layers.BatchNormalization(epsilon=1e-5			,				momentum=0.9			,				name="normalization" )







 def 							UpperCamelCase  (					self		:  str			,				snake_case__		:  tf.Tensor			,				snake_case__		:  bool = False ):



   '''simple docstring'''




   return self.normalization(self.convolution(snake_case__ )			,				training=snake_case__ )






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

 '''simple docstring'''







 def __init__(					self		:  List[str]			,				snake_case__		:  int			,				snake_case__		:  int			,				**snake_case__		:  Union[str, Any] ):



   '''simple docstring'''




   super().__init__(**snake_case__ )
   UpperCAmelCase__      :					Any				       =							tf.keras.layers.GlobalAveragePoolingaD(keepdims=snake_case__			,				name="pooler" )
   UpperCAmelCase__      :					Optional[Any]				       =							[
       tf.keras.layers.ConvaD(filters=snake_case__			,				kernel_size=1			,				activation="relu"			,				name="attention.0" ),
       tf.keras.layers.ConvaD(filters=snake_case__			,				kernel_size=1			,				activation="sigmoid"			,				name="attention.2" ),
   ]







 def 							UpperCamelCase  (					self		:  Optional[int]			,				snake_case__		:  Any ):



   '''simple docstring'''




   UpperCAmelCase__      :					Optional[int]				       =							self.pooler(snake_case__ )
   for layer_module in self.attention:
     UpperCAmelCase__      :					Dict				       =							layer_module(snake_case__ )
   UpperCAmelCase__      :					int				       =							hidden_state * pooled
   return hidden_state






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

 '''simple docstring'''







 def __init__(					self		:  List[str]			,				snake_case__		:  RegNetConfig			,				snake_case__		:  int			,				snake_case__		:  int			,				snake_case__		:  int = 1			,				**snake_case__		:  str ):



   '''simple docstring'''




   super().__init__(**snake_case__ )
   UpperCAmelCase__      :					Optional[Any]				       =							in_channels != out_channels or stride != 1
   UpperCAmelCase__      :					Optional[int]				       =							max(1			,				out_channels // config.groups_width )
   UpperCAmelCase__      :					Tuple				       =							(
       TFRegNetShortCut(snake_case__			,				stride=snake_case__			,				name="shortcut" )
       if should_apply_shortcut
       else tf.keras.layers.Activation("linear"			,				name="shortcut" )
   )
   # `self.layers` instead of `self.layer` because that is a reserved argument.
   UpperCAmelCase__      :					int				       =							[
       TFRegNetConvLayer(snake_case__			,				kernel_size=1			,				activation=config.hidden_act			,				name="layer.0" ),
       TFRegNetConvLayer(
           snake_case__			,				stride=snake_case__			,				groups=snake_case__			,				activation=config.hidden_act			,				name="layer.1" ),
       TFRegNetConvLayer(snake_case__			,				kernel_size=1			,				activation=snake_case__			,				name="layer.2" ),
   ]
   UpperCAmelCase__      :					List[Any]				       =							ACTaFN[config.hidden_act]







 def 							UpperCamelCase  (					self		:  Tuple			,				snake_case__		:  Optional[int] ):



   '''simple docstring'''




   UpperCAmelCase__      :					Any				       =							hidden_state
   for layer_module in self.layers:
     UpperCAmelCase__      :					List[str]				       =							layer_module(snake_case__ )
   UpperCAmelCase__      :					Optional[Any]				       =							self.shortcut(snake_case__ )
   hidden_state += residual
   UpperCAmelCase__      :					Union[str, Any]				       =							self.activation(snake_case__ )
   return hidden_state






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

 '''simple docstring'''







 def __init__(					self		:  List[Any]			,				snake_case__		:  RegNetConfig			,				snake_case__		:  int			,				snake_case__		:  int			,				snake_case__		:  int = 1			,				**snake_case__		:  List[Any] ):



   '''simple docstring'''




   super().__init__(**snake_case__ )
   UpperCAmelCase__      :					int				       =							in_channels != out_channels or stride != 1
   UpperCAmelCase__      :					Union[str, Any]				       =							max(1			,				out_channels // config.groups_width )
   UpperCAmelCase__      :					Dict				       =							(
       TFRegNetShortCut(snake_case__			,				stride=snake_case__			,				name="shortcut" )
       if should_apply_shortcut
       else tf.keras.layers.Activation("linear"			,				name="shortcut" )
   )
   UpperCAmelCase__      :					Optional[Any]				       =							[
       TFRegNetConvLayer(snake_case__			,				kernel_size=1			,				activation=config.hidden_act			,				name="layer.0" ),
       TFRegNetConvLayer(
           snake_case__			,				stride=snake_case__			,				groups=snake_case__			,				activation=config.hidden_act			,				name="layer.1" ),
       TFRegNetSELayer(snake_case__			,				reduced_channels=int(round(in_channels / 4 ) )			,				name="layer.2" ),
       TFRegNetConvLayer(snake_case__			,				kernel_size=1			,				activation=snake_case__			,				name="layer.3" ),
   ]
   UpperCAmelCase__      :					Dict				       =							ACTaFN[config.hidden_act]







 def 							UpperCamelCase  (					self		:  Optional[int]			,				snake_case__		:  List[str] ):



   '''simple docstring'''




   UpperCAmelCase__      :					List[str]				       =							hidden_state
   for layer_module in self.layers:
     UpperCAmelCase__      :					Tuple				       =							layer_module(snake_case__ )
   UpperCAmelCase__      :					Dict				       =							self.shortcut(snake_case__ )
   hidden_state += residual
   UpperCAmelCase__      :					List[Any]				       =							self.activation(snake_case__ )
   return hidden_state






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

 '''simple docstring'''







 def __init__(					self		:  List[Any]			,				snake_case__		:  RegNetConfig			,				snake_case__		:  int			,				snake_case__		:  int			,				snake_case__		:  int = 2			,				snake_case__		:  int = 2			,				**snake_case__		:  Any ):



   '''simple docstring'''




   super().__init__(**snake_case__ )

   UpperCAmelCase__      :					Any				       =							TFRegNetXLayer if config.layer_type == "x" else TFRegNetYLayer
   UpperCAmelCase__      :					int				       =							[
       # downsampling is done in the first layer with stride of 2
       layer(snake_case__			,				snake_case__			,				snake_case__			,				stride=snake_case__			,				name="layers.0" ),
       *[layer(snake_case__			,				snake_case__			,				snake_case__			,				name=F"""layers.{i+1}""" ) for i in range(depth - 1 )],
   ]







 def 							UpperCamelCase  (					self		:  Dict			,				snake_case__		:  Tuple ):



   '''simple docstring'''




   for layer_module in self.layers:
     UpperCAmelCase__      :					Tuple				       =							layer_module(snake_case__ )
   return hidden_state






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

 '''simple docstring'''







 def __init__(					self		:  Dict			,				snake_case__		:  RegNetConfig			,				**snake_case__		:  Any ):



   '''simple docstring'''




   super().__init__(**snake_case__ )
   UpperCAmelCase__      :					Union[str, Any]				       =							[]
   # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
   self.stages.append(
       TFRegNetStage(
           snake_case__			,				config.embedding_size			,				config.hidden_sizes[0]			,				stride=2 if config.downsample_in_first_stage else 1			,				depth=config.depths[0]			,				name="stages.0"			,				) )
   UpperCAmelCase__      :					List[Any]				       =							zip(config.hidden_sizes			,				config.hidden_sizes[1:] )
   for i, ((in_channels, out_channels), depth) in enumerate(zip(snake_case__			,				config.depths[1:] ) ):
     self.stages.append(TFRegNetStage(snake_case__			,				snake_case__			,				snake_case__			,				depth=snake_case__			,				name=F"""stages.{i+1}""" ) )







 def 							UpperCamelCase  (					self		:  Dict			,				snake_case__		:  tf.Tensor			,				snake_case__		:  bool = False			,				snake_case__		:  bool = True ):



   '''simple docstring'''




   UpperCAmelCase__      :					Tuple				       =							() if output_hidden_states else None

   for stage_module in self.stages:
     if output_hidden_states:
       UpperCAmelCase__      :					Optional[Any]				       =							hidden_states + (hidden_state,)

     UpperCAmelCase__      :					Dict				       =							stage_module(snake_case__ )

   if output_hidden_states:
     UpperCAmelCase__      :					Any				       =							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=snake_case__			,				hidden_states=snake_case__ )






@keras_serializable
class 							UpperCAmelCase_							(    tf.keras.layers.Layer				):

 '''simple docstring'''
 lowercase_					:    Dict				=							RegNetConfig







 def __init__(					self		:  int			,				snake_case__		:  str			,				**snake_case__		:  Union[str, Any] ):



   '''simple docstring'''




   super().__init__(**snake_case__ )
   UpperCAmelCase__      :					List[Any]				       =							config
   UpperCAmelCase__      :					Dict				       =							TFRegNetEmbeddings(snake_case__			,				name="embedder" )
   UpperCAmelCase__      :					int				       =							TFRegNetEncoder(snake_case__			,				name="encoder" )
   UpperCAmelCase__      :					int				       =							tf.keras.layers.GlobalAveragePoolingaD(keepdims=snake_case__			,				name="pooler" )







 @unpack_inputs
 def 							UpperCamelCase  (					self		:  Dict			,				snake_case__		:  tf.Tensor			,				snake_case__		:  Optional[bool] = None			,				snake_case__		:  Optional[bool] = None			,				snake_case__		:  bool = False			,				):



   '''simple docstring'''




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

   UpperCAmelCase__      :					str				       =							self.embedder(snake_case__			,				training=snake_case__ )

   UpperCAmelCase__      :					Optional[Any]				       =							self.encoder(
       snake_case__			,				output_hidden_states=snake_case__			,				return_dict=snake_case__			,				training=snake_case__ )

   UpperCAmelCase__      :					Optional[int]				       =							encoder_outputs[0]
   UpperCAmelCase__      :					Optional[Any]				       =							self.pooler(snake_case__ )

   # Change to NCHW output format have uniformity in the modules
   UpperCAmelCase__      :					List[Any]				       =							tf.transpose(snake_case__			,				perm=(0, 3, 1, 2) )
   UpperCAmelCase__      :					Any				       =							tf.transpose(snake_case__			,				perm=(0, 3, 1, 2) )

   # Change the other hidden state outputs to NCHW as well
   if output_hidden_states:
     UpperCAmelCase__      :					Optional[int]				       =							tuple([tf.transpose(snake_case__			,				perm=(0, 3, 1, 2) ) for h in encoder_outputs[1]] )

   if not return_dict:
     return (last_hidden_state, pooled_output) + encoder_outputs[1:]

   return TFBaseModelOutputWithPoolingAndNoAttention(
       last_hidden_state=snake_case__			,				pooler_output=snake_case__			,				hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states			,				)






class 							UpperCAmelCase_							(    A				):

 '''simple docstring'''
 lowercase_					:    List[Any]				=							RegNetConfig
 lowercase_					:    Optional[int]				=							"regnet"
 lowercase_					:    Optional[Any]				=							"pixel_values"







 @property
 def 							UpperCamelCase  (					self		:  Any ):



   '''simple docstring'''




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



SCREAMING_SNAKE_CASE     =       R"""
    Parameters:
    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.
        config ([`RegNetConfig`]): 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.
"""

SCREAMING_SNAKE_CASE     =       R"""
    Args:
        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConveNextImageProcessor.__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.
"""






@add_start_docstrings(
    "The bare RegNet model outputting raw features without any specific head on top."					,				A					,				)
class 							UpperCAmelCase_							(    A				):

 '''simple docstring'''







 def __init__(					self		:  Union[str, Any]			,				snake_case__		:  RegNetConfig			,				*snake_case__		:  Any			,				**snake_case__		:  List[str] ):



   '''simple docstring'''




   super().__init__(snake_case__			,				*snake_case__			,				**snake_case__ )
   UpperCAmelCase__      :					Any				       =							TFRegNetMainLayer(snake_case__			,				name="regnet" )







 @unpack_inputs
 @add_start_docstrings_to_model_forward(snake_case__ )
 @add_code_sample_docstrings(
     checkpoint=_CHECKPOINT_FOR_DOC			,				output_type=snake_case__			,				config_class=_CONFIG_FOR_DOC			,				modality="vision"			,				expected_output=_EXPECTED_OUTPUT_SHAPE			,				)
 def 							UpperCamelCase  (					self		:  Optional[int]			,				snake_case__		:  tf.Tensor			,				snake_case__		:  Optional[bool] = None			,				snake_case__		:  Optional[bool] = None			,				snake_case__		:  int=False			,				):



   '''simple docstring'''




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

   UpperCAmelCase__      :					List[str]				       =							self.regnet(
       pixel_values=snake_case__			,				output_hidden_states=snake_case__			,				return_dict=snake_case__			,				training=snake_case__			,				)
   if not return_dict:
     return (outputs[0],) + outputs[1:]

   return TFBaseModelOutputWithPoolingAndNoAttention(
       last_hidden_state=outputs.last_hidden_state			,				pooler_output=outputs.pooler_output			,				hidden_states=outputs.hidden_states			,				)






@add_start_docstrings(
    "\n    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for\n    ImageNet.\n    "					,				A					,				)
class 							UpperCAmelCase_							(    A					,				A				):

 '''simple docstring'''







 def __init__(					self		:  List[str]			,				snake_case__		:  RegNetConfig			,				*snake_case__		:  Optional[Any]			,				**snake_case__		:  int ):



   '''simple docstring'''




   super().__init__(snake_case__			,				*snake_case__			,				**snake_case__ )
   UpperCAmelCase__      :					Optional[Any]				       =							config.num_labels
   UpperCAmelCase__      :					str				       =							TFRegNetMainLayer(snake_case__			,				name="regnet" )
   # classification head
   UpperCAmelCase__      :					Optional[int]				       =							[
       tf.keras.layers.Flatten(),
       tf.keras.layers.Dense(config.num_labels			,				name="classifier.1" ) if config.num_labels > 0 else tf.identity,
   ]







 @unpack_inputs
 @add_start_docstrings_to_model_forward(snake_case__ )
 @add_code_sample_docstrings(
     checkpoint=_IMAGE_CLASS_CHECKPOINT			,				output_type=snake_case__			,				config_class=_CONFIG_FOR_DOC			,				expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT			,				)
 def 							UpperCamelCase  (					self		:  List[str]			,				snake_case__		:  tf.Tensor = None			,				snake_case__		:  tf.Tensor = None			,				snake_case__		:  bool = None			,				snake_case__		:  bool = None			,				snake_case__		:  List[Any]=False			,				):



   '''simple docstring'''




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

   UpperCAmelCase__      :					Dict				       =							self.regnet(
       snake_case__			,				output_hidden_states=snake_case__			,				return_dict=snake_case__			,				training=snake_case__ )

   UpperCAmelCase__      :					Dict				       =							outputs.pooler_output if return_dict else outputs[1]

   UpperCAmelCase__      :					Union[str, Any]				       =							self.classifier[0](snake_case__ )
   UpperCAmelCase__      :					str				       =							self.classifier[1](snake_case__ )

   UpperCAmelCase__      :					Any				       =							None if labels is None else self.hf_compute_loss(labels=snake_case__			,				logits=snake_case__ )

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

   return TFSequenceClassifierOutput(loss=snake_case__			,				logits=snake_case__			,				hidden_states=outputs.hidden_states )



