"""simple docstring"""





from sklearn.metrics import matthews_corrcoef

import datasets


_UpperCamelCase     :		Tuple											=					"\nCompute the Matthews correlation coefficient (MCC)\n\nThe Matthews correlation coefficient is used in machine learning as a\nmeasure of the quality of binary and multiclass classifications. It takes\ninto account true and false positives and negatives and is generally\nregarded as a balanced measure which can be used even if the classes are of\nvery different sizes. The MCC is in essence a correlation coefficient value\nbetween -1 and +1. A coefficient of +1 represents a perfect prediction, 0\nan average random prediction and -1 an inverse prediction.  The statistic\nis also known as the phi coefficient. [source: Wikipedia]\n"

_UpperCamelCase     :		List[Any]											=					"\nArgs:\n    predictions (list of int): Predicted labels, as returned by a model.\n    references (list of int): Ground truth labels.\n    sample_weight (list of int, float, or bool): Sample weights. Defaults to `None`.\nReturns:\n    matthews_correlation (dict containing float): Matthews correlation.\nExamples:\n    Example 1, a basic example with only predictions and references as inputs:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.54\n\n    Example 2, the same example as above, but also including sample weights:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 3, 1, 1, 1, 2])\n        >>> print(round(results['matthews_correlation'], 2))\n        0.1\n\n    Example 3, the same example as above, but with sample weights that cause a negative correlation:\n        >>> matthews_metric = datasets.load_metric(\"matthews_correlation\")\n        >>> results = matthews_metric.compute(references=[1, 3, 2, 0, 3, 2],\n        ...                                     predictions=[1, 2, 2, 0, 3, 3],\n        ...                                     sample_weight=[0.5, 1, 0, 0, 0, 1])\n        >>> print(round(results['matthews_correlation'], 2))\n        -0.25\n"

_UpperCamelCase     :		int											=					"\\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"


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


      def 	_UpperCAmelCase (     self							) ->      Union[str, Any]:
             return datasets.MetricInfo(
                 description=_DESCRIPTION	,    citation=_CITATION	,    inputs_description=_KWARGS_DESCRIPTION	,    features=datasets.Features(
                     {
                         'predictions': datasets.Value('int32'							),
                         'references': datasets.Value('int32'							),
                     }							)	,    reference_urls=[
                     'https://scikit-learn.org/stable/modules/generated/sklearn.metrics.matthews_corrcoef.html'
                 ]	,    )


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a=None							) ->      str:
             return {
                 "matthews_correlation": float(matthews_corrcoef(a	,    a	,    sample_weight=a							)							),
             }


"""simple docstring"""





import os
import tempfile
import unittest

from transformers import DistilBertConfig, is_torch_available
from transformers.testing_utils import require_torch, require_torch_gpu, slow, torch_device

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
       import torch

       from transformers import (
           DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST,
           DistilBertForMaskedLM,
           DistilBertForMultipleChoice,
           DistilBertForQuestionAnswering,
           DistilBertForSequenceClassification,
           DistilBertForTokenClassification,
           DistilBertModel,
       )


class   UpperCAmelCase_			(					_a):


      def __init__(     self	,    a	,    a=1_3	,    a=7	,    a=True	,    a=True	,    a=False	,    a=True	,    a=9_9	,    a=3_2	,    a=5	,    a=4	,    a=3_7	,    a="gelu"	,    a=0.1	,    a=0.1	,    a=5_1_2	,    a=1_6	,    a=2	,    a=0.02	,    a=3	,    a=4	,    a=None	,    ) ->      Any:
             lowercase__    :	Tuple     					=			parent
             lowercase__    :	List[Any]     					=			batch_size
             lowercase__    :	List[Any]     					=			seq_length
             lowercase__    :	List[Any]     					=			is_training
             lowercase__    :	Optional[Any]     					=			use_input_mask
             lowercase__    :	Optional[int]     					=			use_token_type_ids
             lowercase__    :	int     					=			use_labels
             lowercase__    :	Tuple     					=			vocab_size
             lowercase__    :	int     					=			hidden_size
             lowercase__    :	Any     					=			num_hidden_layers
             lowercase__    :	List[str]     					=			num_attention_heads
             lowercase__    :	Optional[Any]     					=			intermediate_size
             lowercase__    :	Optional[Any]     					=			hidden_act
             lowercase__    :	List[str]     					=			hidden_dropout_prob
             lowercase__    :	List[Any]     					=			attention_probs_dropout_prob
             lowercase__    :	List[Any]     					=			max_position_embeddings
             lowercase__    :	List[str]     					=			type_vocab_size
             lowercase__    :	Tuple     					=			type_sequence_label_size
             lowercase__    :	List[Any]     					=			initializer_range
             lowercase__    :	str     					=			num_labels
             lowercase__    :	Tuple     					=			num_choices
             lowercase__    :	str     					=			scope


      def 	_UpperCAmelCase (     self							) ->      Any:
             lowercase__    :	List[Any]     					=			ids_tensor([self.batch_size, self.seq_length]	,    self.vocab_size							)

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

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

             lowercase__    :	List[Any]     					=			self.get_config()

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


      def 	_UpperCAmelCase (     self							) ->      Optional[int]:
             return DistilBertConfig(
                 vocab_size=self.vocab_size	,    dim=self.hidden_size	,    n_layers=self.num_hidden_layers	,    n_heads=self.num_attention_heads	,    hidden_dim=self.intermediate_size	,    hidden_act=self.hidden_act	,    dropout=self.hidden_dropout_prob	,    attention_dropout=self.attention_probs_dropout_prob	,    max_position_embeddings=self.max_position_embeddings	,    initializer_range=self.initializer_range	,    )


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    a	,    a	,    a							) ->      Dict:
             lowercase__    :	Tuple     					=			DistilBertModel(config=a							)
             model.to(a							)
             model.eval()
             lowercase__    :	Any     					=			model(a	,    a							)
             lowercase__    :	str     					=			model(a							)
             self.parent.assertEqual(result.last_hidden_state.shape	,    (self.batch_size, self.seq_length, self.hidden_size)							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    a	,    a	,    a							) ->      Dict:
             lowercase__    :	Optional[int]     					=			DistilBertForMaskedLM(config=a							)
             model.to(a							)
             model.eval()
             lowercase__    :	Union[str, Any]     					=			model(a	,    attention_mask=a	,    labels=a							)
             self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.seq_length, self.vocab_size)							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    a	,    a	,    a							) ->      int:
             lowercase__    :	Tuple     					=			DistilBertForQuestionAnswering(config=a							)
             model.to(a							)
             model.eval()
             lowercase__    :	Tuple     					=			model(
                 a	,    attention_mask=a	,    start_positions=a	,    end_positions=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 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    a	,    a	,    a							) ->      List[str]:
             lowercase__    :	int     					=			self.num_labels
             lowercase__    :	Dict     					=			DistilBertForSequenceClassification(a							)
             model.to(a							)
             model.eval()
             lowercase__    :	Optional[Any]     					=			model(a	,    attention_mask=a	,    labels=a							)
             self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.num_labels)							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    a	,    a	,    a							) ->      Any:
             lowercase__    :	Any     					=			self.num_labels
             lowercase__    :	List[str]     					=			DistilBertForTokenClassification(config=a							)
             model.to(a							)
             model.eval()

             lowercase__    :	Any     					=			model(a	,    attention_mask=a	,    labels=a							)
             self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.seq_length, self.num_labels)							)


      def 	_UpperCAmelCase (     self	,    a	,    a	,    a	,    a	,    a	,    a							) ->      Tuple:
             lowercase__    :	List[Any]     					=			self.num_choices
             lowercase__    :	Any     					=			DistilBertForMultipleChoice(config=a							)
             model.to(a							)
             model.eval()
             lowercase__    :	str     					=			input_ids.unsqueeze(1							).expand(-1	,    self.num_choices	,    -1							).contiguous()
             lowercase__    :	Optional[int]     					=			input_mask.unsqueeze(1							).expand(-1	,    self.num_choices	,    -1							).contiguous()
             lowercase__    :	int     					=			model(
                 a	,    attention_mask=a	,    labels=a	,    )
             self.parent.assertEqual(result.logits.shape	,    (self.batch_size, self.num_choices)							)


      def 	_UpperCAmelCase (     self							) ->      str:
             lowercase__    :	Union[str, Any]     					=			self.prepare_config_and_inputs()
             ((lowercase__)					,   (lowercase__)					,   (lowercase__)					,   (lowercase__)					,   (lowercase__)					,   (lowercase__))    :	List[str]     					=			config_and_inputs
             lowercase__    :	Optional[Any]     					=			{'input_ids': input_ids, 'attention_mask': input_mask}
             return config, inputs_dict





@require_torch
class   UpperCAmelCase_			(					_a				,							_a				,							unittest.TestCase):
      lowerCamelCase__	:					List[str]										=						(
          (
              DistilBertModel,
              DistilBertForMaskedLM,
              DistilBertForMultipleChoice,
              DistilBertForQuestionAnswering,
              DistilBertForSequenceClassification,
              DistilBertForTokenClassification,
          )
          if is_torch_available()
          else None
      )
      lowerCamelCase__	:					str										=						(
          {
              "feature-extraction": DistilBertModel,
              "fill-mask": DistilBertForMaskedLM,
              "question-answering": DistilBertForQuestionAnswering,
              "text-classification": DistilBertForSequenceClassification,
              "token-classification": DistilBertForTokenClassification,
              "zero-shot": DistilBertForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      lowerCamelCase__	:					Optional[int]										=						True
      lowerCamelCase__	:					Any										=						True
      lowerCamelCase__	:					List[Any]										=						True
      lowerCamelCase__	:					Optional[Any]										=						True


      def 	_UpperCAmelCase (     self							) ->      Union[str, Any]:
             lowercase__    :	str     					=			DistilBertModelTester(self							)
             lowercase__    :	int     					=			ConfigTester(self	,    config_class=a	,    dim=3_7							)


      def 	_UpperCAmelCase (     self							) ->      Dict:
             self.config_tester.run_common_tests()


      def 	_UpperCAmelCase (     self							) ->      Optional[Any]:
             lowercase__    :	int     					=			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_distilbert_model(*a							)


      def 	_UpperCAmelCase (     self							) ->      Any:
             lowercase__    :	int     					=			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_distilbert_for_masked_lm(*a							)


      def 	_UpperCAmelCase (     self							) ->      Optional[int]:
             lowercase__    :	str     					=			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_distilbert_for_question_answering(*a							)


      def 	_UpperCAmelCase (     self							) ->      int:
             lowercase__    :	List[str]     					=			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_distilbert_for_sequence_classification(*a							)


      def 	_UpperCAmelCase (     self							) ->      List[str]:
             lowercase__    :	Dict     					=			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_distilbert_for_token_classification(*a							)


      def 	_UpperCAmelCase (     self							) ->      str:
             lowercase__    :	Any     					=			self.model_tester.prepare_config_and_inputs()
             self.model_tester.create_and_check_distilbert_for_multiple_choice(*a							)


      @slow
      def 	_UpperCAmelCase (     self							) ->      str:
             for model_name in DISTILBERT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
                    lowercase__    :	str     					=			DistilBertModel.from_pretrained(a							)
                    self.assertIsNotNone(a							)


      @slow
      @require_torch_gpu
      def 	_UpperCAmelCase (     self							) ->      Any:
             lowercase__					,   lowercase__    :	Dict     					=			self.model_tester.prepare_config_and_inputs_for_common()
             for model_class in self.all_model_classes:
                    # BertForMultipleChoice behaves incorrectly in JIT environments.
                    if model_class == DistilBertForMultipleChoice:
                           return

                    lowercase__    :	Optional[int]     					=			True
                    lowercase__    :	Union[str, Any]     					=			model_class(config=a							)

                    lowercase__    :	int     					=			self._prepare_for_class(a	,    a							)
                    lowercase__    :	Tuple     					=			torch.jit.trace(
                        a	,    (inputs_dict['input_ids'].to('cpu'							), inputs_dict['attention_mask'].to('cpu'							))							)

                    with tempfile.TemporaryDirectory() as tmp:
                           torch.jit.save(a	,    os.path.join(a	,    'traced_model.pt'							)							)
                           lowercase__    :	Optional[int]     					=			torch.jit.load(os.path.join(a	,    'traced_model.pt'							)	,    map_location=a							)
                           loaded(inputs_dict['input_ids'].to(a							)	,    inputs_dict['attention_mask'].to(a							)							)





@require_torch
class   UpperCAmelCase_			(					unittest.TestCase):


      @slow
      def 	_UpperCAmelCase (     self							) ->      List[str]:
             lowercase__    :	int     					=			DistilBertModel.from_pretrained('distilbert-base-uncased'							)
             lowercase__    :	Union[str, Any]     					=			torch.tensor([[0, 3_4_5, 2_3_2, 3_2_8, 7_4_0, 1_4_0, 1_6_9_5, 6_9, 6_0_7_8, 1_5_8_8, 2]]							)
             lowercase__    :	Optional[Any]     					=			torch.tensor([[0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]							)
             with torch.no_grad():
                    lowercase__    :	Optional[Any]     					=			model(a	,    attention_mask=a							)[0]
             lowercase__    :	Tuple     					=			torch.Size((1, 1_1, 7_6_8)							)
             self.assertEqual(output.shape	,    a							)
             lowercase__    :	List[Any]     					=			torch.tensor(
                 [[[-0.1_639, 0.3_299, 0.1_648], [-0.1_746, 0.3_289, 0.1_710], [-0.1_884, 0.3_357, 0.1_810]]]							)

             self.assertTrue(torch.allclose(output[:, 1:4, 1:4]	,    a	,    atol=1e-4							)							)

