


'''simple docstring'''



from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


A__						:   Any				=    """\
@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__						:   List[Any]				=    """\
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__						:   List[str]				=    """\
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   UpperCAmelCase_    (datasets.Metric    ):





    """simple docstring"""






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










'''simple docstring'''



import re
from typing import Callable, List, Optional, Union

import tensorflow as tf


try:
      from tensorflow.keras.optimizers.legacy import Adam
except ImportError:
      from tensorflow.keras.optimizers import Adam





class   UpperCAmelCase_    (tf.keras.optimizers.schedules.LearningRateSchedule    ):





    """simple docstring"""






    def __init__(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_ = 1.0     ,	SCREAMING_SNAKE_CASE_ = None     ,	)							->	Any:
         super().__init__()
         __lowerCamelCase  :      Optional[Any]														=						initial_learning_rate
         __lowerCamelCase  :      Optional[Any]														=						warmup_steps
         __lowerCamelCase  :      Union[str, Any]														=						power
         __lowerCamelCase  :      Optional[int]														=						decay_schedule_fn
         __lowerCamelCase  :      Any														=						name







    def __call__(				self     ,	SCREAMING_SNAKE_CASE_      )							->	str:
         with tf.name_scope(self.name or 'WarmUp'      ) as name:
              # Implements polynomial warmup. i.e., if global_step < warmup_steps, the
              # learning rate will be `global_step/num_warmup_steps * init_lr`.
              __lowerCamelCase  :      str														=						tf.cast(SCREAMING_SNAKE_CASE_     ,	tf.floataa      )
              __lowerCamelCase  :      Optional[int]														=						tf.cast(self.warmup_steps     ,	tf.floataa      )
              __lowerCamelCase  :      List[Any]														=						global_step_float / warmup_steps_float
              __lowerCamelCase  :      Optional[Any]														=						self.initial_learning_rate * tf.math.pow(SCREAMING_SNAKE_CASE_     ,	self.power      )
              return tf.cond(
                  global_step_float < warmup_steps_float     ,	lambda: warmup_learning_rate     ,	lambda: self.decay_schedule_fn(step - self.warmup_steps      )     ,	name=SCREAMING_SNAKE_CASE_     ,	)







    def  lowercase_							(				self      )							->	Optional[Any]:
         return {
             "initial_learning_rate": self.initial_learning_rate,
             "decay_schedule_fn": self.decay_schedule_fn,
             "warmup_steps": self.warmup_steps,
             "power": self.power,
             "name": self.name,
         }







def      UpperCAmelCase__   (      UpperCAmelCase_       :							float ,       UpperCAmelCase_       :							int ,       UpperCAmelCase_       :							int ,       UpperCAmelCase_       :							float = 0.0 ,       UpperCAmelCase_       :							float = 0.9 ,       UpperCAmelCase_       :							float = 0.999 ,       UpperCAmelCase_       :							float = 1e-8 ,       UpperCAmelCase_       :							Optional[float] = None ,       UpperCAmelCase_       :							Optional[float] = None ,       UpperCAmelCase_       :							float = 0.0 ,       UpperCAmelCase_       :							float = 1.0 ,       UpperCAmelCase_       :							Optional[List[str]] = None ,       )	->						int:
     __lowerCamelCase  :      int														=						tf.keras.optimizers.schedules.PolynomialDecay(
         initial_learning_rate=UpperCAmelCase_ ,       decay_steps=num_train_steps - num_warmup_steps ,       end_learning_rate=init_lr * min_lr_ratio ,       power=UpperCAmelCase_ ,       )
     if num_warmup_steps:
          __lowerCamelCase  :      str														=						WarmUp(
              initial_learning_rate=UpperCAmelCase_ ,       decay_schedule_fn=UpperCAmelCase_ ,       warmup_steps=UpperCAmelCase_ ,       )
     if weight_decay_rate > 0.0:
          __lowerCamelCase  :      List[Any]														=						AdamWeightDecay(
              learning_rate=UpperCAmelCase_ ,       weight_decay_rate=UpperCAmelCase_ ,       beta_a=UpperCAmelCase_ ,       beta_a=UpperCAmelCase_ ,       epsilon=UpperCAmelCase_ ,       clipnorm=UpperCAmelCase_ ,       global_clipnorm=UpperCAmelCase_ ,       exclude_from_weight_decay=['LayerNorm', 'layer_norm', 'bias'] ,       include_in_weight_decay=UpperCAmelCase_ ,       )
     else:
          __lowerCamelCase  :      Tuple														=						tf.keras.optimizers.Adam(
              learning_rate=UpperCAmelCase_ ,       beta_a=UpperCAmelCase_ ,       beta_a=UpperCAmelCase_ ,       epsilon=UpperCAmelCase_ ,       clipnorm=UpperCAmelCase_ ,       global_clipnorm=UpperCAmelCase_ ,       )
     # We return the optimizer and the LR scheduler in order to better track the
     # evolution of the LR independently of the optimizer.
     return optimizer, lr_schedule





class   UpperCAmelCase_    (_UpperCAmelCase    ):





    """simple docstring"""






    def __init__(				self     ,	SCREAMING_SNAKE_CASE_ = 0.0_0_1     ,	SCREAMING_SNAKE_CASE_ = 0.9     ,	SCREAMING_SNAKE_CASE_ = 0.9_9_9     ,	SCREAMING_SNAKE_CASE_ = 1E-7     ,	SCREAMING_SNAKE_CASE_ = False     ,	SCREAMING_SNAKE_CASE_ = 0.0     ,	SCREAMING_SNAKE_CASE_ = None     ,	SCREAMING_SNAKE_CASE_ = None     ,	SCREAMING_SNAKE_CASE_ = "AdamWeightDecay"     ,	**SCREAMING_SNAKE_CASE_     ,	)							->	int:
         super().__init__(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	**SCREAMING_SNAKE_CASE_      )
         __lowerCamelCase  :      int														=						weight_decay_rate
         __lowerCamelCase  :      str														=						include_in_weight_decay
         __lowerCamelCase  :      List[Any]														=						exclude_from_weight_decay







    @classmethod
    def  lowercase_							(				cls     ,	SCREAMING_SNAKE_CASE_      )							->	Dict:
         __lowerCamelCase  :      Any														=						{'WarmUp': WarmUp}
         return super(SCREAMING_SNAKE_CASE_     ,	cls      ).from_config(SCREAMING_SNAKE_CASE_     ,	custom_objects=SCREAMING_SNAKE_CASE_      )







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )							->	Optional[int]:
         super(SCREAMING_SNAKE_CASE_     ,	self      )._prepare_local(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )
         __lowerCamelCase  :      Union[str, Any]														=						tf.constant(
             self.weight_decay_rate     ,	name='adam_weight_decay_rate'      )







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )							->	int:
         __lowerCamelCase  :      Tuple														=						self._do_use_weight_decay(var.name      )
         if do_decay:
              return var.assign_sub(
                  learning_rate * var * apply_state[(var.device, var.dtype.base_dtype)]['weight_decay_rate']     ,	use_locking=self._use_locking     ,	)
         return tf.no_op()







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=None     ,	**SCREAMING_SNAKE_CASE_      )							->	List[str]:
         __lowerCamelCase							,			__lowerCamelCase  :      Optional[Any]														=						list(zip(*SCREAMING_SNAKE_CASE_      )      )
         return super(SCREAMING_SNAKE_CASE_     ,	self      ).apply_gradients(zip(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )     ,	name=SCREAMING_SNAKE_CASE_     ,	**SCREAMING_SNAKE_CASE_      )







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )							->	str:
         if apply_state is None:
              return self._decayed_lr_t[var_dtype], {}

         __lowerCamelCase  :      Optional[int]														=						apply_state or {}
         __lowerCamelCase  :      Dict														=						apply_state.get((var_device, var_dtype)      )
         if coefficients is None:
              __lowerCamelCase  :      List[Any]														=						self._fallback_apply_state(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )
              __lowerCamelCase  :      Optional[Any]														=						coefficients

         return coefficients["lr_t"], {"apply_state": apply_state}







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=None      )							->	str:
         __lowerCamelCase							,			__lowerCamelCase  :      Dict														=						self._get_lr(var.device     ,	var.dtype.base_dtype     ,	SCREAMING_SNAKE_CASE_      )
         __lowerCamelCase  :      Optional[Any]														=						self._decay_weights_op(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )
         with tf.control_dependencies([decay]      ):
              return super(SCREAMING_SNAKE_CASE_     ,	self      )._resource_apply_dense(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	**SCREAMING_SNAKE_CASE_      )







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_=None      )							->	Union[str, Any]:
         __lowerCamelCase							,			__lowerCamelCase  :      Tuple														=						self._get_lr(var.device     ,	var.dtype.base_dtype     ,	SCREAMING_SNAKE_CASE_      )
         __lowerCamelCase  :      List[Any]														=						self._decay_weights_op(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      )
         with tf.control_dependencies([decay]      ):
              return super(SCREAMING_SNAKE_CASE_     ,	self      )._resource_apply_sparse(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_     ,	**SCREAMING_SNAKE_CASE_      )







    def  lowercase_							(				self      )							->	List[Any]:
         __lowerCamelCase  :      Any														=						super().get_config()
         config.update({'weight_decay_rate': self.weight_decay_rate}      )
         return config







    def  lowercase_							(				self     ,	SCREAMING_SNAKE_CASE_      )							->	Dict:
         if self.weight_decay_rate == 0:
              return False

         if self._include_in_weight_decay:
              for r in self._include_in_weight_decay:
                   if re.search(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      ) is not None:
                        return True

         if self._exclude_from_weight_decay:
              for r in self._exclude_from_weight_decay:
                   if re.search(SCREAMING_SNAKE_CASE_     ,	SCREAMING_SNAKE_CASE_      ) is not None:
                        return False
         return True







class   UpperCAmelCase_    (_UpperCAmelCase    ):





    """simple docstring"""






    def __init__(				self      )							->	Tuple:
         __lowerCamelCase  :      Tuple														=						[]
         __lowerCamelCase  :      Optional[Any]														=						None







    @property
    def  lowercase_							(				self      )							->	List[str]:
         if self._accum_steps is None:
              __lowerCamelCase  :      Tuple														=						tf.Variable(
                  tf.constant(0     ,	dtype=tf.intaa      )     ,	trainable=SCREAMING_SNAKE_CASE_     ,	synchronization=tf.VariableSynchronization.ON_READ     ,	aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA     ,	)

         return self._accum_steps.value()







    @property
    def  lowercase_							(				self      )							->	List[str]:
         if not self._gradients:
              raise ValueError('The accumulator should be called first to initialize the gradients'      )
         return [gradient.value() if gradient is not None else gradient for gradient in self._gradients]







    def __call__(				self     ,	SCREAMING_SNAKE_CASE_      )							->	str:
         if not self._gradients:
              __lowerCamelCase  :      List[str]														=						self.step  # Create the step variable.
              self._gradients.extend(
                  [
                      tf.Variable(
                          tf.zeros_like(SCREAMING_SNAKE_CASE_      )     ,	trainable=SCREAMING_SNAKE_CASE_     ,	synchronization=tf.VariableSynchronization.ON_READ     ,	aggregation=tf.VariableAggregation.ONLY_FIRST_REPLICA     ,	)
                      if gradient is not None
                      else gradient
                      for gradient in gradients
                  ]      )
         if len(SCREAMING_SNAKE_CASE_      ) != len(self._gradients      ):
              raise ValueError(f'Expected {len(self._gradients      )} gradients, but got {len(SCREAMING_SNAKE_CASE_      )}'      )

         for accum_gradient, gradient in zip(self._gradients     ,	SCREAMING_SNAKE_CASE_      ):
              if accum_gradient is not None and gradient is not None:
                   accum_gradient.assign_add(SCREAMING_SNAKE_CASE_      )

         self._accum_steps.assign_add(1      )







    def  lowercase_							(				self      )							->	int:
         if not self._gradients:
              return
         self._accum_steps.assign(0      )
         for gradient in self._gradients:
              if gradient is not None:
                   gradient.assign(tf.zeros_like(SCREAMING_SNAKE_CASE_      )      )






