



from __future__ import annotations

import unittest

from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available
from transformers.testing_utils import require_tf, require_tokenizers, slow
from transformers.utils import cached_property

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


if is_tf_available():
 import tensorflow as tf

 from transformers import TFAutoModelForSeqaSeqLM, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel




@require_tf
class 					snake_case__						:






     """simple docstring"""


     _SCREAMING_SNAKE_CASE						=	BlenderbotSmallConfig
     _SCREAMING_SNAKE_CASE						=	{}
     _SCREAMING_SNAKE_CASE						=	"""gelu"""






     def __init__(       self  :  List[Any], _snake_case  :  Union[str, Any], _snake_case  :  List[str]=1_3, _snake_case  :  List[Any]=7, _snake_case  :  Dict=True, _snake_case  :  Any=False, _snake_case  :  Optional[int]=9_9, _snake_case  :  Dict=3_2, _snake_case  :  Tuple=2, _snake_case  :  Optional[int]=4, _snake_case  :  List[Any]=3_7, _snake_case  :  Optional[int]=0.1, _snake_case  :  List[str]=0.1, _snake_case  :  Dict=2_0, _snake_case  :  Union[str, Any]=2, _snake_case  :  Optional[Any]=1, _snake_case  :  Optional[int]=0, )   ->str:
            snake_case__							:	List[str]   	=	parent
            snake_case__							:	Union[str, Any]   	=	batch_size
            snake_case__							:	Optional[Any]   	=	seq_length
            snake_case__							:	str   	=	is_training
            snake_case__							:	Any   	=	use_labels
            snake_case__							:	Optional[Any]   	=	vocab_size
            snake_case__							:	List[Any]   	=	hidden_size
            snake_case__							:	List[str]   	=	num_hidden_layers
            snake_case__							:	List[str]   	=	num_attention_heads
            snake_case__							:	Tuple   	=	intermediate_size

            snake_case__							:	Optional[int]   	=	hidden_dropout_prob
            snake_case__							:	List[Any]   	=	attention_probs_dropout_prob
            snake_case__							:	int   	=	max_position_embeddings
            snake_case__							:	Optional[Any]   	=	eos_token_id
            snake_case__							:	List[Any]   	=	pad_token_id
            snake_case__							:	Any   	=	bos_token_id






     def    lowercase_   (       self  :  Optional[Any]					)   ->Optional[int]:
            snake_case__							:	int   	=	ids_tensor([self.batch_size, self.seq_length - 1], self.vocab_size					)
            snake_case__							:	int   	=	tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size					), 1					)
            snake_case__							:	List[str]   	=	tf.concat([input_ids, eos_tensor], axis=1					)

            snake_case__							:	Any   	=	ids_tensor([self.batch_size, self.seq_length], self.vocab_size					)

            snake_case__							:	Dict   	=	self.config_cls(
                vocab_size=self.vocab_size, d_model=self.hidden_size, encoder_layers=self.num_hidden_layers, decoder_layers=self.num_hidden_layers, encoder_attention_heads=self.num_attention_heads, decoder_attention_heads=self.num_attention_heads, encoder_ffn_dim=self.intermediate_size, decoder_ffn_dim=self.intermediate_size, dropout=self.hidden_dropout_prob, attention_dropout=self.attention_probs_dropout_prob, max_position_embeddings=self.max_position_embeddings, eos_token_ids=[2], bos_token_id=self.bos_token_id, pad_token_id=self.pad_token_id, decoder_start_token_id=self.pad_token_id, **self.config_updates, )
            snake_case__							:	str   	=	prepare_blenderbot_small_inputs_dict(_snake_case, _snake_case, _snake_case					)
            return config, inputs_dict






     def    lowercase_   (       self  :  Dict, _snake_case  :  Dict, _snake_case  :  List[Any]					)   ->Tuple:
            snake_case__							:	str   	=	TFBlenderbotSmallModel(config=_snake_case					).get_decoder()
            snake_case__							:	List[str]   	=	inputs_dict['input_ids']

            snake_case__							:	Tuple   	=	input_ids[:1, :]
            snake_case__							:	str   	=	inputs_dict['attention_mask'][:1, :]
            snake_case__							:	Optional[Any]   	=	inputs_dict['head_mask']
            snake_case__							:	Union[str, Any]   	=	1

            # first forward pass
            snake_case__							:	Dict   	=	model(_snake_case, attention_mask=_snake_case, head_mask=_snake_case, use_cache=_snake_case					)

            snake_case__	,				snake_case__							:	List[Any]   	=	outputs.to_tuple()

            # create hypothetical next token and extent to next_input_ids
            snake_case__							:	Optional[int]   	=	ids_tensor((self.batch_size, 3), config.vocab_size					)
            snake_case__							:	Any   	=	tf.cast(ids_tensor((self.batch_size, 3), 2					), tf.inta					)

            # append to next input_ids and
            snake_case__							:	int   	=	tf.concat([input_ids, next_tokens], axis=-1					)
            snake_case__							:	List[str]   	=	tf.concat([attention_mask, next_attn_mask], axis=-1					)

            snake_case__							:	Tuple   	=	model(_snake_case, attention_mask=_snake_case					)[0]
            snake_case__							:	int   	=	model(_snake_case, attention_mask=_snake_case, past_key_values=_snake_case					)[0]

            self.parent.assertEqual(next_tokens.shape[1], output_from_past.shape[1]					)

            # select random slice
            snake_case__							:	List[str]   	=	int(ids_tensor((1,), output_from_past.shape[-1]					)					)
            snake_case__							:	Tuple   	=	output_from_no_past[:, -3:, random_slice_idx]
            snake_case__							:	List[Any]   	=	output_from_past[:, :, random_slice_idx]

            # test that outputs are equal for slice
            tf.debugging.assert_near(_snake_case, _snake_case, rtol=1e-3					)


def        lowercase_							(A : Dict		,					A : Any		,					A : Optional[int]		,					A : Dict=None		,					A : int=None		,					A : List[str]=None		,					A : Union[str, Any]=None		,					A : Optional[Any]=None		,					):
       if attention_mask is None:
              snake_case__							:	Union[str, Any]   	=	tf.cast(tf.math.not_equal(A		,					config.pad_token_id      )		,					tf.inta      )
       if decoder_attention_mask is None:
              snake_case__							:	List[str]   	=	tf.concat(
                  [
                      tf.ones(decoder_input_ids[:, :1].shape		,					dtype=tf.inta      ),
                      tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:]		,					config.pad_token_id      )		,					tf.inta      ),
                  ]		,					axis=-1		,					)
       if head_mask is None:
              snake_case__							:	Tuple   	=	tf.ones((config.encoder_layers, config.encoder_attention_heads)      )
       if decoder_head_mask is None:
              snake_case__							:	int   	=	tf.ones((config.decoder_layers, config.decoder_attention_heads)      )
       if cross_attn_head_mask is None:
              snake_case__							:	Any   	=	tf.ones((config.decoder_layers, config.decoder_attention_heads)      )
       return {
           "input_ids": input_ids,
           "decoder_input_ids": decoder_input_ids,
           "attention_mask": attention_mask,
           "decoder_attention_mask": decoder_attention_mask,
           "head_mask": head_mask,
           "decoder_head_mask": decoder_head_mask,
           "cross_attn_head_mask": cross_attn_head_mask,
       }




@require_tf
class 					snake_case__						(       lowerCAmelCase_				,     lowerCAmelCase_				,     unittest.TestCase     ):






     """simple docstring"""


     _SCREAMING_SNAKE_CASE						=	(
         (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else ()
     )
     _SCREAMING_SNAKE_CASE						=	(TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else ()
     _SCREAMING_SNAKE_CASE						=	(
         {
             """conversational""": TFBlenderbotSmallForConditionalGeneration,
             """feature-extraction""": TFBlenderbotSmallModel,
             """summarization""": TFBlenderbotSmallForConditionalGeneration,
             """text2text-generation""": TFBlenderbotSmallForConditionalGeneration,
             """translation""": TFBlenderbotSmallForConditionalGeneration,
         }
         if is_tf_available()
         else {}
     )
     _SCREAMING_SNAKE_CASE						=	True
     _SCREAMING_SNAKE_CASE						=	False
     _SCREAMING_SNAKE_CASE						=	False






     def    lowercase_   (       self  :  List[Any]					)   ->List[str]:
            snake_case__							:	Optional[int]   	=	TFBlenderbotSmallModelTester(self					)
            snake_case__							:	List[Any]   	=	ConfigTester(self, config_class=_snake_case					)






     def    lowercase_   (       self  :  List[Any]					)   ->Any:
            self.config_tester.run_common_tests()






     def    lowercase_   (       self  :  Union[str, Any]					)   ->Optional[Any]:
            snake_case__							:	List[Any]   	=	self.model_tester.prepare_config_and_inputs_for_common()
            self.model_tester.check_decoder_model_past_large_inputs(*_snake_case					)




@require_tokenizers
@require_tf
class 					snake_case__						(       unittest.TestCase     ):






     """simple docstring"""


     _SCREAMING_SNAKE_CASE						=	[
         """Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like """
         """  i'm going to throw up.\nand why is that?"""
     ]
     _SCREAMING_SNAKE_CASE						=	"""facebook/blenderbot_small-90M"""






     @cached_property
     def    lowercase_   (       self  :  List[Any]					)   ->List[Any]:
            # use "old" tokenizer here because of bug when downloading new tokenizer
            return BlenderbotSmallTokenizer.from_pretrained('facebook/blenderbot-90M'					)






     @cached_property
     def    lowercase_   (       self  :  List[Any]					)   ->List[str]:
            snake_case__							:	Tuple   	=	TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name					)
            return model






     @slow
     def    lowercase_   (       self  :  Union[str, Any]					)   ->Optional[int]:
            snake_case__							:	Any   	=	self.tokenizer(self.src_text, return_tensors='tf'					)
            snake_case__							:	List[str]   	=	self.model.generate(
                model_inputs.input_ids, attention_mask=model_inputs.attention_mask, num_beams=2, use_cache=_snake_case, )
            snake_case__							:	List[str]   	=	self.tokenizer.batch_decode(generated_ids.numpy(), skip_special_tokens=_snake_case					)[0]
            assert generated_words in (
                "i don't know. i just feel like i'm going to throw up. it's not fun.",
                "i'm not sure. i just feel like i've been feeling like i have to be in a certain place",
                "i'm not sure. i just feel like i've been in a bad situation.",
            )











from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


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

a_   :List[str]        =      "\\nThe BLEU score has some undesirable properties when used for single\nsentences, as it was designed to be a corpus measure. We therefore\nuse a slightly different score for our RL experiments which we call\nthe 'GLEU score'. For the GLEU score, we record all sub-sequences of\n1, 2, 3 or 4 tokens in output and target sequence (n-grams). We then\ncompute a recall, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the target (ground truth) sequence,\nand a precision, which is the ratio of the number of matching n-grams\nto the number of total n-grams in the generated output sequence. Then\nGLEU score is simply the minimum of recall and precision. This GLEU\nscore's range is always between 0 (no matches) and 1 (all match) and\nit is symmetrical when switching output and target. According to\nour experiments, GLEU score correlates quite well with the BLEU\nmetric on a corpus level but does not have its drawbacks for our per\nsentence reward objective.\n"

a_   :List[str]        =      "\\nComputes corpus-level Google BLEU (GLEU) score of translated segments against one or more references.\nInstead of averaging the sentence level GLEU scores (i.e. macro-average precision), Wu et al. (2016) sum up the matching\ntokens and the max of hypothesis and reference tokens for each sentence, then compute using the aggregate values.\n\nArgs:\n    predictions (list of str): list of translations to score.\n        Each translation should be tokenized into a list of tokens.\n    references (list of list of str): list of lists of references for each translation.\n        Each reference should be tokenized into a list of tokens.\n    min_len (int): The minimum order of n-gram this function should extract. Defaults to 1.\n    max_len (int): The maximum order of n-gram this function should extract. Defaults to 4.\n\nReturns:\n    'google_bleu': google_bleu score\n\nExamples:\n    Example 1:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.44\n\n    Example 2:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n        ...          'heed', 'the', 'cat', 'commands']\n        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n        ...          'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.61\n\n    Example 3:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n        ...          'heed', 'the', 'cat', 'commands']\n        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n        ...          'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses, references=list_of_references, min_len=2)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.53\n\n    Example 4:\n        >>> hyp1 = ['It', 'is', 'a', 'guide', 'to', 'action', 'which',\n        ...         'ensures', 'that', 'the', 'rubber', 'duck', 'always',\n        ...         'disobeys', 'the', 'commands', 'of', 'the', 'cat']\n        >>> ref1a = ['It', 'is', 'the', 'guiding', 'principle', 'which',\n        ...          'guarantees', 'the', 'rubber', 'duck', 'forces', 'never',\n        ...          'being', 'under', 'the', 'command', 'of', 'the', 'cat']\n        >>> ref1b = ['It', 'is', 'a', 'guide', 'to', 'action', 'that',\n        ...          'ensures', 'that', 'the', 'rubber', 'duck', 'will', 'never',\n        ...          'heed', 'the', 'cat', 'commands']\n        >>> ref1c = ['It', 'is', 'the', 'practical', 'guide', 'for', 'the',\n        ...          'rubber', 'duck', 'army', 'never', 'to', 'heed', 'the', 'directions',\n        ...          'of', 'the', 'cat']\n\n        >>> hyp2 = ['he', 'read', 'the', 'book', 'because', 'he', 'was',\n        ...         'interested', 'in', 'world', 'history']\n        >>> ref2a = ['he', 'was', 'interested', 'in', 'world', 'history',\n        ...          'because', 'he', 'read', 'the', 'book']\n\n        >>> list_of_references = [[ref1a, ref1b, ref1c], [ref2a]]\n        >>> hypotheses = [hyp1, hyp2]\n        >>> google_bleu = datasets.load_metric(\"google_bleu\")\n        >>> results = google_bleu.compute(predictions=hypotheses,references=list_of_references, min_len=2, max_len=6)\n        >>> print(round(results[\"google_bleu\"], 2))\n        0.4\n"




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






     """simple docstring"""


     def    lowercase_   (       self  :  str					)   ->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    lowercase_   (       self  :  str, _snake_case  :  List[List[List[str]]], _snake_case  :  List[List[str]], _snake_case  :  int = 1, _snake_case  :  int = 4, )   ->Dict[str, float]:
            return {
                "google_bleu": gleu_score.corpus_gleu(
                    list_of_references=_snake_case, hypotheses=_snake_case, min_len=_snake_case, max_len=_snake_case					)
            }






