


from __future__ import annotations

import unittest

from transformers import XGLMConfig, XGLMTokenizer, is_tf_available
from transformers.testing_utils import require_tf, slow

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


if is_tf_available():
  import tensorflow as tf

  from transformers.models.xglm.modeling_tf_xglm import (
      TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST,
      TFXGLMForCausalLM,
      TFXGLMModel,
  )







@require_tf
class       lowerCamelCase__   :
     SCREAMING_SNAKE_CASE__      			=			XGLMConfig
     SCREAMING_SNAKE_CASE__      			=			{}
     SCREAMING_SNAKE_CASE__      			=			'''gelu'''





     def __init__(self		,     UpperCAmelCase		,     UpperCAmelCase=1_4		,     UpperCAmelCase=7		,     UpperCAmelCase=True		,     UpperCAmelCase=True		,     UpperCAmelCase=True		,     UpperCAmelCase=9_9		,     UpperCAmelCase=3_2		,     UpperCAmelCase=2		,     UpperCAmelCase=4		,     UpperCAmelCase=3_7		,     UpperCAmelCase="gelu"		,     UpperCAmelCase=0.1		,     UpperCAmelCase=0.1		,     UpperCAmelCase=5_1_2		,     UpperCAmelCase=0.02		,     )     ->   List[Any]:
      _lowercase							      =parent
      _lowercase							      =batch_size
      _lowercase							      =seq_length
      _lowercase							      =is_training
      _lowercase							      =use_input_mask
      _lowercase							      =use_labels
      _lowercase							      =vocab_size
      _lowercase							      =d_model
      _lowercase							      =num_hidden_layers
      _lowercase							      =num_attention_heads
      _lowercase							      =ffn_dim
      _lowercase							      =activation_function
      _lowercase							      =activation_dropout
      _lowercase							      =attention_dropout
      _lowercase							      =max_position_embeddings
      _lowercase							      =initializer_range
      _lowercase							      =None
      _lowercase							      =0
      _lowercase							      =2
      _lowercase							      =1





     def      __A					(self       )     ->   List[str]:
      return XGLMConfig.from_pretrained('''facebook/xglm-564M'''       )





     def      __A					(self       )     ->   List[str]:
      _lowercase							      =tf.clip_by_value(
          ids_tensor([self.batch_size, self.seq_length]		,     self.vocab_size       )		,     clip_value_min=0		,     clip_value_max=3       )

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

      _lowercase							      =self.get_config()

      _lowercase							      =floats_tensor([self.num_hidden_layers, self.num_attention_heads]		,     2       )

      return (
          config,
          input_ids,
          input_mask,
          head_mask,
      )





     def      __A					(self       )     ->   int:
      return XGLMConfig(
          vocab_size=self.vocab_size		,     d_model=self.hidden_size		,     num_layers=self.num_hidden_layers		,     attention_heads=self.num_attention_heads		,     ffn_dim=self.ffn_dim		,     activation_function=self.activation_function		,     activation_dropout=self.activation_dropout		,     attention_dropout=self.attention_dropout		,     max_position_embeddings=self.max_position_embeddings		,     initializer_range=self.initializer_range		,     use_cache=UpperCAmelCase		,     bos_token_id=self.bos_token_id		,     eos_token_id=self.eos_token_id		,     pad_token_id=self.pad_token_id		,     return_dict=UpperCAmelCase		,     )





     def      __A					(self       )     ->   str:
      _lowercase							      =self.prepare_config_and_inputs()

      (
          (
          _lowercase
      )      ,    (
          _lowercase
      )      ,    (
          _lowercase
      )      ,    (
          _lowercase
      )      ,    
      )							      =config_and_inputs

      _lowercase							      ={
          '''input_ids''': input_ids,
          '''head_mask''': head_mask,
      }

      return config, inputs_dict







@require_tf
class       lowerCamelCase__   (       lowerCAmelCase   ,							lowerCAmelCase   ,							unittest.TestCase):
     SCREAMING_SNAKE_CASE__      			=			(TFXGLMModel, TFXGLMForCausalLM) if is_tf_available() else ()
     SCREAMING_SNAKE_CASE__      			=			(TFXGLMForCausalLM,) if is_tf_available() else ()
     SCREAMING_SNAKE_CASE__      			=			(
         {'''feature-extraction''': TFXGLMModel, '''text-generation''': TFXGLMForCausalLM} if is_tf_available() else {}
     )
     SCREAMING_SNAKE_CASE__      			=			False
     SCREAMING_SNAKE_CASE__      			=			False
     SCREAMING_SNAKE_CASE__      			=			False





     def      __A					(self       )     ->   Optional[Any]:
      _lowercase							      =TFXGLMModelTester(self       )
      _lowercase							      =ConfigTester(self		,     config_class=UpperCAmelCase		,     n_embd=3_7       )





     def      __A					(self       )     ->   Tuple:
      self.config_tester.run_common_tests()





     @slow
     def      __A					(self       )     ->   str:
      for model_name in TF_XGLM_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
       _lowercase							      =TFXGLMModel.from_pretrained(UpperCAmelCase       )
       self.assertIsNotNone(UpperCAmelCase       )





     @unittest.skip(reason='''Currently, model embeddings are going to undergo a major refactor.'''       )
     def      __A					(self       )     ->   Optional[Any]:
      super().test_resize_token_embeddings()







@require_tf
class       lowerCamelCase__   (       unittest.TestCase):





     @slow
     def      __A					(self		,     UpperCAmelCase=True       )     ->   str:
      _lowercase							      =TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''       )
      _lowercase							      =tf.convert_to_tensor([[2, 2_6_8, 9_8_6_5]]		,     dtype=tf.intaa       )  # The dog
      # </s> The dog is a very friendly dog. He is very affectionate and loves to play with other
      # fmt: off
      _lowercase							      =[2, 2_6_8, 9_8_6_5, 6_7, 1_1, 1_9_8_8, 5_7_2_5_2, 9_8_6_5, 5, 9_8_4, 6_7, 1_9_8_8, 2_1_3_8_3_8, 1_6_5_8, 5_3, 7_0_4_4_6, 3_3, 6_6_5_7, 2_7_8, 1_5_8_1]
      # fmt: on
      _lowercase							      =model.generate(UpperCAmelCase		,     do_sample=UpperCAmelCase		,     num_beams=1       )
      if verify_outputs:
       self.assertListEqual(output_ids[0].numpy().tolist()		,     UpperCAmelCase       )





     @slow
     def      __A					(self       )     ->   int:
      _lowercase							      =XGLMTokenizer.from_pretrained('''facebook/xglm-564M'''       )
      _lowercase							      =TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''       )

      tf.random.set_seed(0       )
      _lowercase							      =tokenizer('''Today is a nice day and'''		,     return_tensors='''tf'''       )
      _lowercase							      =tokenized.input_ids
      # forces the generation to happen on CPU, to avoid GPU-related quirks (and assure same output regardless of the available devices)
      with tf.device(''':/CPU:0'''       ):
       _lowercase							      =model.generate(UpperCAmelCase		,     do_sample=UpperCAmelCase		,     seed=[7, 0]       )
      _lowercase							      =tokenizer.decode(output_ids[0]		,     skip_special_tokens=UpperCAmelCase       )

      _lowercase							      =(
          '''Today is a nice day and warm evening here over Southern Alberta!! Today when they closed schools due'''
      )
      self.assertEqual(UpperCAmelCase		,     UpperCAmelCase       )





     @slow
     def      __A					(self       )     ->   str:
      _lowercase							      =TFXGLMForCausalLM.from_pretrained('''facebook/xglm-564M'''       )
      _lowercase							      =XGLMTokenizer.from_pretrained('''facebook/xglm-564M'''       )

      _lowercase							      ='''left'''

      # use different length sentences to test batching
      _lowercase							      =[
          '''This is an extremelly long sentence that only exists to test the ability of the model to cope with '''
          '''left-padding, such as in batched generation. The output for the sequence below should be the same '''
          '''regardless of whether left padding is applied or not. When''',
          '''Hello, my dog is a little''',
      ]

      _lowercase							      =tokenizer(UpperCAmelCase		,     return_tensors='''tf'''		,     padding=UpperCAmelCase       )
      _lowercase							      =inputs['''input_ids''']

      _lowercase							      =model.generate(input_ids=UpperCAmelCase		,     attention_mask=inputs['''attention_mask''']		,     max_new_tokens=1_2       )

      _lowercase							      =tokenizer(sentences[0]		,     return_tensors='''tf'''       ).input_ids
      _lowercase							      =model.generate(input_ids=UpperCAmelCase		,     max_new_tokens=1_2       )

      _lowercase							      =tokenizer(sentences[1]		,     return_tensors='''tf'''       ).input_ids
      _lowercase							      =model.generate(input_ids=UpperCAmelCase		,     max_new_tokens=1_2       )

      _lowercase							      =tokenizer.batch_decode(UpperCAmelCase		,     skip_special_tokens=UpperCAmelCase       )
      _lowercase							      =tokenizer.decode(output_non_padded[0]		,     skip_special_tokens=UpperCAmelCase       )
      _lowercase							      =tokenizer.decode(output_padded[0]		,     skip_special_tokens=UpperCAmelCase       )

      _lowercase							      =[
          '''This is an extremelly long sentence that only exists to test the ability of the model to cope with '''
          '''left-padding, such as in batched generation. The output for the sequence below should be the same '''
          '''regardless of whether left padding is applied or not. When left padding is applied, the sequence will be '''
          '''a single''',
          '''Hello, my dog is a little bit of a shy one, but he is very friendly''',
      ]
      self.assertListEqual(UpperCAmelCase		,     UpperCAmelCase       )
      self.assertListEqual(UpperCAmelCase		,     [non_padded_sentence, padded_sentence]       )





import comet  # From: unbabel-comet
import torch

import datasets


UpperCAmelCase__   	=							datasets.logging.get_logger(__name__)

UpperCAmelCase__   	=							'''\
@inproceedings{rei-EtAl:2020:WMT,
   author    = {Rei, Ricardo  and  Stewart, Craig  and  Farinha, Ana C  and  Lavie, Alon},
   title     = {Unbabel\'s Participation in the WMT20 Metrics Shared Task},
   booktitle      = {Proceedings of the Fifth Conference on Machine Translation},
   month          = {November},
   year           = {2020},
   address        = {Online},
   publisher      = {Association for Computational Linguistics},
   pages     = {909--918},
}
@inproceedings{rei-etal-2020-comet,
   title = "{COMET}: A Neural Framework for {MT} Evaluation",
   author = "Rei, Ricardo  and
      Stewart, Craig  and
      Farinha, Ana C  and
      Lavie, Alon",
   booktitle = "Proceedings of the 2020 Conference on Empirical Methods in Natural Language Processing (EMNLP)",
   month = nov,
   year = "2020",
   address = "Online",
   publisher = "Association for Computational Linguistics",
   url = "https://www.aclweb.org/anthology/2020.emnlp-main.213",
   pages = "2685--2702",
}
'''

UpperCAmelCase__   	=							'''\
Crosslingual Optimized Metric for Evaluation of Translation (COMET) is an open-source framework used to train Machine Translation metrics that achieve high levels of correlation with different types of human judgments (HTER, DA\'s or MQM).
With the release of the framework the authors also released fully trained models that were used to compete in the WMT20 Metrics Shared Task achieving SOTA in that years competition.

See the [README.md] file at https://unbabel.github.io/COMET/html/models.html for more information.
'''

UpperCAmelCase__   	=							'''
COMET score.

Args:

`sources` (list of str): Source sentences
`predictions` (list of str): candidate translations
`references` (list of str): reference translations
`cuda` (bool): If set to True, runs COMET using GPU
`show_progress` (bool): Shows progress
`model`: COMET model to be used. Will default to `wmt-large-da-estimator-1719` if None.

Returns:
    `samples`: List of dictionaries with `src`, `mt`, `ref` and `score`.
    `scores`: List of scores.

Examples:

    >>> comet_metric = datasets.load_metric(\'comet\')
    >>> # comet_metric = load_metric(\'comet\', \'wmt20-comet-da\')  # you can also choose which model to use
    >>> source = ["Dem Feuer konnte Einhalt geboten werden", "Schulen und Kindergärten wurden eröffnet."]
    >>> hypothesis = ["The fire could be stopped", "Schools and kindergartens were open"]
    >>> reference = ["They were able to control the fire.", "Schools and kindergartens opened"]
    >>> results = comet_metric.compute(predictions=hypothesis, references=reference, sources=source)
    >>> print([round(v, 2) for v in results["scores"]])
    [0.19, 0.92]
'''







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





     def      __A					(self       )     ->   Optional[int]:
      return datasets.MetricInfo(
          description=_DESCRIPTION		,     citation=_CITATION		,     homepage='''https://unbabel.github.io/COMET/html/index.html'''		,     inputs_description=_KWARGS_DESCRIPTION		,     features=datasets.Features(
              {
                  '''sources''': datasets.Value('''string'''		,     id='''sequence'''       ),
                  '''predictions''': datasets.Value('''string'''		,     id='''sequence'''       ),
                  '''references''': datasets.Value('''string'''		,     id='''sequence'''       ),
              }       )		,     codebase_urls=['''https://github.com/Unbabel/COMET''']		,     reference_urls=[
              '''https://github.com/Unbabel/COMET''',
              '''https://www.aclweb.org/anthology/2020.emnlp-main.213/''',
              '''http://www.statmt.org/wmt20/pdf/2020.wmt-1.101.pdf6''',
          ]		,     )





     def      __A					(self		,     UpperCAmelCase       )     ->   Dict:
      if self.config_name == "default":
       _lowercase							      =comet.load_from_checkpoint(comet.download_model('''wmt20-comet-da'''       )       )
      else:
       _lowercase							      =comet.load_from_checkpoint(comet.download_model(self.config_name       )       )





     def      __A					(self		,     UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase		,     UpperCAmelCase=None		,     UpperCAmelCase=False       )     ->   int:
      if gpus is None:
       _lowercase							      =1 if torch.cuda.is_available() else 0
      _lowercase							      ={'''src''': sources, '''mt''': predictions, '''ref''': references}
      _lowercase							      =[dict(zip(UpperCAmelCase		,     UpperCAmelCase       )       ) for t in zip(*data.values()       )]
      _lowercase      ,    _lowercase							      =self.scorer.predict(UpperCAmelCase		,     gpus=UpperCAmelCase		,     progress_bar=UpperCAmelCase       )
      return {"mean_score": mean_score, "scores": scores}

