






"""simple docstring"""



from sklearn.metrics import mean_squared_error

import datasets


_lowerCAmelCase	:	Tuple				=      """\
@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}
}
"""

_lowerCAmelCase	:	int				=      """\
Mean Squared Error(MSE) is the average of the square of difference between the predicted
and actual values.
"""


_lowerCAmelCase	:	Tuple				=      """
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 			lowerCAmelCase__			(    datasets.Metric   ):
   def       __a							(		self      :	Union[str, Any]							):


        '''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       __a							(		self      :	List[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       __a							(		self      :	Optional[Any]							,			snake_case__      :	Optional[int]							,			snake_case__      :	List[str]							,			snake_case__      :	str=None							,			snake_case__      :	str="uniform_average"							,			snake_case__      :	int=True							):


        '''simple docstring'''
        UpperCAmelCase__						:    str							=							mean_squared_error(
            snake_case__							,			snake_case__							,			sample_weight=snake_case__							,			multioutput=snake_case__							,			squared=snake_case__							)

        return {"mse": mse}










"""simple docstring"""



import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_sentencepiece, require_tokenizers, require_torch, slow


if is_torch_available():
 import torch

 from transformers import XLMRobertaModel




@require_sentencepiece
@require_tokenizers
@require_torch
class 			lowerCAmelCase__			(    unittest.TestCase   ):
   @slow
   def       __a							(		self      :	Tuple							):


        '''simple docstring'''
        UpperCAmelCase__						:    List[str]							=							XLMRobertaModel.from_pretrained("xlm-roberta-base"							)
        UpperCAmelCase__						:    str							=							torch.tensor([[0, 5_8_1, 1_0_2_6_9, 8_3, 9_9_9_4_2, 1_3_6, 6_0_7_4_2, 2_3, 7_0, 8_0_5_8_3, 1_8_2_7_6, 2]]							)
        # The dog is cute and lives in the garden house

        UpperCAmelCase__						:    Tuple							=							torch.Size((1, 1_2, 7_6_8)							)  # batch_size, sequence_length, embedding_vector_dim
        UpperCAmelCase__						:    Optional[int]							=							torch.tensor(
            [[-0.0101, 0.1218, -0.0803, 0.0801, 0.1327, 0.0776, -0.1215, 0.2383, 0.3338, 0.3106, 0.0300, 0.0252]]							)
        #  xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.base')
        #  xlmr.eval()
        #  expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1]
        with torch.no_grad():
             UpperCAmelCase__						:    int							=							model(snake_case__							)["last_hidden_state"].detach()
        self.assertEqual(output.shape							,			snake_case__							)
        # compare the actual values for a slice of last dim
        self.assertTrue(torch.allclose(output[:, :, -1]							,			snake_case__							,			atol=1e-3							)							)




   @slow
   def       __a							(		self      :	Optional[Any]							):


        '''simple docstring'''
        UpperCAmelCase__						:    Any							=							XLMRobertaModel.from_pretrained("xlm-roberta-large"							)
        UpperCAmelCase__						:    Tuple							=							torch.tensor([[0, 5_8_1, 1_0_2_6_9, 8_3, 9_9_9_4_2, 1_3_6, 6_0_7_4_2, 2_3, 7_0, 8_0_5_8_3, 1_8_2_7_6, 2]]							)
        # The dog is cute and lives in the garden house

        UpperCAmelCase__						:    Union[str, Any]							=							torch.Size((1, 1_2, 1_0_2_4)							)  # batch_size, sequence_length, embedding_vector_dim
        UpperCAmelCase__						:    Optional[Any]							=							torch.tensor(
            [[-0.0699, -0.0318, 0.0705, -0.1241, 0.0999, -0.0520, 0.1004, -0.1838, -0.4704, 0.1437, 0.0821, 0.0126]]							)
        #  xlmr = torch.hub.load('pytorch/fairseq', 'xlmr.large')
        #  xlmr.eval()
        #  expected_output_values_last_dim = xlmr.extract_features(input_ids[0])[:, :, -1]
        with torch.no_grad():
             UpperCAmelCase__						:    Optional[Any]							=							model(snake_case__							)["last_hidden_state"].detach()
        self.assertEqual(output.shape							,			snake_case__							)
        # compare the actual values for a slice of last dim
        self.assertTrue(torch.allclose(output[:, :, -1]							,			snake_case__							,			atol=1e-3							)							)


