



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




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




				def 							A__ (  self   :  Optional[Any]  ):
							lowercase__   					=			floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]  )

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

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




				def 							A__ (  self   :  str  ):
							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 							A__ (  self   :  List[str],   __lowercase   :  int,   __lowercase   :  List[Any],   __lowercase   :  int  ):
							lowercase__   					=			TFRegNetModel(config=__lowercase  )
							lowercase__   					=			model(__lowercase,   training=__lowercase  )
							# 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 							A__ (  self   :  str,   __lowercase   :  List[Any],   __lowercase   :  List[Any],   __lowercase   :  Optional[Any]  ):
							lowercase__   					=			self.num_labels
							lowercase__   					=			TFRegNetForImageClassification(__lowercase  )
							lowercase__   					=			model(__lowercase,   labels=__lowercase,   training=__lowercase  )
							self.parent.assertEqual(result.logits.shape,   (self.batch_size, self.num_labels)  )




				def 							A__ (  self   :  Optional[int]  ):
							lowercase__   					=			self.prepare_config_and_inputs()
							lowercase__					,    lowercase__					,    lowercase__   					=			config_and_inputs
							lowercase__   					=			{"pixel_values": pixel_values}
							return config, inputs_dict
@require_tf
class 			_snake_case     (   lowercase__      ,		lowercase__      ,		unittest.TestCase):
				UpperCamelCase__			:   int       						=(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
				UpperCamelCase__			:   List[Any]       						=(
				    {"""feature-extraction""": TFRegNetModel, """image-classification""": TFRegNetForImageClassification}
				    if is_tf_available()
				    else {}
				)

				UpperCamelCase__			:   Tuple       						=False
				UpperCamelCase__			:   Optional[int]       						=False
				UpperCamelCase__			:   List[Any]       						=False
				UpperCamelCase__			:   List[Any]       						=False
				UpperCamelCase__			:   Dict       						=False




				def 							A__ (  self   :  List[str]  ):
							lowercase__   					=			TFRegNetModelTester(self  )
							lowercase__   					=			ConfigTester(self,   config_class=__lowercase,   has_text_modality=__lowercase  )




				def 							A__ (  self   :  List[str]  ):
							return




				@unittest.skip(reason="RegNet does not use inputs_embeds"  )
				def 							A__ (  self   :  Tuple  ):
							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 							A__ (  self   :  Any  ):
							super().test_keras_fit()




				@unittest.skip(reason="RegNet does not support input and output embeddings"  )
				def 							A__ (  self   :  int  ):
							pass




				def 							A__ (  self   :  int  ):
							lowercase__					,    lowercase__   					=			self.model_tester.prepare_config_and_inputs_for_common()

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

										lowercase__   					=			["pixel_values"]
										self.assertListEqual(arg_names[:1],   __lowercase  )




				def 							A__ (  self   :  Any  ):
							lowercase__   					=			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_model(*__lowercase  )




				def 							A__ (  self   :  Dict  ):
							def check_hidden_states_output(__lowercase   :  str,   __lowercase   :  Any,   __lowercase   :  Optional[int]  ):
										lowercase__   					=			model_class(__lowercase  )
										lowercase__   					=			model(**self._prepare_for_class(__lowercase,   __lowercase  ),   training=__lowercase  )

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

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

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

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

													check_hidden_states_output(__lowercase,   __lowercase,   __lowercase  )




				def 							A__ (  self   :  List[Any]  ):
							lowercase__					,    lowercase__   					=			self.model_tester.prepare_config_and_inputs_for_common()

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

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

													recursive_check(__lowercase,   __lowercase  )

							for model_class in self.all_model_classes:
										lowercase__   					=			model_class(__lowercase  )

										lowercase__   					=			self._prepare_for_class(__lowercase,   __lowercase  )
										lowercase__   					=			self._prepare_for_class(__lowercase,   __lowercase  )
										check_equivalence(__lowercase,   __lowercase,   __lowercase  )

										lowercase__   					=			self._prepare_for_class(__lowercase,   __lowercase,   return_labels=__lowercase  )
										lowercase__   					=			self._prepare_for_class(__lowercase,   __lowercase,   return_labels=__lowercase  )
										check_equivalence(__lowercase,   __lowercase,   __lowercase  )

										lowercase__   					=			self._prepare_for_class(__lowercase,   __lowercase  )
										lowercase__   					=			self._prepare_for_class(__lowercase,   __lowercase  )
										check_equivalence(__lowercase,   __lowercase,   __lowercase,   {"output_hidden_states": True}  )

										lowercase__   					=			self._prepare_for_class(__lowercase,   __lowercase,   return_labels=__lowercase  )
										lowercase__   					=			self._prepare_for_class(__lowercase,   __lowercase,   return_labels=__lowercase  )
										check_equivalence(__lowercase,   __lowercase,   __lowercase,   {"output_hidden_states": True}  )




				def 							A__ (  self   :  List[str]  ):
							lowercase__   					=			self.model_tester.prepare_config_and_inputs()
							self.model_tester.create_and_check_for_image_classification(*__lowercase  )




				@slow
				def 							A__ (  self   :  List[Any]  ):
							for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
										lowercase__   					=			TFRegNetModel.from_pretrained(__lowercase  )
										self.assertIsNotNone(__lowercase  )



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




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




				@cached_property
				def 							A__ (  self   :  Union[str, Any]  ):
							return (
							    AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )
							    if is_vision_available()
							    else None
							)




				@slow
				def 							A__ (  self   :  List[Any]  ):
							lowercase__   					=			TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]  )

							lowercase__   					=			self.default_image_processor
							lowercase__   					=			prepare_img()
							lowercase__   					=			image_processor(images=__lowercase,   return_tensors="tf"  )

							# forward pass
							lowercase__   					=			model(**__lowercase,   training=__lowercase  )

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

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

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









import re

import jax.numpy as jnp
from flax.traverse_util import flatten_dict, unflatten_dict
from jax.random import PRNGKey

from ..utils import logging


lowercase_						=       logging.get_logger(__name__)



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_					):
			lowercase__   					=			r"\w+[.]\d+"
			lowercase__   					=			re.findall(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					)
			for pat in pats:
						lowercase__   					=			key.replace(SCREAMING_SNAKE_CASE_  ,					"_".join(pat.split("."					)					)					)
			return key



def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					):
			lowercase__   					=			pt_tuple_key[:-1] + ("scale",)
			if (
			    any("norm" in str_ for str_ in pt_tuple_key					)
			    and (pt_tuple_key[-1] == "bias")
			    and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict)
			    and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict)
			):
						lowercase__   					=			pt_tuple_key[:-1] + ("scale",)
						return renamed_pt_tuple_key, pt_tensor
			elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict:
						lowercase__   					=			pt_tuple_key[:-1] + ("scale",)
						return renamed_pt_tuple_key, pt_tensor

			# embedding
			if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict:
						lowercase__   					=			pt_tuple_key[:-1] + ("embedding",)
						return renamed_pt_tuple_key, pt_tensor

			# conv layer
			lowercase__   					=			pt_tuple_key[:-1] + ("kernel",)
			if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4:
						lowercase__   					=			pt_tensor.transpose(2  ,					3  ,					1  ,					0					)
						return renamed_pt_tuple_key, pt_tensor

			# linear layer
			lowercase__   					=			pt_tuple_key[:-1] + ("kernel",)
			if pt_tuple_key[-1] == "weight":
						lowercase__   					=			pt_tensor.T
						return renamed_pt_tuple_key, pt_tensor

			# old PyTorch layer norm weight
			lowercase__   					=			pt_tuple_key[:-1] + ("weight",)
			if pt_tuple_key[-1] == "gamma":
						return renamed_pt_tuple_key, pt_tensor

			# old PyTorch layer norm bias
			lowercase__   					=			pt_tuple_key[:-1] + ("bias",)
			if pt_tuple_key[-1] == "beta":
						return renamed_pt_tuple_key, pt_tensor

			return pt_tuple_key, pt_tensor




def __lowerCAmelCase	(       SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_=42					):
			# Step 1: Convert pytorch tensor to numpy
			lowercase__   					=			{k: v.numpy() for k, v in pt_state_dict.items()}

			# Step 2: Since the model is stateless, get random Flax params
			lowercase__   					=			flax_model.init_weights(PRNGKey(SCREAMING_SNAKE_CASE_					)					)

			lowercase__   					=			flatten_dict(SCREAMING_SNAKE_CASE_					)
			lowercase__   					=			{}

			# Need to change some parameters name to match Flax names
			for pt_key, pt_tensor in pt_state_dict.items():
						lowercase__   					=			rename_key(SCREAMING_SNAKE_CASE_					)
						lowercase__   					=			tuple(renamed_pt_key.split("."					)					)

						# Correctly rename weight parameters
						lowercase__					,    lowercase__   					=			rename_key_and_reshape_tensor(SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_  ,					SCREAMING_SNAKE_CASE_					)

						if flax_key in random_flax_state_dict:
									if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
												raise ValueError(
												    f'''PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape '''
												    f'''{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}.'''					)

        # also add unexpected weight so that warning is thrown
						lowercase__   					=			jnp.asarray(SCREAMING_SNAKE_CASE_					)

			return unflatten_dict(SCREAMING_SNAKE_CASE_					)




