

import torch
from torch import nn






class 	UpperCAmelCase__		(	nn.Module	):






  """simple docstring"""


  def __init__(							self						:		Union[str, Any]     ,       __lowerCamelCase						:		List[Any]     ,       __lowerCamelCase						:		int     ,       __lowerCamelCase						:		Tuple     ,       __lowerCamelCase						:		str     ,       __lowerCamelCase						:		Any=1     ,       __lowerCamelCase						:		List[Any]=False )		->							Optional[Any]:
       super().__init__()

       SCREAMING_SNAKE_CASE__   =   n_token
       SCREAMING_SNAKE_CASE__   =   d_embed
       SCREAMING_SNAKE_CASE__   =   d_proj

       SCREAMING_SNAKE_CASE__   =   cutoffs + [n_token]
       SCREAMING_SNAKE_CASE__   =   [0] + self.cutoffs
       SCREAMING_SNAKE_CASE__   =   div_val

       SCREAMING_SNAKE_CASE__   =   self.cutoffs[0]
       SCREAMING_SNAKE_CASE__   =   len(self.cutoffs ) - 1
       SCREAMING_SNAKE_CASE__   =   self.shortlist_size + self.n_clusters

       if self.n_clusters > 0:
            SCREAMING_SNAKE_CASE__   =   nn.Parameter(torch.zeros(self.n_clusters     ,       self.d_embed ) )
            SCREAMING_SNAKE_CASE__   =   nn.Parameter(torch.zeros(self.n_clusters ) )

       SCREAMING_SNAKE_CASE__   =   nn.ModuleList()
       SCREAMING_SNAKE_CASE__   =   nn.ParameterList()

       if div_val == 1:
            for i in range(len(self.cutoffs ) ):
                 if d_proj != d_embed:
                      self.out_projs.append(nn.Parameter(torch.FloatTensor(_UpperCAmelCase     ,       _UpperCAmelCase ) ) )
                 else:
                      self.out_projs.append(_UpperCAmelCase )

            self.out_layers.append(nn.Linear(_UpperCAmelCase     ,       _UpperCAmelCase ) )
       else:
            for i in range(len(self.cutoffs ) ):
                 SCREAMING_SNAKE_CASE__   =   self.cutoff_ends[i], self.cutoff_ends[i + 1]
                 SCREAMING_SNAKE_CASE__   =   d_embed // (div_val**i)

                 self.out_projs.append(nn.Parameter(torch.FloatTensor(_UpperCAmelCase     ,       _UpperCAmelCase ) ) )

                 self.out_layers.append(nn.Linear(_UpperCAmelCase     ,       r_idx - l_idx ) )

       SCREAMING_SNAKE_CASE__   =   keep_order






  def 				lowercase_		(							self						:		int     ,       __lowerCamelCase						:		Union[str, Any]     ,       __lowerCamelCase						:		Any     ,       __lowerCamelCase						:		Union[str, Any]     ,       __lowerCamelCase						:		int )		->							Optional[Any]:
       if proj is None:
            SCREAMING_SNAKE_CASE__   =   nn.functional.linear(_UpperCAmelCase     ,       _UpperCAmelCase     ,       bias=_UpperCAmelCase )
       else:
            # if CUDA_MAJOR <= 9 and CUDA_MINOR <= 1:
            SCREAMING_SNAKE_CASE__   =   nn.functional.linear(_UpperCAmelCase     ,       proj.t().contiguous() )
            SCREAMING_SNAKE_CASE__   =   nn.functional.linear(_UpperCAmelCase     ,       _UpperCAmelCase     ,       bias=_UpperCAmelCase )
            # else:
            #     logit = torch.einsum('bd,de,ev->bv', (hidden, proj, weight.t()))
            #     if bias is not None:
            #         logit = logit + bias

       return logit






  def 				lowercase_		(							self						:		List[str]     ,       __lowerCamelCase						:		int     ,       __lowerCamelCase						:		int=None     ,       __lowerCamelCase						:		List[Any]=False )		->							Dict:

       if labels is not None:
            # Shift so that tokens < n predict n
            SCREAMING_SNAKE_CASE__   =   hidden[..., :-1, :].contiguous()
            SCREAMING_SNAKE_CASE__   =   labels[..., 1:].contiguous()
            SCREAMING_SNAKE_CASE__   =   hidden.view(-1     ,       hidden.size(-1 ) )
            SCREAMING_SNAKE_CASE__   =   labels.view(-1 )
            if hidden.size(0 ) != labels.size(0 ):
                 raise RuntimeError('''Input and labels should have the same size in the batch dimension.''' )
       else:
            SCREAMING_SNAKE_CASE__   =   hidden.view(-1     ,       hidden.size(-1 ) )

       if self.n_clusters == 0:
            SCREAMING_SNAKE_CASE__   =   self._compute_logit(_UpperCAmelCase     ,       self.out_layers[0].weight     ,       self.out_layers[0].bias     ,       self.out_projs[0] )
            if labels is not None:
                 SCREAMING_SNAKE_CASE__   =   labels != -100
                 SCREAMING_SNAKE_CASE__   =   torch.zeros_like(_UpperCAmelCase     ,       dtype=hidden.dtype     ,       device=hidden.device )
                 SCREAMING_SNAKE_CASE__   =   (
                     -nn.functional.log_softmax(_UpperCAmelCase     ,       dim=-1 )[mask].gather(1     ,       labels[mask].unsqueeze(1 ) ).squeeze(1 )
                 )
            else:
                 SCREAMING_SNAKE_CASE__   =   nn.functional.log_softmax(_UpperCAmelCase     ,       dim=-1 )
       else:
            # construct weights and biases
            SCREAMING_SNAKE_CASE__   =   [], []
            for i in range(len(self.cutoffs ) ):
                 if self.div_val == 1:
                      SCREAMING_SNAKE_CASE__   =   self.cutoff_ends[i], self.cutoff_ends[i + 1]
                      SCREAMING_SNAKE_CASE__   =   self.out_layers[0].weight[l_idx:r_idx]
                      SCREAMING_SNAKE_CASE__   =   self.out_layers[0].bias[l_idx:r_idx]
                 else:
                      SCREAMING_SNAKE_CASE__   =   self.out_layers[i].weight
                      SCREAMING_SNAKE_CASE__   =   self.out_layers[i].bias

                 if i == 0:
                      SCREAMING_SNAKE_CASE__   =   torch.cat([weight_i, self.cluster_weight]     ,       dim=0 )
                      SCREAMING_SNAKE_CASE__   =   torch.cat([bias_i, self.cluster_bias]     ,       dim=0 )

                 weights.append(_UpperCAmelCase )
                 biases.append(_UpperCAmelCase )

            SCREAMING_SNAKE_CASE__   =   weights[0], biases[0], self.out_projs[0]

            SCREAMING_SNAKE_CASE__   =   self._compute_logit(_UpperCAmelCase     ,       _UpperCAmelCase     ,       _UpperCAmelCase     ,       _UpperCAmelCase )
            SCREAMING_SNAKE_CASE__   =   nn.functional.log_softmax(_UpperCAmelCase     ,       dim=1 )

            if labels is None:
                 SCREAMING_SNAKE_CASE__   =   hidden.new_empty((head_logit.size(0 ), self.n_token) )
            else:
                 SCREAMING_SNAKE_CASE__   =   torch.zeros_like(_UpperCAmelCase     ,       dtype=hidden.dtype     ,       device=hidden.device )

            SCREAMING_SNAKE_CASE__   =   0
            SCREAMING_SNAKE_CASE__   =   [0] + self.cutoffs
            for i in range(len(_UpperCAmelCase ) - 1 ):
                 SCREAMING_SNAKE_CASE__   =   cutoff_values[i], cutoff_values[i + 1]

                 if labels is not None:
                      SCREAMING_SNAKE_CASE__   =   (labels >= l_idx) & (labels < r_idx)
                      SCREAMING_SNAKE_CASE__   =   mask_i.nonzero().squeeze()

                      if indices_i.numel() == 0:
                           continue

                      SCREAMING_SNAKE_CASE__   =   labels.index_select(0     ,       _UpperCAmelCase ) - l_idx
                      SCREAMING_SNAKE_CASE__   =   head_logprob.index_select(0     ,       _UpperCAmelCase )
                      SCREAMING_SNAKE_CASE__   =   hidden.index_select(0     ,       _UpperCAmelCase )
                 else:
                      SCREAMING_SNAKE_CASE__   =   hidden

                 if i == 0:
                      if labels is not None:
                           SCREAMING_SNAKE_CASE__   =   head_logprob_i.gather(1     ,       target_i[:, None] ).squeeze(1 )
                      else:
                           SCREAMING_SNAKE_CASE__   =   head_logprob[:, : self.cutoffs[0]]
                 else:
                      SCREAMING_SNAKE_CASE__   =   weights[i], biases[i], self.out_projs[i]

                      SCREAMING_SNAKE_CASE__   =   self._compute_logit(_UpperCAmelCase     ,       _UpperCAmelCase     ,       _UpperCAmelCase     ,       _UpperCAmelCase )
                      SCREAMING_SNAKE_CASE__   =   nn.functional.log_softmax(_UpperCAmelCase     ,       dim=1 )
                      SCREAMING_SNAKE_CASE__   =   self.cutoffs[0] + i - 1  # No probability for the head cluster
                      if labels is not None:
                           SCREAMING_SNAKE_CASE__   =   head_logprob_i[:, cluster_prob_idx] + tail_logprob_i.gather(
                               1     ,       target_i[:, None] ).squeeze(1 )
                      else:
                           SCREAMING_SNAKE_CASE__   =   head_logprob[:, cluster_prob_idx, None] + tail_logprob_i
                           SCREAMING_SNAKE_CASE__   =   logprob_i

                 if labels is not None:
                      if (hasattr(self     ,       '''keep_order''' ) and self.keep_order) or keep_order:
                           out.index_copy_(0     ,       _UpperCAmelCase     ,       -logprob_i )
                      else:
                           out[offset : offset + logprob_i.size(0 )].copy_(-logprob_i )
                      offset += logprob_i.size(0 )

       return out







  def 				lowercase_		(							self						:		Union[str, Any]     ,       __lowerCamelCase						:		Any )		->							List[Any]:
       if self.n_clusters == 0:
            SCREAMING_SNAKE_CASE__   =   self._compute_logit(_UpperCAmelCase     ,       self.out_layers[0].weight     ,       self.out_layers[0].bias     ,       self.out_projs[0] )
            return nn.functional.log_softmax(_UpperCAmelCase     ,       dim=-1 )
       else:
            # construct weights and biases
            SCREAMING_SNAKE_CASE__   =   [], []
            for i in range(len(self.cutoffs ) ):
                 if self.div_val == 1:
                      SCREAMING_SNAKE_CASE__   =   self.cutoff_ends[i], self.cutoff_ends[i + 1]
                      SCREAMING_SNAKE_CASE__   =   self.out_layers[0].weight[l_idx:r_idx]
                      SCREAMING_SNAKE_CASE__   =   self.out_layers[0].bias[l_idx:r_idx]
                 else:
                      SCREAMING_SNAKE_CASE__   =   self.out_layers[i].weight
                      SCREAMING_SNAKE_CASE__   =   self.out_layers[i].bias

                 if i == 0:
                      SCREAMING_SNAKE_CASE__   =   torch.cat([weight_i, self.cluster_weight]     ,       dim=0 )
                      SCREAMING_SNAKE_CASE__   =   torch.cat([bias_i, self.cluster_bias]     ,       dim=0 )

                 weights.append(_UpperCAmelCase )
                 biases.append(_UpperCAmelCase )

            SCREAMING_SNAKE_CASE__   =   weights[0], biases[0], self.out_projs[0]
            SCREAMING_SNAKE_CASE__   =   self._compute_logit(_UpperCAmelCase     ,       _UpperCAmelCase     ,       _UpperCAmelCase     ,       _UpperCAmelCase )

            SCREAMING_SNAKE_CASE__   =   hidden.new_empty((head_logit.size(0 ), self.n_token) )
            SCREAMING_SNAKE_CASE__   =   nn.functional.log_softmax(_UpperCAmelCase     ,       dim=1 )

            SCREAMING_SNAKE_CASE__   =   [0] + self.cutoffs
            for i in range(len(_UpperCAmelCase ) - 1 ):
                 SCREAMING_SNAKE_CASE__   =   cutoff_values[i], cutoff_values[i + 1]

                 if i == 0:
                      SCREAMING_SNAKE_CASE__   =   head_logprob[:, : self.cutoffs[0]]
                 else:
                      SCREAMING_SNAKE_CASE__   =   weights[i], biases[i], self.out_projs[i]

                      SCREAMING_SNAKE_CASE__   =   self._compute_logit(_UpperCAmelCase     ,       _UpperCAmelCase     ,       _UpperCAmelCase     ,       _UpperCAmelCase )
                      SCREAMING_SNAKE_CASE__   =   nn.functional.log_softmax(_UpperCAmelCase     ,       dim=1 )

                      SCREAMING_SNAKE_CASE__   =   head_logprob[:, -i] + tail_logprob_i
                      SCREAMING_SNAKE_CASE__   =   logprob_i

            return out





import comet  # From: unbabel-comet
import torch

import datasets


_SCREAMING_SNAKE_CASE					:  List[str]             =      datasets.logging.get_logger(__name__)

_SCREAMING_SNAKE_CASE					:  Any             =      '''\
@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",
}
'''

_SCREAMING_SNAKE_CASE					:  Optional[Any]             =      '''\
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.
'''

_SCREAMING_SNAKE_CASE					:  str             =      '''
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 	UpperCAmelCase__		(	datasets.Metric	):






  """simple docstring"""


  def 				lowercase_		(							self						:		List[Any] )		->							List[str]:
       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 				lowercase_		(							self						:		List[Any]     ,       __lowerCamelCase						:		Dict )		->							Tuple:
       if self.config_name == "default":
            SCREAMING_SNAKE_CASE__   =   comet.load_from_checkpoint(comet.download_model('''wmt20-comet-da''' ) )
       else:
            SCREAMING_SNAKE_CASE__   =   comet.load_from_checkpoint(comet.download_model(self.config_name ) )







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


