



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


			'''simple docstring'''

			def __init__(							self  :				int							,  lowerCAmelCase__  :				Optional[int]							,  lowerCAmelCase__  :				Any=3							,  lowerCAmelCase__  :				Tuple=3_2							,  lowerCAmelCase__  :				str=3							,  lowerCAmelCase__  :				List[str]=1_0							,  lowerCAmelCase__  :				Optional[int]=[1_0, 2_0, 3_0, 4_0]							,  lowerCAmelCase__  :				Dict=[1, 1, 2, 1]							,  lowerCAmelCase__  :				List[Any]=True							,  lowerCAmelCase__  :				Dict=True							,  lowerCAmelCase__  :				str="relu"							,  lowerCAmelCase__  :				str=3							,  lowerCAmelCase__  :				Optional[int]=None							,  ):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	str					 =	parent
					__SCREAMING_SNAKE_CASE :	Tuple					 =	batch_size
					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	image_size
					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	num_channels
					__SCREAMING_SNAKE_CASE :	Any					 =	embeddings_size
					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	hidden_sizes
					__SCREAMING_SNAKE_CASE :	int					 =	depths
					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	is_training
					__SCREAMING_SNAKE_CASE :	List[str]					 =	use_labels
					__SCREAMING_SNAKE_CASE :	str					 =	hidden_act
					__SCREAMING_SNAKE_CASE :	Union[str, Any]					 =	num_labels
					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	scope
					__SCREAMING_SNAKE_CASE :	Tuple					 =	len(lowerCAmelCase__		)

			def UpperCamelCase__      (							self  :				str		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]		)

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

					__SCREAMING_SNAKE_CASE :	Dict					 =	self.get_config()
					return config, pixel_values, labels

			def UpperCamelCase__      (							self  :				int		):





					"""simple docstring"""






					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 UpperCamelCase__      (							self  :				Union[str, Any]							,  lowerCAmelCase__  :				Optional[Any]							,  lowerCAmelCase__  :				List[Any]							,  lowerCAmelCase__  :				Tuple		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Any					 =	TFRegNetModel(config=lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	Tuple					 =	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 // 3_2, self.image_size // 3_2)							,  )

			def UpperCamelCase__      (							self  :				Any							,  lowerCAmelCase__  :				List[Any]							,  lowerCAmelCase__  :				Dict							,  lowerCAmelCase__  :				Optional[int]		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	int					 =	self.num_labels
					__SCREAMING_SNAKE_CASE :	List[str]					 =	TFRegNetForImageClassification(lowerCAmelCase__		)
					__SCREAMING_SNAKE_CASE :	str					 =	model(lowerCAmelCase__							,  labels=lowerCAmelCase__							,  training=lowerCAmelCase__		)
					self.parent.assertEqual(result.logits.shape							,  (self.batch_size, self.num_labels)		)



			def UpperCamelCase__      (							self  :				int		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	int					 =	self.prepare_config_and_inputs()
					__SCREAMING_SNAKE_CASE ,		__SCREAMING_SNAKE_CASE ,		__SCREAMING_SNAKE_CASE :	str					 =	config_and_inputs
					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	{"""pixel_values""": pixel_values}
					return config, inputs_dict






@require_tf
class 		_UpperCamelCase						(							lowerCamelCase__					,      lowerCamelCase__					,      unittest.TestCase					):


			'''simple docstring'''

			_A   :	Optional[int]    					=	(TFRegNetModel, TFRegNetForImageClassification) if is_tf_available() else ()
			_A   :	Tuple    					=	(
			    {'''feature-extraction''': TFRegNetModel, '''image-classification''': TFRegNetForImageClassification}
			    if is_tf_available()
			    else {}
			)

			_A   :	Union[str, Any]    					=	False
			_A   :	Union[str, Any]    					=	False
			_A   :	Union[str, Any]    					=	False
			_A   :	Optional[Any]    					=	False
			_A   :	str    					=	False

			def UpperCamelCase__      (							self  :				Optional[Any]		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	Any					 =	TFRegNetModelTester(self		)
					__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	ConfigTester(self							,  config_class=lowerCAmelCase__							,  has_text_modality=lowerCAmelCase__		)

			def UpperCamelCase__      (							self  :				Optional[int]		):





					"""simple docstring"""






					return

			@unittest.skip(reason="""RegNet does not use inputs_embeds"""		)
			def UpperCamelCase__      (							self  :				Dict		):





					"""simple docstring"""






					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 UpperCamelCase__      (							self  :				Tuple		):





					"""simple docstring"""






					super().test_keras_fit()

			@unittest.skip(reason="""RegNet does not support input and output embeddings"""		)
			def UpperCamelCase__      (							self  :				Optional[Any]		):





					"""simple docstring"""






					pass

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





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE ,		__SCREAMING_SNAKE_CASE :	Tuple					 =	self.model_tester.prepare_config_and_inputs_for_common()

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

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

			def UpperCamelCase__      (							self  :				int		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	str					 =	self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_model(*lowerCAmelCase__		)

			def UpperCamelCase__      (							self  :				Optional[Any]		):





					"""simple docstring"""






					def check_hidden_states_output(lowerCAmelCase__  :				List[str]							,  lowerCAmelCase__  :				Optional[Any]							,  lowerCAmelCase__  :				Optional[int]		):
							__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	model_class(lowerCAmelCase__		)
							__SCREAMING_SNAKE_CASE :	str					 =	model(**self._prepare_for_class(lowerCAmelCase__							,  lowerCAmelCase__		)							,  training=lowerCAmelCase__		)

							__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

							__SCREAMING_SNAKE_CASE :	str					 =	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]							,  )

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

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

									check_hidden_states_output(lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__		)

			def UpperCamelCase__      (							self  :				Optional[Any]		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE ,		__SCREAMING_SNAKE_CASE :	Tuple					 =	self.model_tester.prepare_config_and_inputs_for_common()

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

							def recursive_check(lowerCAmelCase__  :				Union[str, Any]							,  lowerCAmelCase__  :				Union[str, 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:
							__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	model_class(lowerCAmelCase__		)

							__SCREAMING_SNAKE_CASE :	int					 =	self._prepare_for_class(lowerCAmelCase__							,  lowerCAmelCase__		)
							__SCREAMING_SNAKE_CASE :	Optional[int]					 =	self._prepare_for_class(lowerCAmelCase__							,  lowerCAmelCase__		)
							check_equivalence(lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__		)

							__SCREAMING_SNAKE_CASE :	str					 =	self._prepare_for_class(lowerCAmelCase__							,  lowerCAmelCase__							,  return_labels=lowerCAmelCase__		)
							__SCREAMING_SNAKE_CASE :	Optional[Any]					 =	self._prepare_for_class(lowerCAmelCase__							,  lowerCAmelCase__							,  return_labels=lowerCAmelCase__		)
							check_equivalence(lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__		)

							__SCREAMING_SNAKE_CASE :	str					 =	self._prepare_for_class(lowerCAmelCase__							,  lowerCAmelCase__		)
							__SCREAMING_SNAKE_CASE :	List[str]					 =	self._prepare_for_class(lowerCAmelCase__							,  lowerCAmelCase__		)
							check_equivalence(lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  {"""output_hidden_states""": True}		)

							__SCREAMING_SNAKE_CASE :	int					 =	self._prepare_for_class(lowerCAmelCase__							,  lowerCAmelCase__							,  return_labels=lowerCAmelCase__		)
							__SCREAMING_SNAKE_CASE :	int					 =	self._prepare_for_class(lowerCAmelCase__							,  lowerCAmelCase__							,  return_labels=lowerCAmelCase__		)
							check_equivalence(lowerCAmelCase__							,  lowerCAmelCase__							,  lowerCAmelCase__							,  {"""output_hidden_states""": True}		)

			def UpperCamelCase__      (							self  :				Any		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	List[str]					 =	self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__		)



			@slow
			def UpperCamelCase__      (							self  :				List[Any]		):





					"""simple docstring"""






					for model_name in TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
							__SCREAMING_SNAKE_CASE :	List[Any]					 =	TFRegNetModel.from_pretrained(lowerCAmelCase__		)
							self.assertIsNotNone(lowerCAmelCase__		)


def        lowerCAmelCase_     (			):
		__SCREAMING_SNAKE_CASE :	List[str]					 =	Image.open("""./tests/fixtures/tests_samples/COCO/000000039769.png"""      )
		return image






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


			'''simple docstring'''

			@cached_property
			def UpperCamelCase__      (							self  :				Any		):





					"""simple docstring"""






					return (
					    AutoImageProcessor.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)
					    if is_vision_available()
					    else None
					)



			@slow
			def UpperCamelCase__      (							self  :				List[str]		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	List[Any]					 =	TFRegNetForImageClassification.from_pretrained(TF_REGNET_PRETRAINED_MODEL_ARCHIVE_LIST[0]		)

					__SCREAMING_SNAKE_CASE :	Any					 =	self.default_image_processor
					__SCREAMING_SNAKE_CASE :	Dict					 =	prepare_img()
					__SCREAMING_SNAKE_CASE :	int					 =	image_processor(images=lowerCAmelCase__							,  return_tensors="""tf"""		)

					# forward pass
					__SCREAMING_SNAKE_CASE :	Optional[int]					 =	model(**lowerCAmelCase__							,  training=lowerCAmelCase__		)

					# verify the logits
					__SCREAMING_SNAKE_CASE :	Dict					 =	tf.TensorShape((1, 1_0_0_0)		)
					self.assertEqual(outputs.logits.shape							,  lowerCAmelCase__		)

					__SCREAMING_SNAKE_CASE :	str					 =	tf.constant([-0.41_80, -1.50_51, -3.48_36]		)

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




'''simple docstring'''




from sklearn.metrics import mean_squared_error

import datasets


UpperCamelCase__ :			Optional[Any]												=				'''\
@article{scikit-learn,
 title={Scikit-learn: Machine Learning in {P}ython},
 author={Pedregosa, F. and Varoquaux, G. and Gramfort, A. and Michel, V.
         and Thirion, B. and Grisel, O. and Blondel, M. and Prettenhofer, P.
         and Weiss, R. and Dubourg, V. and Vanderplas, J. and Passos, A. and
         Cournapeau, D. and Brucher, M. and Perrot, M. and Duchesnay, E.},
 journal={Journal of Machine Learning Research},
 volume={12},
 pages={2825--2830},
 year={2011}
}
'''

UpperCamelCase__ :			List[str]												=				'''\
Mean Squared Error(MSE) is the average of the square of difference between the predicted
and actual values.
'''


UpperCamelCase__ :			Dict												=				'''
Args:
    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Estimated target values.
    references: array-like of shape (n_samples,) or (n_samples, n_outputs)
        Ground truth (correct) target values.
    sample_weight: array-like of shape (n_samples,), default=None
        Sample weights.
    multioutput: {"raw_values", "uniform_average"} or array-like of shape (n_outputs,), default="uniform_average"
        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.

        "raw_values" : Returns a full set of errors in case of multioutput input.

        "uniform_average" : Errors of all outputs are averaged with uniform weight.

    squared : bool, default=True
        If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.

Returns:
    mse : mean squared error.
Examples:

    >>> mse_metric = datasets.load_metric("mse")
    >>> predictions = [2.5, 0.0, 2, 8]
    >>> references = [3, -0.5, 2, 7]
    >>> results = mse_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'mse\': 0.375}
    >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)
    >>> print(rmse_result)
    {\'mse\': 0.6123724356957945}

    If you\'re using multi-dimensional lists, then set the config as follows :

    >>> mse_metric = datasets.load_metric("mse", "multilist")
    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]
    >>> references = [[0, 2], [-1, 2], [8, -5]]
    >>> results = mse_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {\'mse\': 0.7083333333333334}
    >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\')
    >>> print(results) # doctest: +NORMALIZE_WHITESPACE
    {\'mse\': array([0.41666667, 1. ])}
'''






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION					,      _KWARGS_DESCRIPTION					)
class 		_UpperCamelCase						(							datasets.Metric					):


			'''simple docstring'''

			def UpperCamelCase__      (							self  :				str		):





					"""simple docstring"""






					return datasets.MetricInfo(
					    description=_DESCRIPTION							,  citation=_CITATION							,  inputs_description=_KWARGS_DESCRIPTION							,  features=datasets.Features(self._get_feature_types()		)							,  reference_urls=[
					        """https://scikit-learn.org/stable/modules/generated/sklearn.metrics.mean_squared_error.html"""
					    ]							,  )

			def UpperCamelCase__      (							self  :				Optional[Any]		):





					"""simple docstring"""






					if self.config_name == "multilist":
							return {
							    "predictions": datasets.Sequence(datasets.Value("""float"""		)		),
							    "references": datasets.Sequence(datasets.Value("""float"""		)		),
							}
					else:
							return {
							    "predictions": datasets.Value("""float"""		),
							    "references": datasets.Value("""float"""		),
							}



			def UpperCamelCase__      (							self  :				List[Any]							,  lowerCAmelCase__  :				Any							,  lowerCAmelCase__  :				str							,  lowerCAmelCase__  :				List[Any]=None							,  lowerCAmelCase__  :				Optional[int]="uniform_average"							,  lowerCAmelCase__  :				int=True		):





					"""simple docstring"""






					__SCREAMING_SNAKE_CASE :	str					 =	mean_squared_error(
					    lowerCAmelCase__							,  lowerCAmelCase__							,  sample_weight=lowerCAmelCase__							,  multioutput=lowerCAmelCase__							,  squared=lowerCAmelCase__		)

					return {"mse": mse}