
from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


__A				='''\
@misc{wu2016googles,
      title={Google\'s Neural Machine Translation System: Bridging the Gap between Human and Machine Translation},
      author={Yonghui Wu and Mike Schuster and Zhifeng Chen and Quoc V. Le and Mohammad Norouzi and Wolfgang Macherey
              and Maxim Krikun and Yuan Cao and Qin Gao and Klaus Macherey and Jeff Klingner and Apurva Shah and Melvin
              Johnson and Xiaobing Liu and Łukasz Kaiser and Stephan Gouws and Yoshikiyo Kato and Taku Kudo and Hideto
              Kazawa and Keith Stevens and George Kurian and Nishant Patil and Wei Wang and Cliff Young and
              Jason Smith and Jason Riesa and Alex Rudnick and Oriol Vinyals and Greg Corrado and Macduff Hughes
              and Jeffrey Dean},
      year={2016},
      eprint={1609.08144},
      archivePrefix={arXiv},
      primaryClass={cs.CL}
}
'''

__A				='''\
The BLEU score has some undesirable properties when used for single
sentences, as it was designed to be a corpus measure. We therefore
use a slightly different score for our RL experiments which we call
the \'GLEU score\'. For the GLEU score, we record all sub-sequences of
1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then
compute a recall, which is the ratio of the number of matching n-grams
to the number of total n-grams in the target (ground truth) sequence,
and a precision, which is the ratio of the number of matching n-grams
to the number of total n-grams in the generated output sequence. Then
GLEU score is simply the minimum of recall and precision. This GLEU
score\'s range is always between 0 (no matches) and 1 (all match) and
it is symmetrical when switching output and target. According to
our experiments, GLEU score correlates quite well with the BLEU
metric on a corpus level but does not have its drawbacks for our per
sentence reward objective.
'''

__A				='''\
Computes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.
Instead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching
tokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.

Args:
    predictions (list of str): list of translations to score.
        Each translation should be tokenized into a list of tokens.
    references (list of list of str): list of lists of references for each translation.
        Each reference should be tokenized into a list of tokens.
    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.
    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.

Returns:
    \'google_bleu\': google_bleu score

Examples:
    Example 1:
        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',
        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',
        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']
        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',
        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',
        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']

        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',
        ...         \'interested\', \'in\', \'world\', \'history\']
        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',
        ...          \'because\', \'he\', \'read\', \'the\', \'book\']

        >>> list_of_references = [[ref1a], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric("google_bleu")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results["google_bleu"], 2))
        0.44

    Example 2:
        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',
        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',
        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']
        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',
        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',
        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']
        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',
        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',
        ...          \'heed\', \'the\', \'cat\', \'commands\']
        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',
        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',
        ...          \'of\', \'the\', \'cat\']

        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',
        ...         \'interested\', \'in\', \'world\', \'history\']
        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',
        ...          \'because\', \'he\', \'read\', \'the\', \'book\']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric("google_bleu")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)
        >>> print(round(results["google_bleu"], 2))
        0.61

    Example 3:
        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',
        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',
        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']
        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',
        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',
        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']
        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',
        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',
        ...          \'heed\', \'the\', \'cat\', \'commands\']
        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',
        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',
        ...          \'of\', \'the\', \'cat\']

        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',
        ...         \'interested\', \'in\', \'world\', \'history\']
        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',
        ...          \'because\', \'he\', \'read\', \'the\', \'book\']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric("google_bleu")
        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)
        >>> print(round(results["google_bleu"], 2))
        0.53

    Example 4:
        >>> hyp1 = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'which\',
        ...         \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'always\',
        ...         \'disobeys\', \'the\', \'commands\', \'of\', \'the\', \'cat\']
        >>> ref1a = [\'It\', \'is\', \'the\', \'guiding\', \'principle\', \'which\',
        ...          \'guarantees\', \'the\', \'rubber\', \'duck\', \'forces\', \'never\',
        ...          \'being\', \'under\', \'the\', \'command\', \'of\', \'the\', \'cat\']
        >>> ref1b = [\'It\', \'is\', \'a\', \'guide\', \'to\', \'action\', \'that\',
        ...          \'ensures\', \'that\', \'the\', \'rubber\', \'duck\', \'will\', \'never\',
        ...          \'heed\', \'the\', \'cat\', \'commands\']
        >>> ref1c = [\'It\', \'is\', \'the\', \'practical\', \'guide\', \'for\', \'the\',
        ...          \'rubber\', \'duck\', \'army\', \'never\', \'to\', \'heed\', \'the\', \'directions\',
        ...          \'of\', \'the\', \'cat\']

        >>> hyp2 = [\'he\', \'read\', \'the\', \'book\', \'because\', \'he\', \'was\',
        ...         \'interested\', \'in\', \'world\', \'history\']
        >>> ref2a = [\'he\', \'was\', \'interested\', \'in\', \'world\', \'history\',
        ...          \'because\', \'he\', \'read\', \'the\', \'book\']

        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]
        >>> hypotheses = [hyp1, hyp2]
        >>> google_bleu = datasets.load_metric("google_bleu")
        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)
        >>> print(round(results["google_bleu"], 2))
        0.4
'''




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



	def     SCREAMING_SNAKE_CASE_(    self )				->       MetricInfo:
					return datasets.MetricInfo(
					    description=_DESCRIPTION						,  citation=_CITATION						,  inputs_description=_KWARGS_DESCRIPTION						,  features=datasets.Features(
					        {
					            "predictions": datasets.Sequence(datasets.Value("string"						,  id="token" )						,  id="sequence" ),
					            "references": datasets.Sequence(
					                datasets.Sequence(datasets.Value("string"						,  id="token" )						,  id="sequence" )						,  id="references" ),
					        } )						,  )



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase						,  lowercase = 1						,  lowercase = 4						,  )				->       Dict[str, float]:
					return {
					    "google_bleu": gleu_score.corpus_gleu(
					        list_of_references=lowercase						,  hypotheses=lowercase						,  min_len=lowercase						,  max_len=lowercase )
					}




import unittest

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

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch

			from transformers import (
			    OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
			    OpenAIGPTConfig,
			    OpenAIGPTDoubleHeadsModel,
			    OpenAIGPTForSequenceClassification,
			    OpenAIGPTLMHeadModel,
			    OpenAIGPTModel,
			)




class     _SCREAMING_SNAKE_CASE     :



	def __init__(    self						,  lowercase						,  lowercase=13						,  lowercase=7						,  lowercase=True						,  lowercase=True						,  lowercase=True						,  lowercase=99						,  lowercase=32						,  lowercase=5						,  lowercase=4						,  lowercase=37						,  lowercase="gelu"						,  lowercase=0.1						,  lowercase=0.1						,  lowercase=512						,  lowercase=16						,  lowercase=2						,  lowercase=0.0_2						,  lowercase=3						,  lowercase=4						,  lowercase=None						,  )				->       List[str]:
					lowerCamelCase_						=			parent
					lowerCamelCase_						=			batch_size
					lowerCamelCase_						=			seq_length
					lowerCamelCase_						=			is_training
					lowerCamelCase_						=			use_token_type_ids
					lowerCamelCase_						=			use_labels
					lowerCamelCase_						=			vocab_size
					lowerCamelCase_						=			hidden_size
					lowerCamelCase_						=			num_hidden_layers
					lowerCamelCase_						=			num_attention_heads
					lowerCamelCase_						=			intermediate_size
					lowerCamelCase_						=			hidden_act
					lowerCamelCase_						=			hidden_dropout_prob
					lowerCamelCase_						=			attention_probs_dropout_prob
					lowerCamelCase_						=			max_position_embeddings
					lowerCamelCase_						=			type_vocab_size
					lowerCamelCase_						=			type_sequence_label_size
					lowerCamelCase_						=			initializer_range
					lowerCamelCase_						=			num_labels
					lowerCamelCase_						=			num_choices
					lowerCamelCase_						=			scope
					lowerCamelCase_						=			self.vocab_size - 1



	def     SCREAMING_SNAKE_CASE_(    self )				->       Any:
					lowerCamelCase_						=			ids_tensor([self.batch_size, self.seq_length]						,  self.vocab_size )

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

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

					lowerCamelCase_						=			OpenAIGPTConfig(
					    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						,  )

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

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



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase						,  lowercase						,  lowercase						,  *lowercase )				->       Dict:
					lowerCamelCase_						=			OpenAIGPTModel(config=lowercase )
					model.to(lowercase )
					model.eval()

					lowerCamelCase_						=			model(lowercase						,  token_type_ids=lowercase						,  head_mask=lowercase )
					lowerCamelCase_						=			model(lowercase						,  token_type_ids=lowercase )
					lowerCamelCase_						=			model(lowercase )

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



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase						,  lowercase						,  lowercase						,  *lowercase )				->       int:
					lowerCamelCase_						=			OpenAIGPTLMHeadModel(lowercase )
					model.to(lowercase )
					model.eval()

					lowerCamelCase_						=			model(lowercase						,  token_type_ids=lowercase						,  labels=lowercase )
					self.parent.assertEqual(result.loss.shape						,  () )
					self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.seq_length, self.vocab_size) )



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase						,  lowercase						,  lowercase						,  *lowercase )				->       Dict:
					lowerCamelCase_						=			OpenAIGPTDoubleHeadsModel(lowercase )
					model.to(lowercase )
					model.eval()

					lowerCamelCase_						=			model(lowercase						,  token_type_ids=lowercase						,  labels=lowercase )
					self.parent.assertEqual(result.loss.shape						,  () )
					self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.seq_length, self.vocab_size) )



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase						,  lowercase						,  lowercase						,  *lowercase )				->       int:
					lowerCamelCase_						=			self.num_labels
					lowerCamelCase_						=			OpenAIGPTForSequenceClassification(lowercase )
					model.to(lowercase )
					model.eval()

					lowerCamelCase_						=			ids_tensor([self.batch_size]						,  self.type_sequence_label_size )
					lowerCamelCase_						=			model(lowercase						,  token_type_ids=lowercase						,  labels=lowercase )
					self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.num_labels) )



	def     SCREAMING_SNAKE_CASE_(    self )				->       Union[str, Any]:
					lowerCamelCase_						=			self.prepare_config_and_inputs()
					(
					    (
					    lowerCamelCase_
					)	,    (
					    lowerCamelCase_
					)	,    (
					    lowerCamelCase_
					)	,    (
					    lowerCamelCase_
					)	,    (
					    lowerCamelCase_
					)	,    (
					    lowerCamelCase_
					)	,    (
					    lowerCamelCase_
					)	,    
					)						=			config_and_inputs
					lowerCamelCase_						=			{
					    "input_ids": input_ids,
					    "token_type_ids": token_type_ids,
					    "head_mask": head_mask,
					}

					return config, inputs_dict




@require_torch
class     _SCREAMING_SNAKE_CASE     (      snake_case_			,       snake_case_			,       snake_case_			,       unittest.TestCase						):
	lowerCAmelCase__         = (
	    (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
	    if is_torch_available()
	    else ()
	)
	lowerCAmelCase__         = (
	    (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
	)  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
	lowerCAmelCase__         = (
	    {
	        'feature-extraction': OpenAIGPTModel,
	        'text-classification': OpenAIGPTForSequenceClassification,
	        'text-generation': OpenAIGPTLMHeadModel,
	        'zero-shot': OpenAIGPTForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase						,  lowercase						,  lowercase						,  lowercase )				->       int:
					if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
									# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
									# `OpenAIGPTConfig` 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						,  lowercase						,  lowercase						,  lowercase=False )				->       Any:
					lowerCamelCase_						=			super()._prepare_for_class(lowercase						,  lowercase						,  return_labels=lowercase )

					if return_labels:
									if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
													lowerCamelCase_						=			torch.zeros(
													    (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)						,  dtype=torch.long						,  device=lowercase						,  )
													lowerCamelCase_						=			inputs_dict["labels"]
													lowerCamelCase_						=			inputs_dict["labels"]
													lowerCamelCase_						=			torch.zeros(
													    (self.model_tester.batch_size, self.model_tester.num_choices)						,  dtype=torch.long						,  device=lowercase						,  )
													lowerCamelCase_						=			torch.zeros(
													    self.model_tester.batch_size						,  dtype=torch.long						,  device=lowercase )
					return inputs_dict



	def     SCREAMING_SNAKE_CASE_(    self )				->       Dict:
					lowerCamelCase_						=			OpenAIGPTModelTester(self )
					lowerCamelCase_						=			ConfigTester(self						,  config_class=lowercase						,  n_embd=37 )



	def     SCREAMING_SNAKE_CASE_(    self )				->       Any:
					self.config_tester.run_common_tests()



	def     SCREAMING_SNAKE_CASE_(    self )				->       Union[str, Any]:
					lowerCamelCase_						=			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_openai_gpt_model(*lowercase )



	def     SCREAMING_SNAKE_CASE_(    self )				->       str:
					lowerCamelCase_						=			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_lm_head_model(*lowercase )



	def     SCREAMING_SNAKE_CASE_(    self )				->       Tuple:
					lowerCamelCase_						=			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_double_lm_head_model(*lowercase )



	def     SCREAMING_SNAKE_CASE_(    self )				->       Optional[Any]:
					lowerCamelCase_						=			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*lowercase )



	@slow
	def     SCREAMING_SNAKE_CASE_(    self )				->       Any:
					for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									lowerCamelCase_						=			OpenAIGPTModel.from_pretrained(lowercase )
									self.assertIsNotNone(lowercase )




@require_torch
class     _SCREAMING_SNAKE_CASE     (      unittest.TestCase						):



	@slow
	def     SCREAMING_SNAKE_CASE_(    self )				->       str:
					lowerCamelCase_						=			OpenAIGPTLMHeadModel.from_pretrained("openai-gpt" )
					model.to(lowercase )
					lowerCamelCase_						=			torch.tensor([[481, 4735, 544]]						,  dtype=torch.long						,  device=lowercase )  # the president is
					lowerCamelCase_						=			[
					    481,
					    4735,
					    544,
					    246,
					    963,
					    870,
					    762,
					    239,
					    244,
					    40477,
					    244,
					    249,
					    719,
					    881,
					    487,
					    544,
					    240,
					    244,
					    603,
					    481,
					]  # the president is a very good man. " \n " i\'m sure he is, " said the

					lowerCamelCase_						=			model.generate(lowercase						,  do_sample=lowercase )
					self.assertListEqual(output_ids[0].tolist()						,  lowercase )


