




import inspect
import unittest

from transformers import RegNetConfig, is_flax_available
from transformers.testing_utils import require_flax, slow
from transformers.utils import cached_property, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_flax_common import FlaxModelTesterMixin, floats_tensor


if is_flax_available():
					import jax
					import jax.numpy as jnp

					from transformers.models.regnet.modeling_flax_regnet import FlaxRegNetForImageClassification, FlaxRegNetModel

if is_vision_available():
					from PIL import Image

					from transformers import AutoImageProcessor
class       a__   ( unittest.TestCase				):






						def __init__(       self		,      _A		,      _A=3		,      _A=3_2		,      _A=3		,      _A=1_0		,      _A=[1_0, 2_0, 3_0, 4_0]		,      _A=[1, 1, 2, 1]		,      _A=True		,      _A=True		,      _A="relu"		,      _A=3		,      _A=None		,      ):




											"""simple docstring"""



											__lowerCAmelCase           =       parent
											__lowerCAmelCase           =       batch_size
											__lowerCAmelCase           =       image_size
											__lowerCAmelCase           =       num_channels
											__lowerCAmelCase           =       embeddings_size
											__lowerCAmelCase           =       hidden_sizes
											__lowerCAmelCase           =       depths
											__lowerCAmelCase           =       is_training
											__lowerCAmelCase           =       use_labels
											__lowerCAmelCase           =       hidden_act
											__lowerCAmelCase           =       num_labels
											__lowerCAmelCase           =       scope
											__lowerCAmelCase           =       len(lowerCAmelCase__      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =       floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]      )

											__lowerCAmelCase           =       self.get_config()

											return config, pixel_values






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""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		,      image_size=self.image_size		,      )






						def     __SCREAMING_SNAKE_CASE(       self		,      _A		,      _A      ):




											"""simple docstring"""



											__lowerCAmelCase           =       FlaxRegNetModel(config=lowerCAmelCase__      )
											__lowerCAmelCase           =       model(lowerCAmelCase__      )

											# Output shape (b, c, h, w)
											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     __SCREAMING_SNAKE_CASE(       self		,      _A		,      _A      ):




											"""simple docstring"""



											__lowerCAmelCase           =       self.num_labels
											__lowerCAmelCase           =       FlaxRegNetForImageClassification(config=lowerCAmelCase__      )
											__lowerCAmelCase           =       model(lowerCAmelCase__      )
											self.parent.assertEqual(result.logits.shape		,      (self.batch_size, self.num_labels)      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =       self.prepare_config_and_inputs()
											__lowerCAmelCase           =       config_and_inputs
											__lowerCAmelCase           =       {"pixel_values": pixel_values}
											return config, inputs_dict






@require_flax
class       a__   ( a__			,    unittest.TestCase				):
						_a							:   Optional[int] =   (FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

						_a							:   List[Any] =   False
						_a							:   Tuple =   False
						_a							:   Any =   False






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =       FlaxRegNetModelTester(self      )
											__lowerCAmelCase           =       ConfigTester(self		,      config_class=lowerCAmelCase__		,      has_text_modality=lowerCAmelCase__      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											self.create_and_test_config_common_properties()
											self.config_tester.create_and_test_config_to_json_string()
											self.config_tester.create_and_test_config_to_json_file()
											self.config_tester.create_and_test_config_from_and_save_pretrained()
											self.config_tester.create_and_test_config_with_num_labels()
											self.config_tester.check_config_can_be_init_without_params()
											self.config_tester.check_config_arguments_init()






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											return






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*lowerCAmelCase__      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =       self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*lowerCAmelCase__      )






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




											"""simple docstring"""



											pass






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




											"""simple docstring"""



											pass






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =       self.model_tester.prepare_config_and_inputs_for_common()

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

																__lowerCAmelCase           =       ["pixel_values"]
																self.assertListEqual(arg_names[:1]		,      lowerCAmelCase__      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											def check_hidden_states_output(_A		,      _A		,      _A      ):
																__lowerCAmelCase           =       model_class(lowerCAmelCase__      )

																__lowerCAmelCase           =       model(**self._prepare_for_class(lowerCAmelCase__		,      lowerCAmelCase__      )      )

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

																__lowerCAmelCase           =       self.model_tester.num_stages
																self.assertEqual(len(lowerCAmelCase__      )		,      expected_num_stages + 1      )

											__lowerCAmelCase           =       self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																__lowerCAmelCase           =       True
																check_hidden_states_output(lowerCAmelCase__		,      lowerCAmelCase__		,      lowerCAmelCase__      )

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

																check_hidden_states_output(lowerCAmelCase__		,      lowerCAmelCase__		,      lowerCAmelCase__      )






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =       self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																with self.subTest(model_class.__name__      ):
																					__lowerCAmelCase           =       self._prepare_for_class(lowerCAmelCase__		,      lowerCAmelCase__      )
																					__lowerCAmelCase           =       model_class(lowerCAmelCase__      )

																					@jax.jit
																					def model_jitted(_A		,      **_A      ):
																										return model(pixel_values=lowerCAmelCase__		,      **lowerCAmelCase__      )

																					with self.subTest("JIT Enabled"      ):
																										__lowerCAmelCase           =       model_jitted(**lowerCAmelCase__      ).to_tuple()

																					with self.subTest("JIT Disabled"      ):
																										with jax.disable_jit():
																															__lowerCAmelCase           =       model_jitted(**lowerCAmelCase__      ).to_tuple()

																					self.assertEqual(len(lowerCAmelCase__      )		,      len(lowerCAmelCase__      )      )
																					for jitted_output, output in zip(lowerCAmelCase__		,      lowerCAmelCase__      ):
																										self.assertEqual(jitted_output.shape		,      output.shape      )







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


@require_flax
class       a__   ( unittest.TestCase				):






						@cached_property
						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											return AutoImageProcessor.from_pretrained("facebook/regnet-y-040"      ) if is_vision_available() else None






						@slow
						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""simple docstring"""



											__lowerCAmelCase           =       FlaxRegNetForImageClassification.from_pretrained("facebook/regnet-y-040"      )

											__lowerCAmelCase           =       self.default_image_processor
											__lowerCAmelCase           =       prepare_img()
											__lowerCAmelCase           =       image_processor(images=lowerCAmelCase__		,      return_tensors="np"      )

											__lowerCAmelCase           =       model(**lowerCAmelCase__      )

											# verify the logits
											__lowerCAmelCase           =       (1, 1_0_0_0)
											self.assertEqual(outputs.logits.shape		,      lowerCAmelCase__      )

											__lowerCAmelCase           =       jnp.array([-0.41_80, -1.50_51, -3.48_36]      )

											self.assertTrue(jnp.allclose(outputs.logits[0, :3]		,      lowerCAmelCase__		,      atol=1E-4      )      )










from sklearn.metrics import mean_squared_error

import datasets


UpperCamelCase__         =      """\
@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__         =      """\
Mean Squared Error(MSE) is the average of the square of difference between the predicted
and actual values.
"""


UpperCamelCase__         =      """
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       a__   ( datasets.Metric				):






						def     __SCREAMING_SNAKE_CASE(       self      ):




											"""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     __SCREAMING_SNAKE_CASE(       self      ):




											"""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     __SCREAMING_SNAKE_CASE(       self		,      _A		,      _A		,      _A=None		,      _A="uniform_average"		,      _A=True      ):




											"""simple docstring"""



											__lowerCAmelCase           =	mean_squared_error(
											    _A		,      _A		,      sample_weight=_A		,      multioutput=_A		,      squared=_A      )

											return {"mse": mse}




