



import math
import os
import re
import sys
import unittest
from pathlib import Path
from typing import Tuple
from unittest.mock import patch

from parameterized import parameterized

from transformers.testing_utils import (
    CaptureStderr,
    ExtendSysPath,
    TestCasePlus,
    execute_subprocess_async,
    get_gpu_count,
    get_torch_dist_unique_port,
    require_apex,
    require_bitsandbytes,
    require_fairscale,
    require_torch,
    require_torch_gpu,
    require_torch_multi_gpu,
    require_torch_non_multi_gpu,
    slow,
)
from transformers.trainer_callback import TrainerState
from transformers.trainer_utils import set_seed


__SCREAMING_SNAKE_CASE           =  os.path.abspath(os.path.dirname(__file__))
with ExtendSysPath(F"""{bindir}/../../examples/pytorch/translation"""):
       from run_translation import main  # noqa


set_seed(42)
__SCREAMING_SNAKE_CASE           =  """sshleifer/student_marian_en_ro_6_1"""
__SCREAMING_SNAKE_CASE           =  """sshleifer/tiny-mbart"""

@require_torch
class 	lowerCamelCase_    ( _A						):






      '''simple docstring'''







      def 			SCREAMING_SNAKE_CASE__		(	self      :			Optional[int]	,	__lowerCamelCase      :			Optional[Any]=False	,	__lowerCamelCase      :			str=None	,	__lowerCamelCase      :			List[str]=True	,	__lowerCamelCase      :			str=True	,	__lowerCamelCase      :			List[Any]=True	,	__lowerCamelCase      :			Optional[int]=True	,	)      ->				Dict:
         A							:					str              =						self.run_trainer(
             eval_steps=1	,	max_len=12	,	model_name=__lowerCamelCase	,	num_train_epochs=1	,	distributed=__lowerCamelCase	,	extra_args_str=__lowerCamelCase	,	predict_with_generate=__lowerCamelCase	,	do_train=__lowerCamelCase	,	do_eval=__lowerCamelCase	,	do_predict=__lowerCamelCase	,	)
         A							:					Dict              =						TrainerState.load_from_json(os.path.join(__lowerCamelCase	,	"trainer_state.json" ) ).log_history

         if not do_eval:
            return

         A							:					List[Any]              =						[log for log in logs if "eval_loss" in log.keys()]

         A							:					Any              =						eval_metrics[0]
         if predict_with_generate:
            assert "eval_bleu" in first_step_stats

            A							:					List[str]              =						eval_metrics[-1]
            assert isinstance(last_step_stats["eval_bleu"]	,	__lowerCamelCase )
            assert not math.isnan(float(last_step_stats["eval_loss"] ) ), "eval_loss must not be `nan`"







      @require_torch_non_multi_gpu
      def 			SCREAMING_SNAKE_CASE__		(	self      :			Tuple )      ->				List[Any]:
         self.run_seqaseq_quick()







      @require_torch_multi_gpu
      def 			SCREAMING_SNAKE_CASE__		(	self      :			List[str] )      ->				int:
         self.run_seqaseq_quick(distributed=__lowerCamelCase )







      @require_torch_multi_gpu
      def 			SCREAMING_SNAKE_CASE__		(	self      :			Optional[int] )      ->				str:
         self.run_seqaseq_quick(distributed=__lowerCamelCase )







      @unittest.skip("Requires an update of the env running those tests" )
      @require_torch_multi_gpu
      @require_fairscale
      def 			SCREAMING_SNAKE_CASE__		(	self      :			List[str] )      ->				List[Any]:
         self.run_seqaseq_quick(distributed=__lowerCamelCase	,	extra_args_str="--sharded_ddp simple" )







      @unittest.skip("Requires an update of the env running those tests" )
      @require_torch_multi_gpu
      @require_fairscale
      def 			SCREAMING_SNAKE_CASE__		(	self      :			Tuple )      ->				str:
         self.run_seqaseq_quick(distributed=__lowerCamelCase	,	extra_args_str="--sharded_ddp simple --fp16" )







      @unittest.skip("Requires an update of the env running those tests" )
      @require_torch_multi_gpu
      @require_fairscale
      def 			SCREAMING_SNAKE_CASE__		(	self      :			List[str] )      ->				int:
         self.run_seqaseq_quick(distributed=__lowerCamelCase	,	extra_args_str="--sharded_ddp zero_dp_2"	,	predict_with_generate=__lowerCamelCase )







      @unittest.skip("Requires an update of the env running those tests" )
      @require_torch_multi_gpu
      @require_fairscale
      def 			SCREAMING_SNAKE_CASE__		(	self      :			Optional[Any] )      ->				List[str]:
         self.run_seqaseq_quick(
             distributed=__lowerCamelCase	,	extra_args_str="--sharded_ddp zero_dp_2 --fp16"	,	predict_with_generate=__lowerCamelCase )







      @require_apex
      @require_torch_gpu
      def 			SCREAMING_SNAKE_CASE__		(	self      :			int )      ->				Dict:
         # XXX: apex breaks the trainer if it's run twice e.g. run_seq2seq.main() from the same
         # program and it breaks other tests that run from the same pytest worker, therefore until this is
         # sorted out it must be run only in an external program, that is distributed=True in this
         # test and only under one or more gpus - if we want cpu will need to make a special test
         #
         # specifically to the problem traced it to self.optimizer.step() - if it's run 2nd time via
         # 2nd main() call it botches the future eval.
         #
         self.run_seqaseq_quick(distributed=__lowerCamelCase	,	extra_args_str="--fp16 --fp16_backend=apex" )
         # test 2nd time - was getting eval_loss': nan'
         # to reproduce the problem set distributed=False
         self.run_seqaseq_quick(distributed=__lowerCamelCase	,	extra_args_str="--fp16 --fp16_backend=apex" )







      @parameterized.expand(["base", "low", "high", "mixed"] )
      @require_torch_multi_gpu
      def 			SCREAMING_SNAKE_CASE__		(	self      :			str	,	__lowerCamelCase      :			List[str] )      ->				Tuple:
         # as each sub-test is slow-ish split into multiple sub-tests to avoid CI timeout
         A							:					Dict              =						{
             # test with the default log_level - should be info and thus log info once
             "base": {"extra_args_str": "", "n_matches": 1},
             # test with low log_level and log_level_replica - should be noisy on all processes
             # now the info string should appear twice on 2 processes
             "low": {"extra_args_str": "--log_level debug --log_level_replica debug", "n_matches": 2},
             # test with high log_level and low log_level_replica
             # now the info string should appear once only on the replica
             "high": {"extra_args_str": "--log_level error --log_level_replica debug", "n_matches": 1},
             # test with high log_level and log_level_replica - should be quiet on all processes
             "mixed": {"extra_args_str": "--log_level error --log_level_replica error", "n_matches": 0},
         }

         A							:					List[str]              =						experiments[experiment_id]
         A							:					Union[str, Any]              =						{"distributed": True, "predict_with_generate": False, "do_eval": False, "do_predict": False}
         A							:					Union[str, Any]              =						"Running training"
         with CaptureStderr() as cl:
            self.run_seqaseq_quick(**__lowerCamelCase	,	extra_args_str=data["extra_args_str"] )
         A							:					Dict              =						len(re.findall(__lowerCamelCase	,	cl.err ) )
         self.assertEqual(__lowerCamelCase	,	data["n_matches"] )







      @slow
      def 			SCREAMING_SNAKE_CASE__		(	self      :			Optional[int] )      ->				Optional[int]:
         A							:					int              =						self.run_trainer(
             eval_steps=2	,	max_len=1_28	,	model_name=__lowerCamelCase	,	learning_rate=3e-4	,	num_train_epochs=10	,	distributed=__lowerCamelCase	,	)

         # Check metrics
         A							:					str              =						TrainerState.load_from_json(os.path.join(__lowerCamelCase	,	"trainer_state.json" ) ).log_history
         A							:					Dict              =						[log for log in logs if "eval_loss" in log.keys()]
         A							:					Dict              =						eval_metrics[0]
         A							:					int              =						eval_metrics[-1]

         assert first_step_stats["eval_loss"] > last_step_stats["eval_loss"], "model learned nothing"
         assert isinstance(last_step_stats["eval_bleu"]	,	__lowerCamelCase )

         # test if do_predict saves generations and metrics
         A							:					Optional[Any]              =						os.listdir(__lowerCamelCase )
         A							:					Any              =						{os.path.basename(__lowerCamelCase ) for p in contents}
         assert "generated_predictions.txt" in contents
         assert "predict_results.json" in contents







      @slow
      @require_bitsandbytes
      def 			SCREAMING_SNAKE_CASE__		(	self      :			Dict )      ->				List[str]:
         from transformers.training_args import OptimizerNames

         def train_and_return_metrics(__lowerCamelCase      :			str ) -> Tuple[int, float]:
            A							:					Optional[int]              =						"--skip_memory_metrics 0"

            A							:					str              =						self.run_trainer(
                max_len=1_28	,	model_name=__lowerCamelCase	,	learning_rate=3e-4	,	num_train_epochs=1	,	optim=__lowerCamelCase	,	distributed=__lowerCamelCase	,	extra_args_str=__lowerCamelCase	,	do_eval=__lowerCamelCase	,	do_predict=__lowerCamelCase	,	n_gpus_to_use=1	,	)

            # Check metrics
            A							:					Union[str, Any]              =						TrainerState.load_from_json(Path(__lowerCamelCase	,	"trainer_state.json" ) ).log_history
            A							:					str              =						int(logs[0]["train_mem_gpu_peaked_delta"] / 2**20 )
            A							:					List[Any]              =						int(logs[0]["train_mem_gpu_alloc_delta"] / 2**20 )

            A							:					int              =						logs[0]["train_loss"]
            return gpu_peak_mem_mb, gpu_alloc_mem_mb, loss

         A							:					int              =						train_and_return_metrics(OptimizerNames.ADAMW_TORCH.value )
         A							:					Optional[int]              =						train_and_return_metrics(OptimizerNames.ADAMW_BNB.value )

         A							:					Tuple              =						gpu_alloc_mem_orig - gpu_alloc_mem_bnb

         A							:					Dict              =						gpu_peak_mem_orig + gpu_alloc_mem_orig
         A							:					Dict              =						gpu_peak_mem_bnb + gpu_alloc_mem_bnb
         A							:					int              =						gpu_total_mem_orig - gpu_total_mem_bnb

         # sshleifer/student_marian_en_ro_6_1 has 54M parameter, 29M of which is `nn.Embedding` which
         # doesn't get quantized and remains in fp32. Therefore we only have 25M parameters quantized
         # in 2 bytes and the diff in optim memory usage is derived as so:
         #
         # - normal 25*8=~200MB (8 bytes per param)
         # - bnb    25*2= ~50MB (2 bytes per param)
         #
         # Thus we should expect ~150MB total memory saved.
         #
         # Peak memory should be the same - the total should be different by about that same margin
         #
         # After leaving a small margin to accommodate for differences between gpus let's check
         # that we have at least 120MB in savings
         A							:					Tuple              =						1_20

         # uncomment the following if this test starts failing - requires py38 for a new print feature
         # gpu_peak_mem_diff = gpu_peak_mem_orig - gpu_peak_mem_bnb
         # print(f"{gpu_alloc_mem_orig=}MB {gpu_peak_mem_orig=}MB {gpu_alloc_mem_orig+gpu_peak_mem_orig=}MB")
         # print(f" {gpu_alloc_mem_bnb=}MB  {gpu_peak_mem_bnb=}MB  {gpu_alloc_mem_bnb+gpu_peak_mem_bnb=}MB")
         # print(f"{gpu_alloc_mem_diff=}MB")
         # print(f"{gpu_peak_mem_diff=}MB")
         # print(f"{gpu_total_mem_orig=}MB, {gpu_total_mem_bnb=}MB")
         # print(f"{gpu_total_mem_diff=}MB, {gpu_total_mem_diff=}MB")

         self.assertGreater(
             __lowerCamelCase	,	__lowerCamelCase	,	"should use ~150MB less alloc gpu memory with BNB, compared to without it for this model but got"
             F""" a difference of {gpu_alloc_mem_diff}MB, with gpu_alloc_mem_orig={gpu_alloc_mem_orig}MB and"""
             F""" gpu_alloc_mem_bnb={gpu_alloc_mem_bnb}MB"""	,	)

         self.assertGreater(
             __lowerCamelCase	,	__lowerCamelCase	,	"should use ~150MB less total gpu memory with BNB, compared to without it for this model but got"
             F""" a difference of {gpu_total_mem_diff}MB, with gpu_total_mem_orig={gpu_total_mem_orig}MB and"""
             F""" gpu_total_mem_bnb={gpu_total_mem_bnb}MB"""	,	)

         self.assertEqual(
             __lowerCamelCase	,	__lowerCamelCase	,	F"""loss should be the same, but got loss_orig={loss_orig}, loss_bnb={loss_bnb}""" )







      def 			SCREAMING_SNAKE_CASE__		(	self      :			str	,	__lowerCamelCase      :			int	,	__lowerCamelCase      :			str	,	__lowerCamelCase      :			int	,	__lowerCamelCase      :			float = 3e-3	,	__lowerCamelCase      :			str = "adafactor"	,	__lowerCamelCase      :			bool = False	,	__lowerCamelCase      :			str = None	,	__lowerCamelCase      :			int = 0	,	__lowerCamelCase      :			bool = True	,	__lowerCamelCase      :			bool = True	,	__lowerCamelCase      :			bool = True	,	__lowerCamelCase      :			bool = True	,	__lowerCamelCase      :			int = None	,	)      ->				List[str]:
         A							:					Optional[int]              =						self.test_file_dir / "../fixtures/tests_samples/wmt_en_ro"
         A							:					Optional[int]              =						self.get_auto_remove_tmp_dir()
         A							:					int              =						F"""
            --model_name_or_path {model_name}
            --train_file {data_dir}/train.json
            --validation_file {data_dir}/val.json
            --test_file {data_dir}/test.json
            --output_dir {output_dir}
            --overwrite_output_dir
            --max_train_samples 8
            --max_source_length {max_len}
            --max_target_length {max_len}
            --do_train
            --num_train_epochs {str(__lowerCamelCase )}
            --per_device_train_batch_size 4
            --learning_rate {learning_rate}
            --warmup_steps 8
            --logging_steps 0
            --logging_strategy no
            --save_steps {str(__lowerCamelCase )}
            --group_by_length
            --label_smoothing_factor 0.1
            --target_lang ro_RO
            --source_lang en_XX
        """.split()

         A							:					Optional[Any]              =						F"""
            --do_eval
            --per_device_eval_batch_size 4
            --max_eval_samples 8
            --val_max_target_length {max_len}
            --evaluation_strategy steps
            --eval_steps {str(__lowerCamelCase )}
        """.split()

         A							:					Optional[Any]              =						"\n            --do_predict\n        ".split()

         A							:					Optional[int]              =						[]
         if do_train:
            args += args_train

         if do_eval:
            args += args_eval

         if do_predict:
            args += args_predict

         if predict_with_generate:
            args += "--predict_with_generate".split()

         if do_train:
            if optim == "adafactor":
               args += "--adafactor".split()
            else:
               args += F"""--optim {optim}""".split()

         if extra_args_str is not None:
            args += extra_args_str.split()

         if distributed:
            if n_gpus_to_use is None:
               A							:					Dict              =						get_gpu_count()
            A							:					Any              =						get_torch_dist_unique_port()
            A							:					Optional[Any]              =						F"""
                -m torch.distributed.run
                --nproc_per_node={n_gpus_to_use}
                --master_port={master_port}
                {self.examples_dir_str}/pytorch/translation/run_translation.py
            """.split()
            A							:					Any              =						[sys.executable] + distributed_args + args
            # keep for quick debug
            # print(" ".join([f"\nPYTHONPATH={self.src_dir_str}"] +cmd)); die
            execute_subprocess_async(__lowerCamelCase	,	env=self.get_env() )
         else:
            A							:					List[Any]              =						["run_translation.py"] + args
            with patch.object(__lowerCamelCase	,	"argv"	,	__lowerCamelCase ):
               main()

         return output_dir




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 	lowerCamelCase_    :






						'''simple docstring'''







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







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Dict )      ->				List[Any]:
									A							:					str              =						floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size] )

									A							:					Optional[Any]              =						None
									if self.use_labels:
												A							:					Any              =						ids_tensor([self.batch_size]	,	self.num_labels )

									A							:					List[Any]              =						self.get_config()
									return config, pixel_values, labels







						def 			SCREAMING_SNAKE_CASE__		(	self      :			List[str] )      ->				int:
									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      :			Union[str, Any]	,	__lowerCamelCase      :			Dict	,	__lowerCamelCase      :			List[str]	,	__lowerCamelCase      :			Union[str, Any] )      ->				Tuple:
									A							:					List[str]              =						TFRegNetModel(config=__lowerCamelCase )
									A							:					str              =						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[Any]	,	__lowerCamelCase      :			Optional[Any]	,	__lowerCamelCase      :			Any	,	__lowerCamelCase      :			Tuple )      ->				List[str]:
									A							:					List[Any]              =						self.num_labels
									A							:					int              =						TFRegNetForImageClassification(__lowerCamelCase )
									A							:					str              =						model(__lowerCamelCase	,	labels=__lowerCamelCase	,	training=__lowerCamelCase )
									self.parent.assertEqual(result.logits.shape	,	(self.batch_size, self.num_labels) )







						def 			SCREAMING_SNAKE_CASE__		(	self      :			str )      ->				Dict:
									A							:					Any              =						self.prepare_config_and_inputs()
									A       , A       , A							:					str              =						config_and_inputs
									A							:					Any              =						{"pixel_values": pixel_values}
									return config, inputs_dict







@require_tf
class 	lowerCamelCase_    ( _A						,_A						,unittest.TestCase						):






						'''simple docstring'''
						a__   =  (TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
						a__   =  (
						    {"feature-extraction": TFRegNetModel, "image-classification": TFRegNetForImageClassification}
						    if is_tf_available()
						    else {}
						)

						a__   =  False
						a__   =  False
						a__   =  False
						a__   =  False
						a__   =  False







						def 			SCREAMING_SNAKE_CASE__		(	self      :			str )      ->				List[str]:
									A							:					Optional[Any]              =						TFRegNetModelTester(self )
									A							:					int              =						ConfigTester(self	,	config_class=__lowerCamelCase	,	has_text_modality=__lowerCamelCase )







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Optional[Any] )      ->				Tuple:
									return







						@unittest.skip(reason="RegNet does not use inputs_embeds" )
						def 			SCREAMING_SNAKE_CASE__		(	self      :			Optional[int] )      ->				Optional[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      :			str )      ->				Any:
									super().test_keras_fit()







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







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Union[str, Any] )      ->				Tuple:
									A       , A							:					List[str]              =						self.model_tester.prepare_config_and_inputs_for_common()

									for model_class in self.all_model_classes:
												A							:					Union[str, Any]              =						model_class(__lowerCamelCase )
												A							:					int              =						inspect.signature(model.call )
												# signature.parameters is an OrderedDict => so arg_names order is deterministic
												A							:					Union[str, Any]              =						[*signature.parameters.keys()]

												A							:					Optional[int]              =						["pixel_values"]
												self.assertListEqual(arg_names[:1]	,	__lowerCamelCase )







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Tuple )      ->				Tuple:
									A							:					Tuple              =						self.model_tester.prepare_config_and_inputs()
									self.model_tester.create_and_check_model(*__lowerCamelCase )







						def 			SCREAMING_SNAKE_CASE__		(	self      :			str )      ->				List[str]:
									def check_hidden_states_output(__lowerCamelCase      :			Union[str, Any]	,	__lowerCamelCase      :			Optional[Any]	,	__lowerCamelCase      :			str ):
												A							:					int              =						model_class(__lowerCamelCase )
												A							:					int              =						model(**self._prepare_for_class(__lowerCamelCase	,	__lowerCamelCase )	,	training=__lowerCamelCase )

												A							:					Any              =						outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

												A							:					Dict              =						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]	,	)

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

															# check that output_hidden_states also work using config
															del inputs_dict["output_hidden_states"]
															A							:					Union[str, Any]              =						True

															check_hidden_states_output(__lowerCamelCase	,	__lowerCamelCase	,	__lowerCamelCase )







						def 			SCREAMING_SNAKE_CASE__		(	self      :			Any )      ->				Dict:
									A       , A							:					Tuple              =						self.model_tester.prepare_config_and_inputs_for_common()

									def check_equivalence(__lowerCamelCase      :			int	,	__lowerCamelCase      :			List[str]	,	__lowerCamelCase      :			Dict	,	__lowerCamelCase      :			Optional[Any]={} ):
												A							:					Optional[int]              =						model(__lowerCamelCase	,	return_dict=__lowerCamelCase	,	**__lowerCamelCase )
												A							:					int              =						model(__lowerCamelCase	,	return_dict=__lowerCamelCase	,	**__lowerCamelCase ).to_tuple()

												def recursive_check(__lowerCamelCase      :			List[str]	,	__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:
												A							:					Tuple              =						model_class(__lowerCamelCase )

												A							:					Optional[int]              =						self._prepare_for_class(__lowerCamelCase	,	__lowerCamelCase )
												A							:					Tuple              =						self._prepare_for_class(__lowerCamelCase	,	__lowerCamelCase )
												check_equivalence(__lowerCamelCase	,	__lowerCamelCase	,	__lowerCamelCase )

												A							:					Optional[int]              =						self._prepare_for_class(__lowerCamelCase	,	__lowerCamelCase	,	return_labels=__lowerCamelCase )
												A							:					List[Any]              =						self._prepare_for_class(__lowerCamelCase	,	__lowerCamelCase	,	return_labels=__lowerCamelCase )
												check_equivalence(__lowerCamelCase	,	__lowerCamelCase	,	__lowerCamelCase )

												A							:					Optional[Any]              =						self._prepare_for_class(__lowerCamelCase	,	__lowerCamelCase )
												A							:					str              =						self._prepare_for_class(__lowerCamelCase	,	__lowerCamelCase )
												check_equivalence(__lowerCamelCase	,	__lowerCamelCase	,	__lowerCamelCase	,	{"output_hidden_states": True} )

												A							:					Optional[Any]              =						self._prepare_for_class(__lowerCamelCase	,	__lowerCamelCase	,	return_labels=__lowerCamelCase )
												A							:					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] )      ->				Optional[Any]:
									A							:					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      :			Any )      ->				Union[str, Any]:
									for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
												A							:					Union[str, Any]              =						TFRegNetModel.from_pretrained(__lowerCamelCase )
												self.assertIsNotNone(__lowerCamelCase )







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






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






						'''simple docstring'''







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







						@slow
						def 			SCREAMING_SNAKE_CASE__		(	self      :			Dict )      ->				Optional[Any]:
									A							:					List[Any]              =						TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0] )

									A							:					Optional[int]              =						self.default_image_processor
									A							:					List[Any]              =						prepare_img()
									A							:					str              =						image_processor(images=__lowerCamelCase	,	return_tensors="tf" )

									# forward pass
									A							:					List[Any]              =						model(**__lowerCamelCase	,	training=__lowerCamelCase )

									# verify the logits
									A							:					Dict              =						tf.TensorShape((1, 10_00) )
									self.assertEqual(outputs.logits.shape	,	__lowerCamelCase )

									A							:					Optional[Any]              =						tf.constant([-0.4180, -1.5051, -3.4836] )

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