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







							'''simple docstring'''

							def __init__(self    ,    UpperCAmelCase    ,    UpperCAmelCase=3    ,    UpperCAmelCase=32    ,    UpperCAmelCase=3    ,    UpperCAmelCase=10    ,    UpperCAmelCase=[10, 20, 30, 40]    ,    UpperCAmelCase=[1, 1, 2, 1]    ,    UpperCAmelCase=True    ,    UpperCAmelCase=True    ,    UpperCAmelCase="relu"    ,    UpperCAmelCase=3    ,    UpperCAmelCase=None    ,    )	->  Tuple:
														_snake_case  =    parent
														_snake_case  =    batch_size
														_snake_case  =    image_size
														_snake_case  =    num_channels
														_snake_case  =    embeddings_size
														_snake_case  =    hidden_sizes
														_snake_case  =    depths
														_snake_case  =    is_training
														_snake_case  =    use_labels
														_snake_case  =    hidden_act
														_snake_case  =    num_labels
														_snake_case  =    scope
														_snake_case  =    len(SCREAMING_SNAKE_CASE__    )

							def 			lowercase				(self    )	->  Tuple:
														_snake_case  =    floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

														_snake_case  =    None
														if self.use_labels:
																					_snake_case  =    ids_tensor([self.batch_size]    ,    self.num_labels    )

														_snake_case  =    self.get_config()
														return config, pixel_values, labels

							def 			lowercase				(self    )	->  Dict:
														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 			lowercase				(self    ,    UpperCAmelCase    ,    UpperCAmelCase    ,    UpperCAmelCase    )	->  Optional[int]:
														_snake_case  =    TFRegNetModel(config=SCREAMING_SNAKE_CASE__    )
														_snake_case  =    model(SCREAMING_SNAKE_CASE__    ,    training=SCREAMING_SNAKE_CASE__    )
														# 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 			lowercase				(self    ,    UpperCAmelCase    ,    UpperCAmelCase    ,    UpperCAmelCase    )	->  str:
														_snake_case  =    self.num_labels
														_snake_case  =    TFRegNetForImageClassification(SCREAMING_SNAKE_CASE__    )
														_snake_case  =    model(SCREAMING_SNAKE_CASE__    ,    labels=SCREAMING_SNAKE_CASE__    ,    training=SCREAMING_SNAKE_CASE__    )
														self.parent.assertEqual(result.logits.shape    ,    (self.batch_size, self.num_labels)    )





							def 			lowercase				(self    )	->  Union[str, Any]:
														_snake_case  =    self.prepare_config_and_inputs()
														_snake_case,				_snake_case,				_snake_case  =    config_and_inputs
														_snake_case  =    {"""pixel_values""": pixel_values}
														return config, inputs_dict


@require_tf
class      _lowerCAmelCase       (       __snake_case	,				__snake_case	,				unittest.TestCase ):







							'''simple docstring'''

							lowerCAmelCase_   		=		(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
							lowerCAmelCase_   		=		(
							    {"feature-extraction": TFRegNetModel, "image-classification": TFRegNetForImageClassification}
							    if is_tf_available()
							    else {}
							)

							lowerCAmelCase_   		=		False
							lowerCAmelCase_   		=		False
							lowerCAmelCase_   		=		False
							lowerCAmelCase_   		=		False
							lowerCAmelCase_   		=		False

							def 			lowercase				(self    )	->  List[Any]:
														_snake_case  =    TFRegNetModelTester(self    )
														_snake_case  =    ConfigTester(self    ,    config_class=SCREAMING_SNAKE_CASE__    ,    has_text_modality=SCREAMING_SNAKE_CASE__    )

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

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

							@unittest.skip(reason="""RegNet does not support input and output embeddings"""    )
							def 			lowercase				(self    )	->  Optional[int]:
														pass

							def 			lowercase				(self    )	->  Optional[Any]:
														_snake_case,				_snake_case  =    self.model_tester.prepare_config_and_inputs_for_common()

														for model_class in self.all_model_classes:
																					_snake_case  =    model_class(SCREAMING_SNAKE_CASE__    )
																					_snake_case  =    inspect.signature(model.call    )
																					# signature.parameters is an OrderedDict => so arg_names order is deterministic
																					_snake_case  =    [*signature.parameters.keys()]

																					_snake_case  =    ["""pixel_values"""]
																					self.assertListEqual(arg_names[:1]    ,    SCREAMING_SNAKE_CASE__    )

							def 			lowercase				(self    )	->  Any:
														_snake_case  =    self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_model(*SCREAMING_SNAKE_CASE__    )

							def 			lowercase				(self    )	->  Optional[Any]:



														def check_hidden_states_output(UpperCAmelCase    ,    UpperCAmelCase    ,    UpperCAmelCase    ):
																					_snake_case  =    model_class(SCREAMING_SNAKE_CASE__    )
																					_snake_case  =    model(**self._prepare_for_class(SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    )    ,    training=SCREAMING_SNAKE_CASE__    )

																					_snake_case  =    outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																					_snake_case  =    self.model_tester.num_stages
																					self.assertEqual(len(SCREAMING_SNAKE_CASE__    )    ,    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]    ,    )

														_snake_case,				_snake_case  =    self.model_tester.prepare_config_and_inputs_for_common()
														_snake_case  =    ["""basic""", """bottleneck"""]
														for model_class in self.all_model_classes:
																					for layer_type in layers_type:
																												_snake_case  =    layer_type
																												_snake_case  =    True
																												check_hidden_states_output(SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    )

																												# check that output_hidden_states also work using config
																												del inputs_dict["output_hidden_states"]
																												_snake_case  =    True

																												check_hidden_states_output(SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    )

							def 			lowercase				(self    )	->  str:
														_snake_case,				_snake_case  =    self.model_tester.prepare_config_and_inputs_for_common()

														def check_equivalence(UpperCAmelCase    ,    UpperCAmelCase    ,    UpperCAmelCase    ,    UpperCAmelCase={}    ):
																					_snake_case  =    model(SCREAMING_SNAKE_CASE__    ,    return_dict=SCREAMING_SNAKE_CASE__    ,    **SCREAMING_SNAKE_CASE__    )
																					_snake_case  =    model(SCREAMING_SNAKE_CASE__    ,    return_dict=SCREAMING_SNAKE_CASE__    ,    **SCREAMING_SNAKE_CASE__    ).to_tuple()

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

																												recursive_check(SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    )

														for model_class in self.all_model_classes:
																					_snake_case  =    model_class(SCREAMING_SNAKE_CASE__    )

																					_snake_case  =    self._prepare_for_class(SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    )
																					_snake_case  =    self._prepare_for_class(SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    )
																					check_equivalence(SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    )

																					_snake_case  =    self._prepare_for_class(SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    ,    return_labels=SCREAMING_SNAKE_CASE__    )
																					_snake_case  =    self._prepare_for_class(SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    ,    return_labels=SCREAMING_SNAKE_CASE__    )
																					check_equivalence(SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    )

																					_snake_case  =    self._prepare_for_class(SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    )
																					_snake_case  =    self._prepare_for_class(SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    )
																					check_equivalence(SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    ,    {"""output_hidden_states""": True}    )

																					_snake_case  =    self._prepare_for_class(SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    ,    return_labels=SCREAMING_SNAKE_CASE__    )
																					_snake_case  =    self._prepare_for_class(SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    ,    return_labels=SCREAMING_SNAKE_CASE__    )
																					check_equivalence(SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    ,    SCREAMING_SNAKE_CASE__    ,    {"""output_hidden_states""": True}    )

							def 			lowercase				(self    )	->  int:
														_snake_case  =    self.model_tester.prepare_config_and_inputs()
														self.model_tester.create_and_check_for_image_classification(*SCREAMING_SNAKE_CASE__    )





							@slow
							def 			lowercase				(self    )	->  List[Any]:



														for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
																					_snake_case  =    TFRegNetModel.from_pretrained(SCREAMING_SNAKE_CASE__    )
																					self.assertIsNotNone(SCREAMING_SNAKE_CASE__    )






def    __SCREAMING_SNAKE_CASE (    ):
							_snake_case  =    Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png""" )
							return image


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







							'''simple docstring'''

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





							@slow
							def 			lowercase				(self    )	->  Any:
														_snake_case  =    TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]    )

														_snake_case  =    self.default_image_processor
														_snake_case  =    prepare_img()
														_snake_case  =    image_processor(images=SCREAMING_SNAKE_CASE__    ,    return_tensors="""tf"""    )

														# forward pass
														_snake_case  =    model(**SCREAMING_SNAKE_CASE__    ,    training=SCREAMING_SNAKE_CASE__    )

														# verify the logits
														_snake_case  =    tf.TensorShape((1, 1000)    )
														self.assertEqual(outputs.logits.shape    ,    SCREAMING_SNAKE_CASE__    )

														_snake_case  =    tf.constant([-0.4180, -1.5051, -3.4836]    )

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

import json
import os
import tempfile

from transformers.testing_utils import check_json_file_has_correct_format
class       _lowerCAmelCase  :

 """simple docstring"""
 SCREAMING_SNAKE_CASE_				:					Optional[Any]       						=None

 def      __lowerCAmelCase  (						self			:			Union[str, Any]   ):






      """simple docstring"""



      UpperCamelCase						    =					self.feature_extraction_class(**self.feat_extract_dict   )
      UpperCamelCase						    =					json.loads(feat_extract.to_json_string()   )
      for key, value in self.feat_extract_dict.items():
           self.assertEqual(obj[key]					, SCREAMING_SNAKE_CASE__   )

 def      __lowerCAmelCase  (						self			:			Tuple   ):






      """simple docstring"""



      UpperCamelCase						    =					self.feature_extraction_class(**self.feat_extract_dict   )

      with tempfile.TemporaryDirectory() as tmpdirname:
           UpperCamelCase						    =					os.path.join(SCREAMING_SNAKE_CASE__					, 'feat_extract.json'   )
           feat_extract_first.to_json_file(SCREAMING_SNAKE_CASE__   )
           UpperCamelCase						    =					self.feature_extraction_class.from_json_file(SCREAMING_SNAKE_CASE__   )

      self.assertEqual(feat_extract_second.to_dict()					, feat_extract_first.to_dict()   )

 def      __lowerCAmelCase  (						self			:			Tuple   ):






      """simple docstring"""



      UpperCamelCase						    =					self.feature_extraction_class(**self.feat_extract_dict   )

      with tempfile.TemporaryDirectory() as tmpdirname:
           UpperCamelCase						    =					feat_extract_first.save_pretrained(SCREAMING_SNAKE_CASE__   )[0]
           check_json_file_has_correct_format(SCREAMING_SNAKE_CASE__   )
           UpperCamelCase						    =					self.feature_extraction_class.from_pretrained(SCREAMING_SNAKE_CASE__   )

      self.assertEqual(feat_extract_second.to_dict()					, feat_extract_first.to_dict()   )






 def      __lowerCAmelCase  (						self			:			Union[str, Any]   ):






      """simple docstring"""



      UpperCamelCase						    =					self.feature_extraction_class()
      self.assertIsNotNone(SCREAMING_SNAKE_CASE__   )


