
'''simple docstring'''
import importlib.metadata
import warnings
from copy import deepcopy

from packaging import version

from ..utils import logging
from .import_utils import is_accelerate_available, is_bitsandbytes_available


if is_bitsandbytes_available():
						import bitsandbytes as bnb
						import torch
						import torch.nn as nn

						from ..pytorch_utils import ConvaD

if is_accelerate_available():
						from accelerate import init_empty_weights
						from accelerate.utils import find_tied_parameters

lowerCAmelCase					:    Optional[int]           = logging.get_logger(__name__)







def 		A_(     A						:		Optional[int]		,     A						:		Any		,     A						:		Union[str, Any]		,     A						:		Optional[int]=None		,     A						:		List[str]=None):
							# Recurse if needed
							if "." in tensor_name:
														UpperCamelCase   			=     tensor_name.split('.')
														for split in splits[:-1]:
																					UpperCamelCase   			=     getattr(A		,     A)
																					if new_module is None:
																												raise ValueError(f'''{module} has no attribute {split}.''')
																					UpperCamelCase   			=     new_module
														UpperCamelCase   			=     splits[-1]

							if tensor_name not in module._parameters and tensor_name not in module._buffers:
														raise ValueError(f'''{module} does not have a parameter or a buffer named {tensor_name}.''')
							UpperCamelCase   			=     tensor_name in module._buffers
							UpperCamelCase   			=     getattr(A		,     A)

							if old_value.device == torch.device('meta') and device not in ["meta", torch.device('meta')] and value is None:
														raise ValueError(f'''{tensor_name} is on the meta device, we need a `value` to put in on {device}.''')

							UpperCamelCase   			=     False
							UpperCamelCase   			=     False
							if is_buffer or not is_bitsandbytes_available():
														UpperCamelCase   			=     False
														UpperCamelCase   			=     False
							else:
														UpperCamelCase   			=     hasattr(bnb.nn		,     'Params4bit') and isinstance(module._parameters[tensor_name]		,     bnb.nn.Paramsabit)
														UpperCamelCase   			=     isinstance(module._parameters[tensor_name]		,     bnb.nn.IntaParams)

							if is_abit or is_abit:
														UpperCamelCase   			=     module._parameters[tensor_name]
														if param.device.type != "cuda":
																					if value is None:
																												UpperCamelCase   			=     old_value.to(A)
																					elif isinstance(A		,     torch.Tensor):
																												UpperCamelCase   			=     value.to('cpu')
																												if value.dtype == torch.inta:
																																			UpperCamelCase   			=     version.parse(importlib.metadata.version('bitsandbytes')) > version.parse(
																																			    '0.37.2')
																																			if not is_abit_serializable:
																																										raise ValueError(
																																										    'Detected int8 weights but the version of bitsandbytes is not compatible with int8 serialization. '
																																										    'Make sure to download the latest `bitsandbytes` version. `pip install --upgrade bitsandbytes`.')
																					else:
																												UpperCamelCase   			=     torch.tensor(A		,     device='cpu')

																					# Support models using `Conv1D` in place of `nn.Linear` (e.g. gpt2) by transposing the weight matrix prior to quantization.
																					# Since weights are saved in the correct "orientation", we skip transposing when loading.
																					if issubclass(module.source_cls		,     A) and fpaa_statistics is None:
																												UpperCamelCase   			=     new_value.T

																					UpperCamelCase   			=     old_value.__dict__
																					if is_abit:
																												UpperCamelCase   			=     bnb.nn.IntaParams(A		,     requires_grad=A		,     **A).to(A)
																					elif is_abit:
																												UpperCamelCase   			=     bnb.nn.Paramsabit(A		,     requires_grad=A		,     **A).to(A)

																					UpperCamelCase   			=     new_value
																					if fpaa_statistics is not None:
																												setattr(module.weight		,     'SCB'		,     fpaa_statistics.to(A))

							else:
														if value is None:
																					UpperCamelCase   			=     old_value.to(A)
														elif isinstance(A		,     torch.Tensor):
																					UpperCamelCase   			=     value.to(A)
														else:
																					UpperCamelCase   			=     torch.tensor(A		,     device=A)

														if is_buffer:
																					UpperCamelCase   			=     new_value
														else:
																					UpperCamelCase   			=     nn.Parameter(A		,     requires_grad=old_value.requires_grad)
																					UpperCamelCase   			=     new_value







def 		A_(     A						:		Union[str, Any]		,     A						:		str=None		,     A						:		List[str]=None		,     A						:		str=None		,     A						:		Dict=False):
							for name, module in model.named_children():
														if current_key_name is None:
																					UpperCamelCase   			=     []
														current_key_name.append(A)

														if (isinstance(A		,     nn.Linear) or isinstance(A		,     A)) and name not in modules_to_not_convert:
																					# Check if the current key is not in the `modules_to_not_convert`
																					if not any(key in '.'.join(A) for key in modules_to_not_convert):
																												with init_empty_weights():
																																			if isinstance(A		,     A):
																																										UpperCamelCase			,	UpperCamelCase   			=     module.weight.shape
																																			else:
																																										UpperCamelCase   			=     module.in_features
																																										UpperCamelCase   			=     module.out_features

																																			if quantization_config.quantization_method() == "llm_int8":
																																										UpperCamelCase   			=     bnb.nn.LinearabitLt(
																																										    A		,     A		,     module.bias is not None		,     has_fpaa_weights=quantization_config.llm_inta_has_fpaa_weight		,     threshold=quantization_config.llm_inta_threshold		,     )
																																										UpperCamelCase   			=     True
																																			else:
																																										if (
																																										    quantization_config.llm_inta_skip_modules is not None
																																										    and name in quantization_config.llm_inta_skip_modules
																																										):
																																																	pass
																																										else:
																																																	UpperCamelCase   			=     bnb.nn.Linearabit(
																																																	    A		,     A		,     module.bias is not None		,     quantization_config.bnb_abit_compute_dtype		,     compress_statistics=quantization_config.bnb_abit_use_double_quant		,     quant_type=quantization_config.bnb_abit_quant_type		,     )
																																																	UpperCamelCase   			=     True
                    # Store the module class in case we need to transpose the weight later
																																			UpperCamelCase   			=     type(A)
																																			# Force requires grad to False to avoid unexpected errors
																																			model._modules[name].requires_grad_(A)
														if len(list(module.children())) > 0:
																					UpperCamelCase			,	UpperCamelCase   			=     _replace_with_bnb_linear(
																					    A		,     A		,     A		,     A		,     has_been_replaced=A		,     )
														# Remove the last key for recursion
														current_key_name.pop(-1)
							return model, has_been_replaced







def 		A_(     A						:		Union[str, Any]		,     A						:		List[Any]=None		,     A						:		Optional[Any]=None		,     A						:		str=None):
							UpperCamelCase   			=     ['lm_head'] if modules_to_not_convert is None else modules_to_not_convert
							UpperCamelCase			,	UpperCamelCase   			=     _replace_with_bnb_linear(
							    A		,     A		,     A		,     A)

							if not has_been_replaced:
														logger.warning(
														    'You are loading your model in 8bit or 4bit but no linear modules were found in your model.'
														    ' Please double check your model architecture, or submit an issue on github if you think this is'
														    ' a bug.')

							return model







def 		A_(     *A						:		Tuple		,     **A						:		Optional[int]):
							warnings.warn(
							    '`replace_8bit_linear` will be deprecated in a future version, please use `replace_with_bnb_linear` instead'		,     A		,     )
							return replace_with_bnb_linear(*A		,     **A)







def 		A_(     *A						:		List[str]		,     **A						:		Tuple):
							warnings.warn(
							    '`set_module_8bit_tensor_to_device` will be deprecated in a future version, please use `set_module_quantized_tensor_to_device` instead'		,     A		,     )
							return set_module_quantized_tensor_to_device(*A		,     **A)







def 		A_(     A						:		int):
							UpperCamelCase   			=     deepcopy(A)  # this has 0 cost since it is done inside `init_empty_weights` context manager`
							tied_model.tie_weights()

							UpperCamelCase   			=     find_tied_parameters(A)
							# For compatibility with Accelerate < 0.18
							if isinstance(A		,     A):
														UpperCamelCase   			=     sum(list(tied_params.values())		,     []) + list(tied_params.keys())
							else:
														UpperCamelCase   			=     sum(A		,     [])
							UpperCamelCase   			=     len(A) > 0

							# Check if it is a base model
							UpperCamelCase   			=     not hasattr(A		,     model.base_model_prefix)

							# Ignore this for base models (BertModel, GPT2Model, etc.)
							if (not has_tied_params) and is_base_model:
														return []

							# otherwise they have an attached head
							UpperCamelCase   			=     list(model.named_children())
							UpperCamelCase   			=     [list_modules[-1][0]]

							# add last module together with tied weights
							UpperCamelCase   			=     set(A) - set(A)
							UpperCamelCase   			=     list(set(A)) + list(A)

							# remove ".weight" from the keys
							UpperCamelCase   			=     ['.weight', '.bias']
							UpperCamelCase   			=     []
							for name in list_untouched:
														for name_to_remove in names_to_remove:
																					if name_to_remove in name:
																												UpperCamelCase   			=     name.replace(A		,     '')
														filtered_module_names.append(A)

							return filtered_module_names






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


lowerCAmelCase					:    Dict           = logging.get_logger(__name__)

# General docstring
lowerCAmelCase					:    str           = 'RegNetConfig'

# Base docstring
lowerCAmelCase					:    str           = 'facebook/regnet-y-040'
lowerCAmelCase					:    Dict           = [1, 10_88, 7, 7]

# Image classification docstring
lowerCAmelCase					:    Dict           = 'facebook/regnet-y-040'
lowerCAmelCase					:    int           = 'tabby, tabby cat'

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


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







				def __init__(       self						,				A_						,				A_ = 3						,				A_ = 1						,				A_ = 1						,				A_ = "relu"						,				**A_						,				)->		str:







											'''simple docstring'''






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







				def 						UpperCAmelCase_    (       self						,				A_     )->		Any:







											'''simple docstring'''






											UpperCamelCase   			=     self.convolution(self.padding(A_     )     )
											UpperCamelCase   			=     self.normalization(A_     )
											UpperCamelCase   			=     self.activation(A_     )
											return hidden_state


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







				def __init__(       self						,				A_						,				**A_     )->		Optional[Any]:







											'''simple docstring'''






											super().__init__(**A_     )
											UpperCamelCase   			=     config.num_channels
											UpperCamelCase   			=     TFRegNetConvLayer(
											    out_channels=config.embedding_size						,				kernel_size=3						,				stride=2						,				activation=config.hidden_act						,				name='embedder'						,				)







				def 						UpperCAmelCase_    (       self						,				A_     )->		List[Any]:







											'''simple docstring'''






											UpperCamelCase   			=     shape_list(A_     )[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   			=     tf.transpose(A_						,				perm=(0, 2, 3, 1)     )
											UpperCamelCase   			=     self.embedder(A_     )
											return hidden_state


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







				def __init__(       self						,				A_						,				A_ = 2						,				**A_     )->		List[Any]:







											'''simple docstring'''






											super().__init__(**A_     )
											UpperCamelCase   			=     tf.keras.layers.ConvaD(
											    filters=A_						,				kernel_size=1						,				strides=A_						,				use_bias=A_						,				name='convolution'     )
											UpperCamelCase   			=     tf.keras.layers.BatchNormalization(epsilon=1e-5						,				momentum=0.9						,				name='normalization'     )







				def 						UpperCAmelCase_    (       self						,				A_						,				A_ = False     )->		tf.Tensor:







											'''simple docstring'''






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


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







				def __init__(       self						,				A_						,				A_						,				**A_     )->		Optional[Any]:







											'''simple docstring'''






											super().__init__(**A_     )
											UpperCamelCase   			=     tf.keras.layers.GlobalAveragePoolingaD(keepdims=A_						,				name='pooler'     )
											UpperCamelCase   			=     [
											    tf.keras.layers.ConvaD(filters=A_						,				kernel_size=1						,				activation='relu'						,				name='attention.0'     ),
											    tf.keras.layers.ConvaD(filters=A_						,				kernel_size=1						,				activation='sigmoid'						,				name='attention.2'     ),
											]







				def 						UpperCAmelCase_    (       self						,				A_     )->		Optional[int]:







											'''simple docstring'''






											UpperCamelCase   			=     self.pooler(A_     )
											for layer_module in self.attention:
																		UpperCamelCase   			=     layer_module(A_     )
											UpperCamelCase   			=     hidden_state * pooled
											return hidden_state


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







				def __init__(       self						,				A_						,				A_						,				A_						,				A_ = 1						,				**A_     )->		Dict:







											'''simple docstring'''






											super().__init__(**A_     )
											UpperCamelCase   			=     in_channels != out_channels or stride != 1
											UpperCamelCase   			=     max(1						,				out_channels // config.groups_width     )
											UpperCamelCase   			=     (
											    TFRegNetShortCut(A_						,				stride=A_						,				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   			=     [
											    TFRegNetConvLayer(A_						,				kernel_size=1						,				activation=config.hidden_act						,				name='layer.0'     ),
											    TFRegNetConvLayer(
											        A_						,				stride=A_						,				groups=A_						,				activation=config.hidden_act						,				name='layer.1'     ),
											    TFRegNetConvLayer(A_						,				kernel_size=1						,				activation=A_						,				name='layer.2'     ),
											]
											UpperCamelCase   			=     ACTaFN[config.hidden_act]







				def 						UpperCAmelCase_    (       self						,				A_     )->		Tuple:







											'''simple docstring'''






											UpperCamelCase   			=     hidden_state
											for layer_module in self.layers:
																		UpperCamelCase   			=     layer_module(A_     )
											UpperCamelCase   			=     self.shortcut(A_     )
											hidden_state += residual
											UpperCamelCase   			=     self.activation(A_     )
											return hidden_state


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







				def __init__(       self						,				A_						,				A_						,				A_						,				A_ = 1						,				**A_     )->		Any:







											'''simple docstring'''






											super().__init__(**A_     )
											UpperCamelCase   			=     in_channels != out_channels or stride != 1
											UpperCamelCase   			=     max(1						,				out_channels // config.groups_width     )
											UpperCamelCase   			=     (
											    TFRegNetShortCut(A_						,				stride=A_						,				name='shortcut'     )
											    if should_apply_shortcut
											    else tf.keras.layers.Activation('linear'						,				name='shortcut'     )
											)
											UpperCamelCase   			=     [
											    TFRegNetConvLayer(A_						,				kernel_size=1						,				activation=config.hidden_act						,				name='layer.0'     ),
											    TFRegNetConvLayer(
											        A_						,				stride=A_						,				groups=A_						,				activation=config.hidden_act						,				name='layer.1'     ),
											    TFRegNetSELayer(A_						,				reduced_channels=int(round(in_channels / 4     )     )						,				name='layer.2'     ),
											    TFRegNetConvLayer(A_						,				kernel_size=1						,				activation=A_						,				name='layer.3'     ),
											]
											UpperCamelCase   			=     ACTaFN[config.hidden_act]







				def 						UpperCAmelCase_    (       self						,				A_     )->		List[Any]:







											'''simple docstring'''






											UpperCamelCase   			=     hidden_state
											for layer_module in self.layers:
																		UpperCamelCase   			=     layer_module(A_     )
											UpperCamelCase   			=     self.shortcut(A_     )
											hidden_state += residual
											UpperCamelCase   			=     self.activation(A_     )
											return hidden_state


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







				def __init__(       self						,				A_						,				A_						,				A_						,				A_ = 2						,				A_ = 2						,				**A_     )->		Dict:







											'''simple docstring'''






											super().__init__(**A_     )

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







				def 						UpperCAmelCase_    (       self						,				A_     )->		List[Any]:







											'''simple docstring'''






											for layer_module in self.layers:
																		UpperCamelCase   			=     layer_module(A_     )
											return hidden_state


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







				def __init__(       self						,				A_						,				**A_     )->		str:







											'''simple docstring'''






											super().__init__(**A_     )
											UpperCamelCase   			=     []
											# based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
											self.stages.append(
											    TFRegNetStage(
											        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'						,				)     )
											UpperCamelCase   			=     zip(config.hidden_sizes						,				config.hidden_sizes[1:]     )
											for i, ((in_channels, out_channels), depth) in enumerate(zip(A_						,				config.depths[1:]     )     ):
																		self.stages.append(TFRegNetStage(A_						,				A_						,				A_						,				depth=A_						,				name=F'''stages.{i+1}'''     )     )







				def 						UpperCAmelCase_    (       self						,				A_						,				A_ = False						,				A_ = True     )->		TFBaseModelOutputWithNoAttention:







											'''simple docstring'''






											UpperCamelCase   			=     () if output_hidden_states else None

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

																		UpperCamelCase   			=     stage_module(A_     )

											if output_hidden_states:
																		UpperCamelCase   			=     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_     )


@keras_serializable
class 			SCREAMING_SNAKE_CASE__      (     tf.keras.layers.Layer):
				lowerCAmelCase_     			=							RegNetConfig







				def __init__(       self						,				A_						,				**A_     )->		Union[str, Any]:







											'''simple docstring'''






											super().__init__(**A_     )
											UpperCamelCase   			=     config
											UpperCamelCase   			=     TFRegNetEmbeddings(A_						,				name='embedder'     )
											UpperCamelCase   			=     TFRegNetEncoder(A_						,				name='encoder'     )
											UpperCamelCase   			=     tf.keras.layers.GlobalAveragePoolingaD(keepdims=A_						,				name='pooler'     )







				@unpack_inputs
				def 						UpperCAmelCase_    (       self						,				A_						,				A_ = None						,				A_ = None						,				A_ = False						,				)->		TFBaseModelOutputWithPoolingAndNoAttention:







											'''simple docstring'''






											UpperCamelCase   			=     (
											    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
											)
											UpperCamelCase   			=     return_dict if return_dict is not None else self.config.use_return_dict

											UpperCamelCase   			=     self.embedder(A_						,				training=A_     )

											UpperCamelCase   			=     self.encoder(
											    A_						,				output_hidden_states=A_						,				return_dict=A_						,				training=A_     )

											UpperCamelCase   			=     encoder_outputs[0]
											UpperCamelCase   			=     self.pooler(A_     )

											# Change to NCHW output format have uniformity in the modules
											UpperCamelCase   			=     tf.transpose(A_						,				perm=(0, 3, 1, 2)     )
											UpperCamelCase   			=     tf.transpose(A_						,				perm=(0, 3, 1, 2)     )

											# Change the other hidden state outputs to NCHW as well
											if output_hidden_states:
																		UpperCamelCase   			=     tuple([tf.transpose(A_						,				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=A_						,				pooler_output=A_						,				hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states						,				)


class 			SCREAMING_SNAKE_CASE__      (     snake_case_):
				lowerCAmelCase_     			=							RegNetConfig
				lowerCAmelCase_     			=							"""regnet"""
				lowerCAmelCase_     			=							"""pixel_values"""







				@property
				def 						UpperCAmelCase_    (       self     )->		List[str]:







											'''simple docstring'''






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


lowerCAmelCase					:    str           = r'\n    Parameters:\n    This model is a Tensorflow\n    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a\n    regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and\n    behavior.\n        config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.\n            Initializing with a config file does not load the weights associated with the model, only the\n            configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.\n'

lowerCAmelCase					:    List[str]           = r'\n    Args:\n        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):\n            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See\n            [`ConveNextImageProcessor.__call__`] for details.\n        output_hidden_states (`bool`, *optional*):\n            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for\n            more detail.\n        return_dict (`bool`, *optional*):\n            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.\n'


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







				def __init__(       self						,				A_						,				*A_						,				**A_     )->		List[Any]:







											'''simple docstring'''






											super().__init__(A_						,				*A_						,				**A_     )
											UpperCamelCase   			=     TFRegNetMainLayer(A_						,				name='regnet'     )







				@unpack_inputs
				@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						,				)
				def 						UpperCAmelCase_    (       self						,				A_						,				A_ = None						,				A_ = None						,				A_=False						,				)->		Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]:







											'''simple docstring'''






											UpperCamelCase   			=     (
											    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
											)
											UpperCamelCase   			=     return_dict if return_dict is not None else self.config.use_return_dict

											UpperCamelCase   			=     self.regnet(
											    pixel_values=A_						,				output_hidden_states=A_						,				return_dict=A_						,				training=A_						,				)
											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(
    """
    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    """							,       snake_case_							,       )
class 			SCREAMING_SNAKE_CASE__      (     snake_case_							,       snake_case_):







				def __init__(       self						,				A_						,				*A_						,				**A_     )->		str:







											'''simple docstring'''






											super().__init__(A_						,				*A_						,				**A_     )
											UpperCamelCase   			=     config.num_labels
											UpperCamelCase   			=     TFRegNetMainLayer(A_						,				name='regnet'     )
											# classification head
											UpperCamelCase   			=     [
											    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(A_     )
				@add_code_sample_docstrings(
				    checkpoint=_IMAGE_CLASS_CHECKPOINT						,				output_type=A_						,				config_class=_CONFIG_FOR_DOC						,				expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT						,				)
				def 						UpperCAmelCase_    (       self						,				A_ = None						,				A_ = None						,				A_ = None						,				A_ = None						,				A_=False						,				)->		Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:







											'''simple docstring'''






											UpperCamelCase   			=     (
											    output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
											)
											UpperCamelCase   			=     return_dict if return_dict is not None else self.config.use_return_dict

											UpperCamelCase   			=     self.regnet(
											    A_						,				output_hidden_states=A_						,				return_dict=A_						,				training=A_     )

											UpperCamelCase   			=     outputs.pooler_output if return_dict else outputs[1]

											UpperCamelCase   			=     self.classifier[0](A_     )
											UpperCamelCase   			=     self.classifier[1](A_     )

											UpperCamelCase   			=     None if labels is None else self.hf_compute_loss(labels=A_						,				logits=A_     )

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

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




