






"""simple docstring"""


from __future__ import annotations

import unittest

from transformers import CTRLConfig, is_tf_available
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.models.ctrl.modeling_tf_ctrl import (
           TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST,
           TFCTRLForSequenceClassification,
           TFCTRLLMHeadModel,
           TFCTRLModel,
       )


class    snake_case						(				_lowerCAmelCase		):


   '''simple docstring'''

   def __init__(      self					:	str,			_lowerCamelCase					:	str,			):

     '''simple docstring'''
     __A		     =					parent
     __A		     =					13
     __A		     =					7
     __A		     =					True
     __A		     =					True
     __A		     =					True
     __A		     =					True
     __A		     =					True
     __A		     =					99
     __A		     =					32
     __A		     =					2
     __A		     =					4
     __A		     =					37
     __A		     =					'''gelu'''
     __A		     =					0.1
     __A		     =					0.1
     __A		     =					5_12
     __A		     =					16
     __A		     =					2
     __A		     =					0.02
     __A		     =					3
     __A		     =					4
     __A		     =					None
     __A		     =					self.vocab_size - 1


   def 							_SCREAMING_SNAKE_CASE							(      self					:	int    ):

     '''simple docstring'''
     __A		     =					ids_tensor([self.batch_size, self.seq_length],			self.vocab_size    )

     __A		     =					None
     if self.use_input_mask:
       __A		     =					random_attention_mask([self.batch_size, self.seq_length]    )

     __A		     =					None
     if self.use_token_type_ids:
       __A		     =					ids_tensor([self.batch_size, self.seq_length],			self.type_vocab_size    )

     __A		     =					None
     if self.use_mc_token_ids:
       __A		     =					ids_tensor([self.batch_size, self.num_choices],			self.seq_length    )

     __A		     =					None
     __A		     =					None
     __A		     =					None
     if self.use_labels:
       __A		     =					ids_tensor([self.batch_size],			self.type_sequence_label_size    )
       __A		     =					ids_tensor([self.batch_size, self.seq_length],			self.num_labels    )
       __A		     =					ids_tensor([self.batch_size],			self.num_choices    )

     __A		     =					CTRLConfig(
         vocab_size=self.vocab_size,			n_embd=self.hidden_size,			n_layer=self.num_hidden_layers,			n_head=self.num_attention_heads,			n_positions=self.max_position_embeddings,			pad_token_id=self.pad_token_id,			)

     __A		     =					ids_tensor([self.num_hidden_layers, self.num_attention_heads],			2    )

     return (
         config,
         input_ids,
         input_mask,
         head_mask,
         token_type_ids,
         mc_token_ids,
         sequence_labels,
         token_labels,
         choice_labels,
     )


   def 							_SCREAMING_SNAKE_CASE							(      self					:	Optional[Any],			_lowerCamelCase					:	List[Any],			_lowerCamelCase					:	Union[str, Any],			_lowerCamelCase					:	Any,			_lowerCamelCase					:	List[str],			_lowerCamelCase					:	Any,			*_lowerCamelCase					:	str    ):

     '''simple docstring'''
     __A		     =					TFCTRLModel(config=_lowerCamelCase    )
     __A		     =					{'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
     __A		     =					model(_lowerCamelCase    )

     __A		     =					[input_ids, None, input_mask]  # None is the input for 'past'
     __A		     =					model(_lowerCamelCase    )

     __A		     =					model(_lowerCamelCase    )

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


   def 							_SCREAMING_SNAKE_CASE							(      self					:	List[str],			_lowerCamelCase					:	List[Any],			_lowerCamelCase					:	str,			_lowerCamelCase					:	List[Any],			_lowerCamelCase					:	Tuple,			_lowerCamelCase					:	List[str],			*_lowerCamelCase					:	List[Any]    ):

     '''simple docstring'''
     __A		     =					TFCTRLLMHeadModel(config=_lowerCamelCase    )
     __A		     =					{'''input_ids''': input_ids, '''attention_mask''': input_mask, '''token_type_ids''': token_type_ids}
     __A		     =					model(_lowerCamelCase    )
     self.parent.assertEqual(result.logits.shape,			(self.batch_size, self.seq_length, self.vocab_size)    )


   def 							_SCREAMING_SNAKE_CASE							(      self					:	Optional[int],			_lowerCamelCase					:	List[Any],			_lowerCamelCase					:	Tuple,			_lowerCamelCase					:	Dict,			_lowerCamelCase					:	int,			_lowerCamelCase					:	List[Any],			*_lowerCamelCase					:	Optional[int]    ):

     '''simple docstring'''
     __A		     =					self.num_labels
     __A		     =					ids_tensor([self.batch_size],			self.type_sequence_label_size    )
     __A		     =					{
         '''input_ids''': input_ids,
         '''token_type_ids''': token_type_ids,
         '''labels''': sequence_labels,
     }
     __A		     =					TFCTRLForSequenceClassification(_lowerCamelCase    )
     __A		     =					model(_lowerCamelCase    )
     self.parent.assertEqual(result.logits.shape,			(self.batch_size, self.num_labels)    )






   def 							_SCREAMING_SNAKE_CASE							(      self					:	Optional[Any]    ):

     '''simple docstring'''
     __A		     =					self.prepare_config_and_inputs()

     (
         (
         __A
     )     ,       (
         __A
     )     ,       (
         __A
     )     ,       (
         __A
     )     ,       (
         __A
     )     ,       (
         __A
     )     ,       (
         __A
     )     ,       (
         __A
     )     ,       (
         __A
     )     ,       
     )		     =					config_and_inputs

     __A		     =					{'''input_ids''': input_ids, '''token_type_ids''': token_type_ids, '''attention_mask''': input_mask}
     return config, inputs_dict





@require_tf
class    snake_case						(				_lowerCAmelCase  ,      _lowerCAmelCase  ,      unittest.TestCase		):


   '''simple docstring'''

   A_		:      Dict							=					(TFCTRLModel, TFCTRLLMHeadModel, TFCTRLForSequenceClassification) if is_tf_available() else ()
   A_		:      List[str]							=					(TFCTRLLMHeadModel,) if is_tf_available() else ()
   A_		:      Optional[int]							=					(
       {
           "feature-extraction": TFCTRLModel,
           "text-classification": TFCTRLForSequenceClassification,
           "text-generation": TFCTRLLMHeadModel,
           "zero-shot": TFCTRLForSequenceClassification,
       }
       if is_tf_available()
       else {}
   )
   A_		:      Union[str, Any]							=					False
   A_		:      Optional[int]							=					False


   def 							_SCREAMING_SNAKE_CASE							(      self					:	Tuple,			_lowerCamelCase					:	Union[str, Any],			_lowerCamelCase					:	Any,			_lowerCamelCase					:	Union[str, Any],			_lowerCamelCase					:	Union[str, Any],			_lowerCamelCase					:	Optional[int]    ):

     '''simple docstring'''
     if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
       # Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
       # `CTRLConfig` was never used in pipeline tests, either because of a missing checkpoint or because a tiny
       # config could not be created.
       return True

     return False


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

     '''simple docstring'''
     __A		     =					TFCTRLModelTester(self    )
     __A		     =					ConfigTester(self,			config_class=_lowerCamelCase,			n_embd=37    )


   def 							_SCREAMING_SNAKE_CASE							(      self					:	int    ):

     '''simple docstring'''
     self.config_tester.run_common_tests()


   def 							_SCREAMING_SNAKE_CASE							(      self					:	Optional[Any]    ):

     '''simple docstring'''
     __A		     =					self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_ctrl_model(*_lowerCamelCase    )


   def 							_SCREAMING_SNAKE_CASE							(      self					:	Optional[Any]    ):

     '''simple docstring'''
     __A		     =					self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_ctrl_lm_head(*_lowerCamelCase    )


   def 							_SCREAMING_SNAKE_CASE							(      self					:	List[str]    ):

     '''simple docstring'''
     __A		     =					self.model_tester.prepare_config_and_inputs()
     self.model_tester.create_and_check_ctrl_for_sequence_classification(*_lowerCamelCase    )


   def 							_SCREAMING_SNAKE_CASE							(      self					:	int    ):

     '''simple docstring'''
     __A     ,       __A		     =					self.model_tester.prepare_config_and_inputs_for_common()
     __A		     =					[TFCTRLLMHeadModel]
     __A		     =					[TFCTRLForSequenceClassification]

     for model_class in self.all_model_classes:
       __A		     =					model_class(_lowerCamelCase    )
       model.build()  # may be needed for the get_bias() call below
       assert isinstance(model.get_input_embeddings(),			tf.keras.layers.Layer    )

       if model_class in list_lm_models:
         __A		     =					model.get_output_embeddings()
         assert isinstance(_lowerCamelCase,			tf.keras.layers.Layer    )
         __A		     =					model.get_bias()
         assert isinstance(_lowerCamelCase,			_lowerCamelCase    )
         for k, v in name.items():
           assert isinstance(_lowerCamelCase,			tf.Variable    )
       elif model_class in list_other_models_with_output_ebd:
         __A		     =					model.get_output_embeddings()
         assert isinstance(_lowerCamelCase,			tf.keras.layers.Layer    )
         __A		     =					model.get_bias()
         assert name is None
       else:
         __A		     =					model.get_output_embeddings()
         assert x is None
         __A		     =					model.get_bias()
         assert name is None






   @slow
   def 							_SCREAMING_SNAKE_CASE							(      self					:	str    ):

     '''simple docstring'''
     for model_name in TF_CTRL_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       __A		     =					TFCTRLModel.from_pretrained(_lowerCamelCase    )
       self.assertIsNotNone(_lowerCamelCase    )





@require_tf
class    snake_case						(				unittest.TestCase		):


   '''simple docstring'''

   @slow
   def 							_SCREAMING_SNAKE_CASE							(      self					:	Dict    ):

     '''simple docstring'''
     __A		     =					TFCTRLLMHeadModel.from_pretrained('''ctrl'''    )
     __A		     =					tf.convert_to_tensor([[1_18_59, 0, 16_11, 8]],			dtype=tf.intaa    )  # Legal the president is
     __A		     =					[
         1_18_59,
         0,
         16_11,
         8,
         5,
         1_50,
         2_64_49,
         2,
         19,
         3_48,
         4_69,
         3,
         25_95,
         48,
         2_07_40,
         24_65_33,
         24_65_33,
         19,
         30,
         5,
     ]  # Legal the president is a good guy and I don't want to lose my job. \n \n I have a

     __A		     =					model.generate(_lowerCamelCase,			do_sample=_lowerCamelCase    )
     self.assertListEqual(output_ids[0].numpy().tolist(),			_lowerCamelCase    )








from sklearn.metrics import mean_absolute_error

import datasets


a					:				Optional[Any]       =      '\\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'

a					:				int       =      '\\nMean Absolute Error (MAE) is the mean of the magnitude of difference between the predicted and actual\nvalues.\n'


a					:				Any       =      '\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\nReturns:\n    mae : mean absolute error.\n        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.\n        MAE output is non-negative floating point. The best value is 0.0.\nExamples:\n\n    >>> mae_metric = datasets.load_metric("mae")\n    >>> predictions = [2.5, 0.0, 2, 8]\n    >>> references = [3, -0.5, 2, 7]\n    >>> results = mae_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'mae\': 0.5}\n\n    If you\'re using multi-dimensional lists, then set the config as follows :\n\n    >>> mae_metric = datasets.load_metric("mae", "multilist")\n    >>> predictions = [[0.5, 1], [-1, 1], [7, -6]]\n    >>> references = [[0, 2], [-1, 2], [8, -5]]\n    >>> results = mae_metric.compute(predictions=predictions, references=references)\n    >>> print(results)\n    {\'mae\': 0.75}\n    >>> results = mae_metric.compute(predictions=predictions, references=references, multioutput=\'raw_values\')\n    >>> print(results)\n    {\'mae\': array([0.5, 1. ])}\n'

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

       def 					UpperCAmelCase					(      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_absolute_error.html'''
            ]						,    )

       def 					UpperCAmelCase					(      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 					UpperCAmelCase					(      self						,    a__						,    a__						,    a__=None						,    a__="uniform_average"       ):






        '''simple docstring'''






        snake_case :			str							=   mean_absolute_error(a__						,    a__						,    sample_weight=a__						,    multioutput=a__       )

        return {"mae": mae_score}






