




'''simple docstring'''







from __future__ import annotations

import unittest

from transformers import AlbertConfig, is_tf_available
from transformers.models.auto import get_values
from transformers.testing_utils import require_tf, slow

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
      import tensorflow as tf

      from transformers import TF_MODEL_FOR_PRETRAINING_MAPPING
      from transformers.models.albert.modeling_tf_albert import (
          TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
          TFAlbertForMaskedLM,
          TFAlbertForMultipleChoice,
          TFAlbertForPreTraining,
          TFAlbertForQuestionAnswering,
          TFAlbertForSequenceClassification,
          TFAlbertForTokenClassification,
          TFAlbertModel,
      )







class 				_a   :





     '''simple docstring'''



     def __init__(							self       ,__a       ,__a=13       ,__a=7       ,__a=True       ,__a=True       ,__a=True       ,__a=True       ,__a=99       ,__a=16       ,__a=32       ,__a=2       ,__a=4       ,__a=37       ,__a="gelu"       ,__a=0.1       ,__a=0.1       ,__a=512       ,__a=16       ,__a=2       ,__a=0.02       ,__a=3       ,__a=4       ,__a=None       ,)			->							Optional[int]:
          snake_case :			List[str]					   = parent
          snake_case :			int					   = 13
          snake_case :			List[Any]					   = 7
          snake_case :			Tuple					   = True
          snake_case :			List[Any]					   = True
          snake_case :			List[str]					   = True
          snake_case :			List[str]					   = True
          snake_case :			List[Any]					   = 99
          snake_case :			Union[str, Any]					   = 16
          snake_case :			Dict					   = 32
          snake_case :			Union[str, Any]					   = 2
          snake_case :			str					   = 4
          snake_case :			List[str]					   = 37
          snake_case :			List[str]					   = "gelu"
          snake_case :			Optional[int]					   = 0.1
          snake_case :			Dict					   = 0.1
          snake_case :			Any					   = 512
          snake_case :			Any					   = 16
          snake_case :			Union[str, Any]					   = 2
          snake_case :			int					   = 0.02
          snake_case :			str					   = 3
          snake_case :			str					   = 4
          snake_case :			List[Any]					   = None







     def  snake_case_			(							self       )			->							int:
          snake_case :			Optional[int]					   = ids_tensor([self.batch_size, self.seq_length]       ,self.vocab_size       )

          snake_case :			Any					   = None
          if self.use_input_mask:
               snake_case :			int					   = random_attention_mask([self.batch_size, self.seq_length]       )

          snake_case :			Optional[int]					   = None
          if self.use_token_type_ids:
               snake_case :			List[Any]					   = ids_tensor([self.batch_size, self.seq_length]       ,self.type_vocab_size       )

          snake_case :			List[str]					   = None
          snake_case :			Optional[int]					   = None
          snake_case :			str					   = None
          if self.use_labels:
               snake_case :			Union[str, Any]					   = ids_tensor([self.batch_size]       ,self.type_sequence_label_size       )
               snake_case :			Optional[int]					   = ids_tensor([self.batch_size, self.seq_length]       ,self.num_labels       )
               snake_case :			Dict					   = ids_tensor([self.batch_size]       ,self.num_choices       )

          snake_case :			int					   = AlbertConfig(
              vocab_size=self.vocab_size       ,hidden_size=self.hidden_size       ,embedding_size=self.embedding_size       ,num_hidden_layers=self.num_hidden_layers       ,num_attention_heads=self.num_attention_heads       ,intermediate_size=self.intermediate_size       ,hidden_act=self.hidden_act       ,hidden_dropout_prob=self.hidden_dropout_prob       ,attention_probs_dropout_prob=self.attention_probs_dropout_prob       ,max_position_embeddings=self.max_position_embeddings       ,type_vocab_size=self.type_vocab_size       ,initializer_range=self.initializer_range       ,)

          return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels







     def  snake_case_			(							self       ,__a       ,__a       ,__a       ,__a       ,__a       ,__a       ,__a       )			->							Optional[int]:
          snake_case :			List[Any]					   = TFAlbertModel(config=__a       )
          # inputs = {'input_ids': input_ids,
          #           'attention_mask': input_mask,
          #           'token_type_ids': token_type_ids}
          # sequence_output, pooled_output = model(**inputs)
          snake_case :			List[str]					   = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
          snake_case :			Tuple					   = model(__a       )

          snake_case :			Any					   = [input_ids, input_mask]
          snake_case :			Optional[int]					   = model(__a       )

          snake_case :			Any					   = model(__a       )

          self.parent.assertEqual(result.last_hidden_state.shape       ,(self.batch_size, self.seq_length, self.hidden_size)       )
          self.parent.assertEqual(result.pooler_output.shape       ,(self.batch_size, self.hidden_size)       )







     def  snake_case_			(							self       ,__a       ,__a       ,__a       ,__a       ,__a       ,__a       ,__a       )			->							Tuple:
          snake_case :			str					   = self.num_labels
          snake_case :			str					   = TFAlbertForPreTraining(config=__a       )
          snake_case :			Any					   = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
          snake_case :			str					   = model(__a       )
          self.parent.assertEqual(result.prediction_logits.shape       ,(self.batch_size, self.seq_length, self.vocab_size)       )
          self.parent.assertEqual(result.sop_logits.shape       ,(self.batch_size, self.num_labels)       )







     def  snake_case_			(							self       ,__a       ,__a       ,__a       ,__a       ,__a       ,__a       ,__a       )			->							Dict:
          snake_case :			Union[str, Any]					   = TFAlbertForMaskedLM(config=__a       )
          snake_case :			Any					   = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
          snake_case :			Optional[int]					   = model(__a       )
          self.parent.assertEqual(result.logits.shape       ,(self.batch_size, self.seq_length, self.vocab_size)       )







     def  snake_case_			(							self       ,__a       ,__a       ,__a       ,__a       ,__a       ,__a       ,__a       )			->							str:
          snake_case :			Optional[Any]					   = self.num_labels
          snake_case :			Optional[Any]					   = TFAlbertForSequenceClassification(config=__a       )
          snake_case :			str					   = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
          snake_case :			Union[str, Any]					   = model(__a       )
          self.parent.assertEqual(result.logits.shape       ,(self.batch_size, self.num_labels)       )







     def  snake_case_			(							self       ,__a       ,__a       ,__a       ,__a       ,__a       ,__a       ,__a       )			->							Union[str, Any]:
          snake_case :			str					   = TFAlbertForQuestionAnswering(config=__a       )
          snake_case :			List[Any]					   = {"input_ids": input_ids, "attention_mask": input_mask, "token_type_ids": token_type_ids}
          snake_case :			List[str]					   = model(__a       )
          self.parent.assertEqual(result.start_logits.shape       ,(self.batch_size, self.seq_length)       )
          self.parent.assertEqual(result.end_logits.shape       ,(self.batch_size, self.seq_length)       )







     def  snake_case_			(							self       ,__a       ,__a       ,__a       ,__a       ,__a       ,__a       ,__a       )			->							Optional[int]:
          snake_case :			Tuple					   = self.num_choices
          snake_case :			List[Any]					   = TFAlbertForMultipleChoice(config=__a       )
          snake_case :			Any					   = tf.tile(tf.expand_dims(__a       ,1       )       ,(1, self.num_choices, 1)       )
          snake_case :			str					   = tf.tile(tf.expand_dims(__a       ,1       )       ,(1, self.num_choices, 1)       )
          snake_case :			Optional[int]					   = tf.tile(tf.expand_dims(__a       ,1       )       ,(1, self.num_choices, 1)       )
          snake_case :			Optional[int]					   = {
              "input_ids": multiple_choice_inputs_ids,
              "attention_mask": multiple_choice_input_mask,
              "token_type_ids": multiple_choice_token_type_ids,
          }
          snake_case :			Union[str, Any]					   = model(__a       )
          self.parent.assertListEqual(list(result["""logits"""].shape       )       ,[self.batch_size, self.num_choices]       )







     def  snake_case_			(							self       ,__a       ,__a       ,__a       ,__a       ,__a       ,__a       ,__a       )			->							Dict:
          snake_case :			Tuple					   = self.num_labels
          snake_case :			Optional[Any]					   = TFAlbertForTokenClassification(config=__a       )
          snake_case :			Optional[Any]					   = {
              "input_ids": input_ids,
              "attention_mask": input_mask,
              "token_type_ids": token_type_ids,
          }
          snake_case :			List[Any]					   = model(__a       )
          self.parent.assertListEqual(list(result["""logits"""].shape       )       ,[self.batch_size, self.seq_length, self.num_labels]       )







     def  snake_case_			(							self       )			->							List[str]:
          snake_case :			int					   = self.prepare_config_and_inputs()
          (
              snake_case				
          ) :			Optional[Any]					   = config_and_inputs
          snake_case :			Tuple					   = {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
          return config, inputs_dict







@require_tf
class 				_a   (lowerCamelCase_,		lowerCamelCase_,		unittest.TestCase  ):





     '''simple docstring'''



     lowerCAmelCase_     :    Optional[int]									=				(
         (
             TFAlbertModel,
             TFAlbertForPreTraining,
             TFAlbertForMaskedLM,
             TFAlbertForSequenceClassification,
             TFAlbertForQuestionAnswering,
             TFAlbertForTokenClassification,
             TFAlbertForMultipleChoice,
         )
         if is_tf_available()
         else ()
     )
     lowerCAmelCase_     :    Optional[int]									=				(
         {
             """feature-extraction""": TFAlbertModel,
             """fill-mask""": TFAlbertForMaskedLM,
             """question-answering""": TFAlbertForQuestionAnswering,
             """text-classification""": TFAlbertForSequenceClassification,
             """token-classification""": TFAlbertForTokenClassification,
             """zero-shot""": TFAlbertForSequenceClassification,
         }
         if is_tf_available()
         else {}
     )
     lowerCAmelCase_     :    List[Any]									=				False
     lowerCAmelCase_     :    int									=				False







     def  snake_case_			(							self       ,__a       ,__a       ,__a=False       )			->							List[Any]:
          snake_case :			Optional[int]					   = super()._prepare_for_class(__a       ,__a       ,return_labels=__a       )

          if return_labels:
               if model_class in get_values(__a       ):
                    snake_case :			Any					   = tf.zeros(self.model_tester.batch_size       ,dtype=tf.intaa       )

          return inputs_dict







     def  snake_case_			(							self       )			->							Dict:
          snake_case :			Union[str, Any]					   = TFAlbertModelTester(self       )
          snake_case :			List[str]					   = ConfigTester(self       ,config_class=__a       ,hidden_size=37       )







     def  snake_case_			(							self       )			->							List[str]:
          self.config_tester.run_common_tests()







     def  snake_case_			(							self       )			->							Optional[Any]:
          snake_case :			Optional[int]					   = self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_albert_model(*__a       )







     def  snake_case_			(							self       )			->							List[str]:
          snake_case :			int					   = self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_albert_for_pretraining(*__a       )







     def  snake_case_			(							self       )			->							List[str]:
          snake_case :			List[str]					   = self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_albert_for_masked_lm(*__a       )







     def  snake_case_			(							self       )			->							int:
          snake_case :			int					   = self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_albert_for_multiple_choice(*__a       )







     def  snake_case_			(							self       )			->							Tuple:
          snake_case :			str					   = self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_albert_for_sequence_classification(*__a       )







     def  snake_case_			(							self       )			->							Any:
          snake_case :			Tuple					   = self.model_tester.prepare_config_and_inputs()
          self.model_tester.create_and_check_albert_for_question_answering(*__a       )







     @slow
     def  snake_case_			(							self       )			->							Union[str, Any]:







          for model_name in TF_ALBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
               snake_case :			List[Any]					   = TFAlbertModel.from_pretrained(__a       )
               self.assertIsNotNone(__a       )







@require_tf
class 				_a   (unittest.TestCase  ):





     '''simple docstring'''



     @slow
     def  snake_case_			(							self       )			->							Tuple:
          snake_case :			Optional[Any]					   = TFAlbertForPreTraining.from_pretrained("""albert-base-v2"""       )
          snake_case :			Tuple					   = tf.constant([[0, 1, 2, 3, 4, 5]]       )
          snake_case :			Tuple					   = model(__a       )[0]

          snake_case :			Optional[Any]					   = [1, 6, 30_000]
          self.assertEqual(output.shape       ,__a       )

          snake_case :			Optional[Any]					   = tf.constant(
              [
                  [
                      [4.595_668, 0.74_462_754, -1.818_147],
                      [4.5_954_347, 0.7_454_184, -1.8_188_258],
                      [4.5_954_905, 0.7_448_235, -1.8_182_316],
                  ]
              ]       )
          tf.debugging.assert_near(output[:, :3, :3]       ,__a       ,atol=1E-4       )









'''simple docstring'''







from sklearn.metrics import mean_absolute_error

import datasets


lowercase			:      int			=					"""\
@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}
}
"""

lowercase			:      Optional[Any]			=					"""\
Mean Absolute Error (MAE) is the mean of the magnitude of difference between the predicted and actual
values.
"""


lowercase			:      List[Any]			=					"""
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.

Returns:
    mae : mean absolute error.
        If multioutput is \"raw_values\", then mean absolute error is returned for each output separately. If multioutput is \"uniform_average\" or an ndarray of weights, then the weighted average of all output errors is returned.
        MAE output is non-negative floating point. The best value is 0.0.
Examples:

    >>> mae_metric = datasets.load_metric(\"mae\")
    >>> predictions = [2.5, 0.0, 2, 8]
    >>> references = [3, -0.5, 2, 7]
    >>> results = mae_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'mae': 0.5}

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

    >>> mae_metric = datasets.load_metric(\"mae\", \"multilist\")
    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]
    >>> references = [[0, 2], [-1, 2], [8, -5]]
    >>> results = mae_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'mae': 0.75}
    >>> results = mae_metric.compute(predictions=predictions, references=references, multioutput='raw_values')
    >>> print(results)
    {'mae': array([0.5, 1. ])}
"""







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





     '''simple docstring'''



     def  snake_case_			(							self       )			->							int:
          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_absolute_error.html"""
              ]       ,)







     def  snake_case_			(							self       )			->							Any:
          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       ,__a       ,__a       ,__a=None       ,__a="uniform_average"       )			->							str:
          snake_case :			int					   = mean_absolute_error(__a       ,__a       ,sample_weight=__a       ,multioutput=__a       )

          return {"mae": mae_score}



