





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 							_UpperCAmelCase       (       unittest.TestCase       ):

  """simple docstring"""


  def __init__(							self					:						List[str]   ,    lowerCAmelCase_					:						Optional[int]   ,    lowerCAmelCase_					:						Optional[int]=3   ,    lowerCAmelCase_					:						Dict=3_2   ,    lowerCAmelCase_					:						Tuple=3   ,    lowerCAmelCase_					:						Union[str, Any]=1_0   ,    lowerCAmelCase_					:						List[str]=[1_0, 2_0, 3_0, 4_0]   ,    lowerCAmelCase_					:						Optional[int]=[1, 1, 2, 1]   ,    lowerCAmelCase_					:						Union[str, Any]=True   ,    lowerCAmelCase_					:						Any=True   ,    lowerCAmelCase_					:						Tuple="relu"   ,    lowerCAmelCase_					:						Union[str, Any]=3   ,    lowerCAmelCase_					:						Optional[int]=None   ,    )				->		int:
     __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 							lowercase						(							self					:						Optional[int]	)				->		List[Any]:
     __lowerCAmelCase				      =      floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]	)

     __lowerCAmelCase				      =      self.get_config()

     return config, pixel_values






  def 							lowercase						(							self					:						Tuple	)				->		List[Any]:
     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 							lowercase						(							self					:						List[str]   ,    lowerCAmelCase_					:						List[str]   ,    lowerCAmelCase_					:						List[str]	)				->		str:
     __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 							lowercase						(							self					:						str   ,    lowerCAmelCase_					:						Optional[int]   ,    lowerCAmelCase_					:						int	)				->		Tuple:
     __lowerCAmelCase				      =      self.num_labels
     __lowerCAmelCase				      =      FlaxRegNetForImageClassification(config=lowerCAmelCase_	)
     __lowerCAmelCase				      =      model(lowerCAmelCase_	)
     self.parent.assertEqual(result.logits.shape   ,    (self.batch_size, self.num_labels)	)






  def 							lowercase						(							self					:						List[Any]	)				->		Optional[Any]:
     __lowerCAmelCase				      =      self.prepare_config_and_inputs()
     __lowerCAmelCase      ,      __lowerCAmelCase				      =      config_and_inputs
     __lowerCAmelCase				      =      {'pixel_values': pixel_values}
     return config, inputs_dict





@require_flax
class 							_UpperCAmelCase       (       _UpperCamelCase						,       unittest.TestCase       ):

  """simple docstring"""


  a_              =					(FlaxRegNetModel, FlaxRegNetForImageClassification) if is_flax_available() else ()

  a_              =					False
  a_              =					False
  a_              =					False






  def 							lowercase						(							self					:						Dict	)				->		None:
     __lowerCAmelCase				      =      FlaxRegNetModelTester(self	)
     __lowerCAmelCase				      =      ConfigTester(self   ,    config_class=lowerCAmelCase_   ,    has_text_modality=lowerCAmelCase_	)






  def 							lowercase						(							self					:						int	)				->		Optional[int]:
     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 							lowercase						(							self					:						str	)				->		Union[str, Any]:
     return






  def 							lowercase						(							self					:						Dict	)				->		str:
     __lowerCAmelCase				      =      self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_model(*lowerCAmelCase_	)






  def 							lowercase						(							self					:						Union[str, Any]	)				->		Tuple:
     __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 							lowercase						(							self					:						Union[str, Any]	)				->		Any:
     pass






  @unittest.skip(reason='RegNet does not support input and output embeddings'	)
  def 							lowercase						(							self					:						Tuple	)				->		Tuple:
     pass






  def 							lowercase						(							self					:						Optional[Any]	)				->		str:
     __lowerCAmelCase      ,      __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 							lowercase						(							self					:						List[Any]	)				->		Union[str, Any]:
     def check_hidden_states_output(lowerCAmelCase_					:						Any   ,    lowerCAmelCase_					:						Tuple   ,    lowerCAmelCase_					:						Tuple	):
        __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      ,      __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 							lowercase						(							self					:						str	)				->		str:
     __lowerCAmelCase      ,      __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(lowerCAmelCase_					:						Optional[int]   ,    **lowerCAmelCase_					:						Dict	):
              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 							_UpperCAmelCase       (       unittest.TestCase       ):

  """simple docstring"""


  @cached_property
  def 							lowercase						(							self					:						Union[str, Any]	)				->		Optional[Any]:
     return AutoImageProcessor.from_pretrained('facebook/regnet-y-040'	) if is_vision_available() else None






  @slow
  def 							lowercase						(							self					:						Optional[Any]	)				->		Union[str, Any]:
     __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	)	)








'''simple docstring'''


from sklearn.metrics import mean_squared_error

import datasets


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

_SCREAMING_SNAKE_CASE									=				"\\nMean Squared Error(MSE) is the average of the square of difference between the predicted\nand actual values.\n"


_SCREAMING_SNAKE_CASE									=				"\nArgs:\n    predictions: array-like of shape (n_samples,) or (n_samples, n_outputs)\n        Estimated target values.\n    references: array-like of shape (n_samples,) or (n_samples, n_outputs)\n        Ground truth (correct) target values.\n    sample_weight: array-like of shape (n_samples,), default=None\n        Sample weights.\n    multioutput: {\"raw_values\", \"uniform_average\"} or array-like of shape (n_outputs,), default=\"uniform_average\"\n        Defines aggregating of multiple output values. Array-like value defines weights used to average errors.\n\n        \"raw_values\" : Returns a full set of errors in case of multioutput input.\n\n        \"uniform_average\" : Errors of all outputs are averaged with uniform weight.\n\n    squared : bool, default=True\n        If True returns MSE value, if False returns RMSE (Root Mean Squared Error) value.\n\nReturns:\n    mse : mean squared error.\nExamples:\n\n    >>> mse_metric = datasets.load_metric(\"mse\")\n    >>> predictions = [2.5, 0.0, 2, 8]\n    >>> references = [3, -0.5, 2, 7]\n    >>> results = mse_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'mse': 0.375}\n    >>> rmse_result = mse_metric.compute(predictions=predictions, references=references, squared=False)\n    >>> print(rmse_result)\n    {'mse': 0.6123724356957945}\n\n    If you're using multi-dimensional lists, then set the config as follows :\n\n    >>> mse_metric = datasets.load_metric(\"mse\", \"multilist\")\n    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n    >>> references = [[0, 2], [-1, 2], [8, -5]]\n    >>> results = mse_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {'mse': 0.7083333333333334}\n    >>> results = mse_metric.compute(predictions=predictions, references=references, multioutput='raw_values')\n    >>> print(results) # doctest: +NORMALIZE_WHITESPACE\n    {'mse': array([0.41666667, 1. ])}\n"

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




 def 				_snake_case (						self		)     ->				Dict:
     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 				_snake_case (						self		)     ->				Tuple:
     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 				_snake_case (						self      ,  _lowerCAmelCase      ,  _lowerCAmelCase      ,  _lowerCAmelCase=None      ,  _lowerCAmelCase="uniform_average"      ,  _lowerCAmelCase=True		)     ->				Union[str, Any]:
     _lowerCAmelCase						      =   mean_squared_error(
         _lowerCAmelCase      ,  _lowerCAmelCase      ,  sample_weight=_lowerCAmelCase      ,  multioutput=_lowerCAmelCase      ,  squared=_lowerCAmelCase		)

     return {"mse": mse}


