

'''simple docstring'''

import unittest

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


if is_torch_available():
 import torch

 from transformers import XLMProphetNetForConditionalGeneration, XLMProphetNetTokenizer




@require_torch
class 			A_					(							unittest.TestCase				):






     '''simple docstring'''



     @slow
     def   UpperCAmelCase_			(						self					:	Optional[int]			)		->      Tuple:
      UpperCAmelCase			:      Optional[int]		   =					XLMProphetNetForConditionalGeneration.from_pretrained('microsoft/xprophetnet-large-wiki100-cased'			)
      model.to(lowercase_			)

      # encoder-decoder outputs
      UpperCAmelCase			:      int		   =					torch.tensor([[17, 96_208, 103_471, 2]]			).to(lowercase_			)
      UpperCAmelCase			:      Tuple		   =					torch.tensor(
          [[2, 250, 9_953, 34, 69_489, 1_620, 32, 118_424, 624, 210, 105, 2_913, 1_032, 351]]			).to(lowercase_			)
      UpperCAmelCase			:      int		   =					model(
          input_ids=lowercase_	,     attention_mask=lowercase_	,     encoder_outputs=lowercase_	,     decoder_input_ids=lowercase_			)
      UpperCAmelCase			:      Dict		   =					output[0]
      UpperCAmelCase			:      List[Any]		   =					torch.Size((1, 14, 250_012)			)
      self.assertEqual(output_predited_logis.shape	,     lowercase_			)
      UpperCAmelCase			:      Dict		   =					torch.tensor(
          [[[-6.3986, -8.2391, 12.5189], [-6.3289, -8.0864, 12.6211], [-6.2418, -8.0445, 12.7968]]]			).to(lowercase_			)
      self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]	,     lowercase_	,     atol=1E-4			)			)

      # encoder outputs
      UpperCAmelCase			:      Tuple		   =					model.prophetnet.encoder(lowercase_			)[0]
      UpperCAmelCase			:      Union[str, Any]		   =					torch.tensor(
          [[[-1.4260, -0.7628, 0.8453], [-1.4719, -0.1391, 0.7807], [-1.7678, 0.0114, 0.4646]]]			).to(lowercase_			)
      UpperCAmelCase			:      Any		   =					torch.Size((1, 4, 1_024)			)
      self.assertEqual(encoder_outputs.shape	,     lowercase_			)
      self.assertTrue(torch.allclose(encoder_outputs[:, :3, :3]	,     lowercase_	,     atol=1E-4			)			)

      # decoder outputs
      UpperCAmelCase			:      int		   =					model.prophetnet.decoder(
          lowercase_	,     encoder_hidden_states=lowercase_	,     )
      UpperCAmelCase			:      Tuple		   =					decoder_outputs[1].view(1	,     model.config.ngram	,     14	,     -1			)
      UpperCAmelCase			:      Union[str, Any]		   =					model.lm_head(lowercase_			)
      UpperCAmelCase			:      int		   =					predicting_streams_logits[:, 0]
      self.assertTrue(torch.allclose(next_first_stream_logits[:, :3, :3]	,     lowercase_	,     atol=1E-4			)			)


     @slow
     def   UpperCAmelCase_			(						self					:	str			)		->      Optional[Any]:
      UpperCAmelCase			:      Union[str, Any]		   =					XLMProphetNetForConditionalGeneration.from_pretrained(
          'microsoft/xprophetnet-large-wiki100-cased-xglue-ntg'			)
      model.to(lowercase_			)

      UpperCAmelCase			:      List[str]		   =					torch.tensor([[17, 96_208, 103_471, 2]]			).to(lowercase_			)
      UpperCAmelCase			:      Union[str, Any]		   =					torch.tensor(
          [[2, 250, 9_953, 34, 69_489, 1_620, 32, 118_424, 624, 210, 105, 2_913, 1_032, 351]]			).to(lowercase_			)
      UpperCAmelCase			:      List[Any]		   =					model(
          input_ids=lowercase_	,     attention_mask=lowercase_	,     encoder_outputs=lowercase_	,     decoder_input_ids=lowercase_			)
      UpperCAmelCase			:      Tuple		   =					output[0]
      UpperCAmelCase			:      Any		   =					torch.Size((1, 14, 250_012)			)
      self.assertEqual(output_predited_logis.shape	,     lowercase_			)
      # compare the actual values for a slice.
      UpperCAmelCase			:      List[str]		   =					torch.tensor(
          [[[-9.2253, -9.7173, -6.3529], [-7.6701, -9.0145, -1.9382], [-8.0195, -7.0004, -0.1523]]]			).to(lowercase_			)

      self.assertTrue(torch.allclose(output_predited_logis[:, :3, :3]	,     lowercase_	,     atol=1E-4			)			)




     @slow
     def   UpperCAmelCase_			(						self					:	Optional[Any]			)		->      int:
      UpperCAmelCase			:      Any		   =					XLMProphetNetForConditionalGeneration.from_pretrained(
          'microsoft/xprophetnet-large-wiki100-cased-xglue-ntg'			)
      model.to(lowercase_			)
      UpperCAmelCase			:      Any		   =					512

      UpperCAmelCase			:      List[Any]		   =					XLMProphetNetTokenizer.from_pretrained('microsoft/xprophetnet-large-wiki100-cased-xglue-ntg'			)

      UpperCAmelCase			:      Union[str, Any]		   =					(
          'Microsoft Corporation intends to officially end free support for the Windows 7 operating system after'
          ' January 14, 2020, according to the official portal of the organization. From that day, users of this'
          ' system will not be able to receive security updates, which could make their computers vulnerable to'
          ' cyber attacks.'
      )
      UpperCAmelCase			:      Any		   =					(
          'орпорация Microsoft намерена официально прекратить бесплатную поддержку операционной системы Windows 7'
          ' после 14 января 2020 года, сообщается на официальном портале организации . С указанного дня пользователи'
          ' этой системы не смогут получать обновления безопасности, из-за чего их компьютеры могут стать уязвимыми'
          ' к кибератакам.'
      )
      UpperCAmelCase			:      Union[str, Any]		   =					(
          '根据该组织的官方门户网站，微软公司打算在2020年1月14日之后正式终止对Windows 7操作系统的免费支持。从那时起，该系统的用户将无法接收安全更新，这可能会使他们的计算机容易受到网络攻击。'
      )

      UpperCAmelCase			:      Union[str, Any]		   =					tokenizer(
          [EN_SENTENCE, RU_SENTENCE, ZH_SENTENCE]	,     padding=lowercase_	,     max_length=255	,     return_tensors='pt'			).input_ids
      UpperCAmelCase			:      Optional[int]		   =					input_ids.to(lowercase_			)

      UpperCAmelCase			:      Optional[Any]		   =					model.generate(
          lowercase_	,     num_beams=10	,     length_penalty=1.0	,     no_repeat_ngram_size=3	,     early_stopping=lowercase_			)
      UpperCAmelCase			:      Dict		   =					[tokenizer.decode(lowercase_	,     skip_special_tokens=lowercase_			) for g in summary_ids]
      UpperCAmelCase			:      Optional[Any]		   =					'Microsoft to end Windows 7 free support after January 14, 2020'
      UpperCAmelCase			:      List[str]		   =					'Microsoft намерена прекратить бесплатную поддержку Windows 7 после 14 января 2020 года'
      UpperCAmelCase			:      Optional[Any]		   =					'微软打算终止对Windows 7操作系统的免费支持'
      self.assertListEqual(
          [EXPECTED_TITLE_EN, EXPECTED_TITLE_RU, EXPECTED_TITLE_ZH]	,     lowercase_	,     )

      UpperCAmelCase			:      Dict		   =					model.generate(
          lowercase_	,     num_beams=1	,     length_penalty=1.0	,     no_repeat_ngram_size=3	,     early_stopping=lowercase_			)
      UpperCAmelCase			:      Optional[Any]		   =					[
          tokenizer.convert_ids_to_tokens(lowercase_	,     skip_special_tokens=lowercase_			) for g in summary_ids_beama
      ]
      UpperCAmelCase			:      Union[str, Any]		   =					'▁Microsoft ▁to ▁end ▁free ▁support ▁for ▁Windows ▁7'.split(' '			)
      UpperCAmelCase			:      Tuple		   =					'▁Microsoft ▁намерен а ▁прекрати ть ▁бес плат ную ▁поддержку ▁Windows ▁7 ▁после ▁14 ▁января ▁2020 ▁года'.split(
          ' '			)
      UpperCAmelCase			:      Union[str, Any]		   =					'微软 公司 打算 终止 对 Windows ▁7 操作 系统的 免费 支持'.split(' '			)
      self.assertListEqual(
          [EXPECTED_TITLE_EN_BEAM1_TOK, EXPECTED_TITLE_RU_BEAM1_TOK, EXPECTED_TITLE_ZH_BEAM1_TOK]	,     lowercase_	,     )







'''simple docstring'''

from sklearn.metrics import accuracy_score

import datasets


lowercase__            =     "\nAccuracy is the proportion of correct predictions among the total number of cases processed. It can be computed with:\nAccuracy = (TP + TN) / (TP + TN + FP + FN)\n Where:\nTP: True positive\nTN: True negative\nFP: False positive\nFN: False negative\n"


lowercase__            =     "\nArgs:\n    predictions (`list` of `int`): Predicted labels.\n    references (`list` of `int`): Ground truth labels.\n    normalize (`boolean`): If set to False, returns the number of correctly classified samples. Otherwise, returns the fraction of correctly classified samples. Defaults to True.\n    sample_weight (`list` of `float`): Sample weights Defaults to None.\n\nReturns:\n    accuracy (`float` or `int`): Accuracy score. Minimum possible value is 0. Maximum possible value is 1.0, or the number of examples input, if `normalize` is set to `True`.. A higher score means higher accuracy.\n\nExamples:\n\n    Example 1-A simple example\n        >>> accuracy_metric = datasets.load_metric(\"accuracy\")\n        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0])\n        >>> print(results)\n        {'accuracy': 0.5}\n\n    Example 2-The same as Example 1, except with `normalize` set to `False`.\n        >>> accuracy_metric = datasets.load_metric(\"accuracy\")\n        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], normalize=False)\n        >>> print(results)\n        {'accuracy': 3.0}\n\n    Example 3-The same as Example 1, except with `sample_weight` set.\n        >>> accuracy_metric = datasets.load_metric(\"accuracy\")\n        >>> results = accuracy_metric.compute(references=[0, 1, 2, 0, 1, 2], predictions=[0, 1, 1, 2, 1, 0], sample_weight=[0.5, 2, 0.7, 0.5, 9, 0.4])\n        >>> print(results)\n        {'accuracy': 0.8778625954198473}\n"


lowercase__            =     "\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 			A_					(							datasets.Metric				):






     '''simple docstring'''



     def   UpperCAmelCase_			(						self					:	int			)		->      str:
      return datasets.MetricInfo(
          description=_DESCRIPTION	,     citation=_CITATION	,     inputs_description=_KWARGS_DESCRIPTION	,     features=datasets.Features(
              {
                  'predictions': datasets.Sequence(datasets.Value('int32'			)			),
                  'references': datasets.Sequence(datasets.Value('int32'			)			),
              }
              if self.config_name == 'multilabel'
              else {
                  'predictions': datasets.Value('int32'			),
                  'references': datasets.Value('int32'			),
              }			)	,     reference_urls=['https://scikit-learn.org/stable/modules/generated/sklearn.metrics.accuracy_score.html']	,     )




     def   UpperCAmelCase_			(						self					:	str	,     lowercase_					:	Union[str, Any]	,     lowercase_					:	Any	,     lowercase_					:	Tuple=True	,     lowercase_					:	Union[str, Any]=None			)		->      Dict:
      return {
          "accuracy": float(
              accuracy_score(lowercase_	,     lowercase_	,     normalize=lowercase_	,     sample_weight=lowercase_			)			)
      }




