






"""simple docstring"""
import argparse
import os

from . import (
    ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    BART_PRETRAINED_MODEL_ARCHIVE_LIST,
    BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
    DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
    DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
    ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
    LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    T5_PRETRAINED_CONFIG_ARCHIVE_MAP,
    TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    XLM_PRETRAINED_CONFIG_ARCHIVE_MAP,
    XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
    AlbertConfig,
    BartConfig,
    BertConfig,
    CamembertConfig,
    CTRLConfig,
    DistilBertConfig,
    DPRConfig,
    ElectraConfig,
    FlaubertConfig,
    GPTaConfig,
    LayoutLMConfig,
    LxmertConfig,
    OpenAIGPTConfig,
    RobertaConfig,
    TaConfig,
    TFAlbertForPreTraining,
    TFBartForConditionalGeneration,
    TFBartForSequenceClassification,
    TFBertForPreTraining,
    TFBertForQuestionAnswering,
    TFBertForSequenceClassification,
    TFCamembertForMaskedLM,
    TFCTRLLMHeadModel,
    TFDistilBertForMaskedLM,
    TFDistilBertForQuestionAnswering,
    TFDPRContextEncoder,
    TFDPRQuestionEncoder,
    TFDPRReader,
    TFElectraForPreTraining,
    TFFlaubertWithLMHeadModel,
    TFGPTaLMHeadModel,
    TFLayoutLMForMaskedLM,
    TFLxmertForPreTraining,
    TFLxmertVisualFeatureEncoder,
    TFOpenAIGPTLMHeadModel,
    TFRobertaForCausalLM,
    TFRobertaForMaskedLM,
    TFRobertaForSequenceClassification,
    TFTaForConditionalGeneration,
    TFTransfoXLLMHeadModel,
    TFWavaVecaModel,
    TFXLMRobertaForMaskedLM,
    TFXLMWithLMHeadModel,
    TFXLNetLMHeadModel,
    TransfoXLConfig,
    WavaVecaConfig,
    WavaVecaModel,
    XLMConfig,
    XLMRobertaConfig,
    XLNetConfig,
    is_torch_available,
    load_pytorch_checkpoint_in_tfa_model,
)
from .utils import CONFIG_NAME, WEIGHTS_NAME, cached_file, logging


if is_torch_available():
			import numpy as np
			import torch

			from . import (
			    AlbertForPreTraining,
			    BartForConditionalGeneration,
			    BertForPreTraining,
			    BertForQuestionAnswering,
			    BertForSequenceClassification,
			    CamembertForMaskedLM,
			    CTRLLMHeadModel,
			    DistilBertForMaskedLM,
			    DistilBertForQuestionAnswering,
			    DPRContextEncoder,
			    DPRQuestionEncoder,
			    DPRReader,
			    ElectraForPreTraining,
			    FlaubertWithLMHeadModel,
			    GPTaLMHeadModel,
			    LayoutLMForMaskedLM,
			    LxmertForPreTraining,
			    LxmertVisualFeatureEncoder,
			    OpenAIGPTLMHeadModel,
			    RobertaForMaskedLM,
			    RobertaForSequenceClassification,
			    TaForConditionalGeneration,
			    TransfoXLLMHeadModel,
			    XLMRobertaForMaskedLM,
			    XLMWithLMHeadModel,
			    XLNetLMHeadModel,
			)


logging.set_verbosity_info()

lowerCamelCase_					=      {
    '''bart''': (
        BartConfig,
        TFBartForConditionalGeneration,
        TFBartForSequenceClassification,
        BartForConditionalGeneration,
        BART_PRETRAINED_MODEL_ARCHIVE_LIST,
    ),
    '''bert''': (
        BertConfig,
        TFBertForPreTraining,
        BertForPreTraining,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''bert-large-uncased-whole-word-masking-finetuned-squad''': (
        BertConfig,
        TFBertForQuestionAnswering,
        BertForQuestionAnswering,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''bert-large-cased-whole-word-masking-finetuned-squad''': (
        BertConfig,
        TFBertForQuestionAnswering,
        BertForQuestionAnswering,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''bert-base-cased-finetuned-mrpc''': (
        BertConfig,
        TFBertForSequenceClassification,
        BertForSequenceClassification,
        BERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''dpr''': (
        DPRConfig,
        TFDPRQuestionEncoder,
        TFDPRContextEncoder,
        TFDPRReader,
        DPRQuestionEncoder,
        DPRContextEncoder,
        DPRReader,
        DPR_CONTEXT_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
        DPR_QUESTION_ENCODER_PRETRAINED_MODEL_ARCHIVE_LIST,
        DPR_READER_PRETRAINED_MODEL_ARCHIVE_LIST,
    ),
    '''gpt2''': (
        GPTaConfig,
        TFGPTaLMHeadModel,
        GPTaLMHeadModel,
        GPT2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''xlnet''': (
        XLNetConfig,
        TFXLNetLMHeadModel,
        XLNetLMHeadModel,
        XLNET_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''xlm''': (
        XLMConfig,
        TFXLMWithLMHeadModel,
        XLMWithLMHeadModel,
        XLM_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''xlm-roberta''': (
        XLMRobertaConfig,
        TFXLMRobertaForMaskedLM,
        XLMRobertaForMaskedLM,
        XLM_ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''transfo-xl''': (
        TransfoXLConfig,
        TFTransfoXLLMHeadModel,
        TransfoXLLMHeadModel,
        TRANSFO_XL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''openai-gpt''': (
        OpenAIGPTConfig,
        TFOpenAIGPTLMHeadModel,
        OpenAIGPTLMHeadModel,
        OPENAI_GPT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''roberta''': (
        RobertaConfig,
        TFRobertaForCausalLM,
        TFRobertaForMaskedLM,
        RobertaForMaskedLM,
        ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''layoutlm''': (
        LayoutLMConfig,
        TFLayoutLMForMaskedLM,
        LayoutLMForMaskedLM,
        LAYOUTLM_PRETRAINED_MODEL_ARCHIVE_LIST,
    ),
    '''roberta-large-mnli''': (
        RobertaConfig,
        TFRobertaForSequenceClassification,
        RobertaForSequenceClassification,
        ROBERTA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''camembert''': (
        CamembertConfig,
        TFCamembertForMaskedLM,
        CamembertForMaskedLM,
        CAMEMBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''flaubert''': (
        FlaubertConfig,
        TFFlaubertWithLMHeadModel,
        FlaubertWithLMHeadModel,
        FLAUBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''distilbert''': (
        DistilBertConfig,
        TFDistilBertForMaskedLM,
        DistilBertForMaskedLM,
        DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''distilbert-base-distilled-squad''': (
        DistilBertConfig,
        TFDistilBertForQuestionAnswering,
        DistilBertForQuestionAnswering,
        DISTILBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''lxmert''': (
        LxmertConfig,
        TFLxmertForPreTraining,
        LxmertForPreTraining,
        LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''lxmert-visual-feature-encoder''': (
        LxmertConfig,
        TFLxmertVisualFeatureEncoder,
        LxmertVisualFeatureEncoder,
        LXMERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''ctrl''': (
        CTRLConfig,
        TFCTRLLMHeadModel,
        CTRLLMHeadModel,
        CTRL_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''albert''': (
        AlbertConfig,
        TFAlbertForPreTraining,
        AlbertForPreTraining,
        ALBERT_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''t5''': (
        TaConfig,
        TFTaForConditionalGeneration,
        TaForConditionalGeneration,
        T5_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''electra''': (
        ElectraConfig,
        TFElectraForPreTraining,
        ElectraForPreTraining,
        ELECTRA_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
    '''wav2vec2''': (
        WavaVecaConfig,
        TFWavaVecaModel,
        WavaVecaModel,
        WAV_2_VEC_2_PRETRAINED_CONFIG_ARCHIVE_MAP,
    ),
}

def 				snake_case      (   A__	,A__	,A__	,A__	,A__=False	,A__=True						):
			if model_type not in MODEL_CLASSES:
						raise ValueError(F"""Unrecognized model type, should be one of {list(MODEL_CLASSES.keys()						)}."""						)

			UpperCAmelCase_     ,	UpperCAmelCase_     ,	UpperCAmelCase_     ,	UpperCAmelCase_     : int			     =					MODEL_CLASSES[model_type]

			# Initialise TF model
			if config_file in aws_config_map:
						UpperCAmelCase_     : Tuple			     =					cached_file(A__	,A__	,force_download=not use_cached_models						)
			UpperCAmelCase_     : Dict			     =					config_class.from_json_file(A__						)
			UpperCAmelCase_     : int			     =					True
			UpperCAmelCase_     : Union[str, Any]			     =					True
			print(F"""Building TensorFlow model from configuration: {config}"""						)
			UpperCAmelCase_     : Optional[int]			     =					model_class(A__						)

			# Load weights from tf checkpoint
			if pytorch_checkpoint_path in aws_config_map.keys():
						UpperCAmelCase_     : Optional[Any]			     =					cached_file(
						    A__	,A__	,force_download=not use_cached_models						)
			# Load PyTorch checkpoint in tf2 model:
			UpperCAmelCase_     : Optional[Any]			     =					load_pytorch_checkpoint_in_tfa_model(A__	,A__						)

			if compare_with_pt_model:
						UpperCAmelCase_     : Optional[int]			     =					tf_model(tf_model.dummy_inputs	,training=A__						)  # build the network

						UpperCAmelCase_     : Tuple			     =					torch.load(A__	,map_location="cpu"						)
						UpperCAmelCase_     : str			     =					pt_model_class.from_pretrained(
						    pretrained_model_name_or_path=A__	,config=A__	,state_dict=A__						)

						with torch.no_grad():
									UpperCAmelCase_     : Any			     =					pt_model(**pt_model.dummy_inputs						)

						UpperCAmelCase_     : Tuple			     =					pto[0].numpy()
						UpperCAmelCase_     : Tuple			     =					tfo[0].numpy()
						UpperCAmelCase_     : Optional[int]			     =					np.amax(np.abs(np_pt - np_tf						)						)
						print(F"""Max absolute difference between models outputs {diff}"""						)
						assert diff <= 2e-2, F"""Error, model absolute difference is >2e-2: {diff}"""

			# Save pytorch-model
			print(F"""Save TensorFlow model to {tf_dump_path}"""						)
			tf_model.save_weights(A__	,save_format="h5"						)

def 				snake_case      (   A__	,A__	,A__=None	,A__=None	,A__=False	,A__=False	,A__=False	,A__=False	,):
			if args_model_type is None:
						UpperCAmelCase_     : List[str]			     =					list(MODEL_CLASSES.keys()						)
			else:
						UpperCAmelCase_     : int			     =					[args_model_type]

			for j, model_type in enumerate(A__	,start=1						):
						print("=" * 1_00						)
						print(F""" Converting model type {j}/{len(A__						)}: {model_type}"""						)
						print("=" * 1_00						)
						if model_type not in MODEL_CLASSES:
									raise ValueError(F"""Unrecognized model type {model_type}, should be one of {list(MODEL_CLASSES.keys()						)}."""						)

						UpperCAmelCase_     ,	UpperCAmelCase_     ,	UpperCAmelCase_     ,	UpperCAmelCase_     ,	UpperCAmelCase_     : str			     =					MODEL_CLASSES[model_type]

						if model_shortcut_names_or_path is None:
									UpperCAmelCase_     : Optional[int]			     =					list(aws_model_maps.keys()						)
						if config_shortcut_names_or_path is None:
									UpperCAmelCase_     : Dict			     =					model_shortcut_names_or_path

						for i, (model_shortcut_name, config_shortcut_name) in enumerate(
						    zip(A__	,A__						)	,start=1						):
									print("-" * 1_00						)
									if "-squad" in model_shortcut_name or "-mrpc" in model_shortcut_name or "-mnli" in model_shortcut_name:
												if not only_convert_finetuned_models:
															print(F"""    Skipping finetuned checkpoint {model_shortcut_name}"""						)
															continue
												UpperCAmelCase_     : Tuple			     =					model_shortcut_name
									elif only_convert_finetuned_models:
												print(F"""    Skipping not finetuned checkpoint {model_shortcut_name}"""						)
												continue
									print(
									    F"""    Converting checkpoint {i}/{len(A__						)}: {model_shortcut_name} - model_type {model_type}"""						)
									print("-" * 1_00						)

									if config_shortcut_name in aws_config_map:
												UpperCAmelCase_     : int			     =					cached_file(A__	,A__	,force_download=not use_cached_models						)
									else:
												UpperCAmelCase_     : Any			     =					config_shortcut_name

									if model_shortcut_name in aws_model_maps:
												UpperCAmelCase_     : Union[str, Any]			     =					cached_file(A__	,A__	,force_download=not use_cached_models						)
									else:
												UpperCAmelCase_     : Tuple			     =					model_shortcut_name

									if os.path.isfile(A__						):
												UpperCAmelCase_     : List[str]			     =					"converted_model"

									convert_pt_checkpoint_to_tf(
									    model_type=A__	,pytorch_checkpoint_path=A__	,config_file=A__	,tf_dump_path=os.path.join(A__	,model_shortcut_name + "-tf_model.h5"						)	,compare_with_pt_model=A__	,)
									if remove_cached_files:
												os.remove(A__						)
												os.remove(A__						)


if __name__ == "__main__":
			lowerCamelCase_					=      argparse.ArgumentParser()
			# Required parameters
			parser.add_argument(
			    '''--tf_dump_path''', default=None, type=str, required=True, help='''Path to the output Tensorflow dump file.'''
			)
			parser.add_argument(
			    '''--model_type''',
			    default=None,
			    type=str,
			    help=(
			        f'Model type selected in the list of {list(MODEL_CLASSES.keys())}. If not given, will download and '
			        '''convert all the models from AWS.'''
			    ),
			)
			parser.add_argument(
			    '''--pytorch_checkpoint_path''',
			    default=None,
			    type=str,
			    help=(
			        '''Path to the PyTorch checkpoint path or shortcut name to download from AWS. '''
			        '''If not given, will download and convert all the checkpoints from AWS.'''
			    ),
			)
			parser.add_argument(
			    '''--config_file''',
			    default=None,
			    type=str,
			    help=(
			        '''The config json file corresponding to the pre-trained model. \n'''
			        '''This specifies the model architecture. If not given and '''
			        '''--pytorch_checkpoint_path is not given or is a shortcut name '''
			        '''use the configuration associated to the shortcut name on the AWS'''
			    ),
			)
			parser.add_argument(
			    '''--compare_with_pt_model''', action='''store_true''', help='''Compare Tensorflow and PyTorch model predictions.'''
			)
			parser.add_argument(
			    '''--use_cached_models''',
			    action='''store_true''',
			    help='''Use cached models if possible instead of updating to latest checkpoint versions.''',
			)
			parser.add_argument(
			    '''--remove_cached_files''',
			    action='''store_true''',
			    help='''Remove pytorch models after conversion (save memory when converting in batches).''',
			)
			parser.add_argument('''--only_convert_finetuned_models''', action='''store_true''', help='''Only convert finetuned models.''')
			lowerCamelCase_					=      parser.parse_args()

			# if args.pytorch_checkpoint_path is not None:
			#     convert_pt_checkpoint_to_tf(args.model_type.lower(),
			#                                 args.pytorch_checkpoint_path,
			#                                 args.config_file if args.config_file is not None else args.pytorch_checkpoint_path,
			#                                 args.tf_dump_path,
			#                                 compare_with_pt_model=args.compare_with_pt_model,
			#                                 use_cached_models=args.use_cached_models)
			# else:
			convert_all_pt_checkpoints_to_tf(
			    args.model_type.lower() if args.model_type is not None else None,
			    args.tf_dump_path,
			    model_shortcut_names_or_path=[args.pytorch_checkpoint_path]
			    if args.pytorch_checkpoint_path is not None
			    else None,
			    config_shortcut_names_or_path=[args.config_file] if args.config_file is not None else None,
			    compare_with_pt_model=args.compare_with_pt_model,
			    use_cached_models=args.use_cached_models,
			    remove_cached_files=args.remove_cached_files,
			    only_convert_finetuned_models=args.only_convert_finetuned_models,
			)











"""simple docstring"""
from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import RegNetConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

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


if is_tf_available():
			import tensorflow as tf

			from transformers import TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST, TFRegNetForImageClassification, TFRegNetModel


if is_vision_available():
			from PIL import Image

			from transformers import AutoImageProcessor







class 			UpperCamelCase_       :





	def __init__(      self					: Optional[Any]	,	lowerCAmelCase_					: Optional[Any]	,	lowerCAmelCase_					: Optional[int]=3	,	lowerCAmelCase_					: Optional[int]=32	,	lowerCAmelCase_					: List[Any]=3	,	lowerCAmelCase_					: List[Any]=10	,	lowerCAmelCase_					: Any=[10, 20, 30, 40]	,	lowerCAmelCase_					: Any=[1, 1, 2, 1]	,	lowerCAmelCase_					: Union[str, Any]=True	,	lowerCAmelCase_					: Union[str, Any]=True	,	lowerCAmelCase_					: int="relu"	,	lowerCAmelCase_					: Tuple=3	,	lowerCAmelCase_					: Optional[int]=None	,	)						->			str:
				UpperCAmelCase_     : Tuple			     =					parent
				UpperCAmelCase_     : int			     =					batch_size
				UpperCAmelCase_     : str			     =					image_size
				UpperCAmelCase_     : List[Any]			     =					num_channels
				UpperCAmelCase_     : Tuple			     =					embeddings_size
				UpperCAmelCase_     : Union[str, Any]			     =					hidden_sizes
				UpperCAmelCase_     : int			     =					depths
				UpperCAmelCase_     : Optional[Any]			     =					is_training
				UpperCAmelCase_     : Dict			     =					use_labels
				UpperCAmelCase_     : str			     =					hidden_act
				UpperCAmelCase_     : str			     =					num_labels
				UpperCAmelCase_     : str			     =					scope
				UpperCAmelCase_     : str			     =					len(lowerCAmelCase_						)





	def      _SCREAMING_SNAKE_CASE      (      self					: Tuple						)						->			Dict:
				UpperCAmelCase_     : Any			     =					floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]						)

				UpperCAmelCase_     : Union[str, Any]			     =					None
				if self.use_labels:
							UpperCAmelCase_     : List[str]			     =					ids_tensor([self.batch_size]	,	self.num_labels						)

				UpperCAmelCase_     : Optional[Any]			     =					self.get_config()
				return config, pixel_values, labels





	def      _SCREAMING_SNAKE_CASE      (      self					: List[str]						)						->			Union[str, Any]:
				return RegNetConfig(
				    num_channels=self.num_channels	,	embeddings_size=self.embeddings_size	,	hidden_sizes=self.hidden_sizes	,	depths=self.depths	,	hidden_act=self.hidden_act	,	num_labels=self.num_labels	,	)





	def      _SCREAMING_SNAKE_CASE      (      self					: Optional[int]	,	lowerCAmelCase_					: Union[str, Any]	,	lowerCAmelCase_					: str	,	lowerCAmelCase_					: Dict						)						->			str:
				UpperCAmelCase_     : List[Any]			     =					TFRegNetModel(config=lowerCAmelCase_						)
				UpperCAmelCase_     : List[Any]			     =					model(lowerCAmelCase_	,	training=lowerCAmelCase_						)
				# expected last hidden states: B, C, H // 32, W // 32
				self.parent.assertEqual(
				    result.last_hidden_state.shape	,	(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)	,	)





	def      _SCREAMING_SNAKE_CASE      (      self					: Optional[int]	,	lowerCAmelCase_					: Tuple	,	lowerCAmelCase_					: Tuple	,	lowerCAmelCase_					: List[Any]						)						->			Optional[Any]:
				UpperCAmelCase_     : Union[str, Any]			     =					self.num_labels
				UpperCAmelCase_     : List[Any]			     =					TFRegNetForImageClassification(lowerCAmelCase_						)
				UpperCAmelCase_     : Optional[int]			     =					model(lowerCAmelCase_	,	labels=lowerCAmelCase_	,	training=lowerCAmelCase_						)
				self.parent.assertEqual(result.logits.shape	,	(self.batch_size, self.num_labels)						)





	def      _SCREAMING_SNAKE_CASE      (      self					: List[Any]						)						->			Dict:
				UpperCAmelCase_     : Any			     =					self.prepare_config_and_inputs()
				UpperCAmelCase_     ,	UpperCAmelCase_     ,	UpperCAmelCase_     : Dict			     =					config_and_inputs
				UpperCAmelCase_     : List[str]			     =					{"pixel_values": pixel_values}
				return config, inputs_dict







@require_tf
class 			UpperCamelCase_       (__A				,						__A				,						unittest.TestCase     ):
	__magic_name__	      =				(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
	__magic_name__	      =				(
	    {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification}
	    if is_tf_available()
	    else {}
	)

	__magic_name__	      =				False
	__magic_name__	      =				False
	__magic_name__	      =				False
	__magic_name__	      =				False
	__magic_name__	      =				False





	def      _SCREAMING_SNAKE_CASE      (      self					: Optional[int]						)						->			Union[str, Any]:
				UpperCAmelCase_     : Optional[int]			     =					TFRegNetModelTester(self						)
				UpperCAmelCase_     : Optional[Any]			     =					ConfigTester(self	,	config_class=lowerCAmelCase_	,	has_text_modality=lowerCAmelCase_						)





	def      _SCREAMING_SNAKE_CASE      (      self					: List[str]						)						->			Optional[int]:
				return





	@unittest.skip(reason="RegNet does not use inputs_embeds"						)
	def      _SCREAMING_SNAKE_CASE      (      self					: List[str]						)						->			Union[str, Any]:
				pass





	@unittest.skipIf(
	    not is_tf_available() or len(tf.config.list_physical_devices("GPU"						)						) == 0	,	reason="TF does not support backprop for grouped convolutions on CPU."	,	)
	@slow
	def      _SCREAMING_SNAKE_CASE      (      self					: List[str]						)						->			Dict:
				super().test_keras_fit()





	@unittest.skip(reason="RegNet does not support input and output embeddings"						)
	def      _SCREAMING_SNAKE_CASE      (      self					: List[str]						)						->			Any:
				pass





	def      _SCREAMING_SNAKE_CASE      (      self					: int						)						->			List[str]:
				UpperCAmelCase_     ,	UpperCAmelCase_     : Tuple			     =					self.model_tester.prepare_config_and_inputs_for_common()

				for model_class in self.all_model_classes:
							UpperCAmelCase_     : Dict			     =					model_class(lowerCAmelCase_						)
							UpperCAmelCase_     : Tuple			     =					inspect.signature(model.call						)
							# signature.parameters is an OrderedDict => so arg_names order is deterministic
							UpperCAmelCase_     : List[Any]			     =					[*signature.parameters.keys()]

							UpperCAmelCase_     : int			     =					["pixel_values"]
							self.assertListEqual(arg_names[:1]	,	lowerCAmelCase_						)





	def      _SCREAMING_SNAKE_CASE      (      self					: Union[str, Any]						)						->			Union[str, Any]:
				UpperCAmelCase_     : List[Any]			     =					self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_model(*lowerCAmelCase_						)





	def      _SCREAMING_SNAKE_CASE      (      self					: Optional[Any]						)						->			Optional[int]:
				def check_hidden_states_output(lowerCAmelCase_					: Optional[int]	,	lowerCAmelCase_					: Dict	,	lowerCAmelCase_					: int						):
							UpperCAmelCase_     : str			     =					model_class(lowerCAmelCase_						)
							UpperCAmelCase_     : Any			     =					model(**self._prepare_for_class(lowerCAmelCase_	,	lowerCAmelCase_						)	,	training=lowerCAmelCase_						)

							UpperCAmelCase_     : str			     =					outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

							UpperCAmelCase_     : Optional[Any]			     =					self.model_tester.num_stages
							self.assertEqual(len(lowerCAmelCase_						)	,	expected_num_stages + 1						)

							# RegNet's feature maps are of shape (batch_size, num_channels, height, width)
							self.assertListEqual(
							    list(hidden_states[0].shape[-2:]						)	,	[self.model_tester.image_size // 2, self.model_tester.image_size // 2]	,	)

				UpperCAmelCase_     ,	UpperCAmelCase_     : List[str]			     =					self.model_tester.prepare_config_and_inputs_for_common()
				UpperCAmelCase_     : Tuple			     =					["basic", "bottleneck"]
				for model_class in self.all_model_classes:
							for layer_type in layers_type:
										UpperCAmelCase_     : List[Any]			     =					layer_type
										UpperCAmelCase_     : int			     =					True
										check_hidden_states_output(lowerCAmelCase_	,	lowerCAmelCase_	,	lowerCAmelCase_						)

										# check that output_hidden_states also work using config
										del inputs_dict["output_hidden_states"]
										UpperCAmelCase_     : Optional[int]			     =					True

										check_hidden_states_output(lowerCAmelCase_	,	lowerCAmelCase_	,	lowerCAmelCase_						)





	def      _SCREAMING_SNAKE_CASE      (      self					: Union[str, Any]						)						->			Any:
				UpperCAmelCase_     ,	UpperCAmelCase_     : Any			     =					self.model_tester.prepare_config_and_inputs_for_common()

				def check_equivalence(lowerCAmelCase_					: Optional[Any]	,	lowerCAmelCase_					: Tuple	,	lowerCAmelCase_					: Optional[Any]	,	lowerCAmelCase_					: List[str]={}						):
							UpperCAmelCase_     : Tuple			     =					model(lowerCAmelCase_	,	return_dict=lowerCAmelCase_	,	**lowerCAmelCase_						)
							UpperCAmelCase_     : Optional[Any]			     =					model(lowerCAmelCase_	,	return_dict=lowerCAmelCase_	,	**lowerCAmelCase_						).to_tuple()

							def recursive_check(lowerCAmelCase_					: List[Any]	,	lowerCAmelCase_					: Any						):
										if isinstance(lowerCAmelCase_	,	(List, Tuple)						):
													for tuple_iterable_value, dict_iterable_value in zip(lowerCAmelCase_	,	lowerCAmelCase_						):
																recursive_check(lowerCAmelCase_	,	lowerCAmelCase_						)
										elif tuple_object is None:
													return
										else:
													self.assertTrue(
													    all(tf.equal(lowerCAmelCase_	,	lowerCAmelCase_						)						)	,	msg=(
													        "Tuple and dict output are not equal. Difference:"
													        f""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object						)						)}"""
													    )	,	)

										recursive_check(lowerCAmelCase_	,	lowerCAmelCase_						)

				for model_class in self.all_model_classes:
							UpperCAmelCase_     : Union[str, Any]			     =					model_class(lowerCAmelCase_						)

							UpperCAmelCase_     : List[Any]			     =					self._prepare_for_class(lowerCAmelCase_	,	lowerCAmelCase_						)
							UpperCAmelCase_     : str			     =					self._prepare_for_class(lowerCAmelCase_	,	lowerCAmelCase_						)
							check_equivalence(lowerCAmelCase_	,	lowerCAmelCase_	,	lowerCAmelCase_						)

							UpperCAmelCase_     : Any			     =					self._prepare_for_class(lowerCAmelCase_	,	lowerCAmelCase_	,	return_labels=lowerCAmelCase_						)
							UpperCAmelCase_     : List[Any]			     =					self._prepare_for_class(lowerCAmelCase_	,	lowerCAmelCase_	,	return_labels=lowerCAmelCase_						)
							check_equivalence(lowerCAmelCase_	,	lowerCAmelCase_	,	lowerCAmelCase_						)

							UpperCAmelCase_     : Union[str, Any]			     =					self._prepare_for_class(lowerCAmelCase_	,	lowerCAmelCase_						)
							UpperCAmelCase_     : str			     =					self._prepare_for_class(lowerCAmelCase_	,	lowerCAmelCase_						)
							check_equivalence(lowerCAmelCase_	,	lowerCAmelCase_	,	lowerCAmelCase_	,	{"output_hidden_states": True}						)

							UpperCAmelCase_     : List[str]			     =					self._prepare_for_class(lowerCAmelCase_	,	lowerCAmelCase_	,	return_labels=lowerCAmelCase_						)
							UpperCAmelCase_     : Tuple			     =					self._prepare_for_class(lowerCAmelCase_	,	lowerCAmelCase_	,	return_labels=lowerCAmelCase_						)
							check_equivalence(lowerCAmelCase_	,	lowerCAmelCase_	,	lowerCAmelCase_	,	{"output_hidden_states": True}						)





	def      _SCREAMING_SNAKE_CASE      (      self					: Union[str, Any]						)						->			str:
				UpperCAmelCase_     : List[str]			     =					self.model_tester.prepare_config_and_inputs()
				self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase_						)





	@slow
	def      _SCREAMING_SNAKE_CASE      (      self					: str						)						->			Union[str, Any]:
				for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							UpperCAmelCase_     : Any			     =					TFRegNetModel.from_pretrained(lowerCAmelCase_						)
							self.assertIsNotNone(lowerCAmelCase_						)





def 				snake_case      (   ):
			UpperCAmelCase_     : Dict			     =					Image.open("./tests/fixtures/tests_samples/COCO/000000039769.png"						)
			return image







@require_tf
@require_vision
class 			UpperCamelCase_       (unittest.TestCase     ):





	@cached_property
	def      _SCREAMING_SNAKE_CASE      (      self					: List[Any]						)						->			List[Any]:
				return (
				    AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)
				    if is_vision_available()
				    else None
				)





	@slow
	def      _SCREAMING_SNAKE_CASE      (      self					: Tuple						)						->			Dict:
				UpperCAmelCase_     : Any			     =					TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]						)

				UpperCAmelCase_     : Union[str, Any]			     =					self.default_image_processor
				UpperCAmelCase_     : int			     =					prepare_img()
				UpperCAmelCase_     : List[Any]			     =					image_processor(images=lowerCAmelCase_	,	return_tensors="tf"						)

				# forward pass
				UpperCAmelCase_     : Tuple			     =					model(**lowerCAmelCase_	,	training=lowerCAmelCase_						)

				# verify the logits
				UpperCAmelCase_     : List[str]			     =					tf.TensorShape((1, 1_000)						)
				self.assertEqual(outputs.logits.shape	,	lowerCAmelCase_						)

				UpperCAmelCase_     : Optional[Any]			     =					tf.constant([-0.4_1_8_0, -1.5_0_5_1, -3.4_8_3_6]						)

				tf.debugging.assert_near(outputs.logits[0, :3]	,	lowerCAmelCase_	,	atol=1e-4						)



