



'''simple docstring'''



import baseaa
import io
import json
import os
from copy import deepcopy

from ..optimizer import AcceleratedOptimizer
from ..scheduler import AcceleratedScheduler
class 						lowerCamelCase_				:







						def __init__(	self :   List[Any]					,     lowerCAmelCase__ :   Optional[Any]					):

													"""simple docstring"""

													if isinstance(lowerCAmelCase__					,     lowerCAmelCase__					):
																				# Don't modify user's data should they want to reuse it (e.g. in tests), because once we
																				# modified it, it will not be accepted here again, since `auto` values would have been overridden
																				SCREAMING_SNAKE_CASE       :   Optional[Any]         =      deepcopy(lowerCAmelCase__					)
													elif os.path.exists(lowerCAmelCase__					):
																				with io.open(lowerCAmelCase__					,     '''r'''					,     encoding='''utf-8'''					) as f:
																											SCREAMING_SNAKE_CASE       :   Dict         =      json.load(lowerCAmelCase__					)
													else:
																				try:
																											SCREAMING_SNAKE_CASE       :   List[str]         =      baseaa.urlsafe_baadecode(lowerCAmelCase__					).decode('''utf-8'''					)
																											SCREAMING_SNAKE_CASE       :   Optional[Any]         =      json.loads(lowerCAmelCase__					)
																				except (UnicodeDecodeError, AttributeError, ValueError):
																											raise ValueError(
																											    F"""Expected a string path to an existing deepspeed config, or a dictionary, or a base64 encoded string. Received: {config_file_or_dict}"""					)

													SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      config

													self.set_stage_and_offload()







						def        __lowercase     (	self :   List[str]					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   str         =      self.get_value('''zero_optimization.stage'''					,     -1					)

													# offload
													SCREAMING_SNAKE_CASE       :   List[str]         =      False
													if self.is_zeroa() or self.is_zeroa():
																				SCREAMING_SNAKE_CASE       :   List[str]         =      set(['''cpu''', '''nvme''']					)
																				SCREAMING_SNAKE_CASE       :   Optional[int]         =      set(
																				    [
																				        self.get_value('''zero_optimization.offload_optimizer.device'''					),
																				        self.get_value('''zero_optimization.offload_param.device'''					),
																				    ]					)
																				if len(offload_devices & offload_devices_valid					) > 0:
																											SCREAMING_SNAKE_CASE       :   Optional[Any]         =      True







						def        __lowercase     (	self :   List[Any]					,     lowerCAmelCase__ :   Optional[Any]					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   Tuple         =      self.config

													# find the config node of interest if it exists
													SCREAMING_SNAKE_CASE       :   Any         =      ds_key_long.split('''.'''					)
													SCREAMING_SNAKE_CASE       :   List[str]         =      nodes.pop()
													for node in nodes:
																				SCREAMING_SNAKE_CASE       :   Tuple         =      config.get(lowerCAmelCase__					)
																				if config is None:
																											return None, ds_key

													return config, ds_key







						def        __lowercase     (	self :   str					,     lowerCAmelCase__ :   Dict					,     lowerCAmelCase__ :   Optional[Any]=None					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   Tuple         =      self.find_config_node(lowerCAmelCase__					)
													if config is None:
																				return default
													return config.get(lowerCAmelCase__					,     lowerCAmelCase__					)







						def        __lowercase     (	self :   str					,     lowerCAmelCase__ :   List[Any]					,     lowerCAmelCase__ :   Any=False					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   List[Any]         =      self.config

													# find the config node of interest if it exists
													SCREAMING_SNAKE_CASE       :   Any         =      ds_key_long.split('''.'''					)
													for node in nodes:
																				SCREAMING_SNAKE_CASE       :   Tuple         =      config
																				SCREAMING_SNAKE_CASE       :   Optional[Any]         =      config.get(lowerCAmelCase__					)
																				if config is None:
																											if must_exist:
																																		raise ValueError(F"""Can't find {ds_key_long} entry in the config: {self.config}"""					)
																											else:
																																		return

        # if found remove it
													if parent_config is not None:
																				parent_config.pop(lowerCAmelCase__					)







						def        __lowercase     (	self :   int					,     lowerCAmelCase__ :   Union[str, Any]					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   int         =      self.get_value(lowerCAmelCase__					)
													return False if value is None else bool(lowerCAmelCase__					)







						def        __lowercase     (	self :   Optional[int]					,     lowerCAmelCase__ :   List[str]					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   Dict         =      self.get_value(lowerCAmelCase__					)
													return False if value is None else not bool(lowerCAmelCase__					)







						def        __lowercase     (	self :   Tuple					):

													"""simple docstring"""
													return self._stage == 2







						def        __lowercase     (	self :   Union[str, Any]					):

													"""simple docstring"""
													return self._stage == 3







						def        __lowercase     (	self :   Optional[Any]					):

													"""simple docstring"""
													return self._offload


class 						lowerCamelCase_				:







						def __init__(	self :   Optional[int]					,     lowerCAmelCase__ :   List[str]					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   Dict         =      engine







						def        __lowercase     (	self :   Optional[Any]					,     lowerCAmelCase__ :   List[str]					,     **lowerCAmelCase__ :   int					):

													"""simple docstring"""
													self.engine.backward(lowerCAmelCase__					,     **lowerCAmelCase__					)

													# Deepspeed's `engine.step` performs the following operations:
													# - gradient accumulation check
													# - gradient clipping
													# - optimizer step
													# - zero grad
													# - checking overflow
													# - lr_scheduler step (only if engine.lr_scheduler is not None)
													self.engine.step()
													# and this plugin overrides the above calls with no-ops when Accelerate runs under
													# Deepspeed, but allows normal functionality for non-Deepspeed cases thus enabling a simple
													# training loop that works transparently under many training regimes.


class 						lowerCamelCase_				(       snake_case_      ):







						def __init__(	self :   Dict					,     lowerCAmelCase__ :   List[str]					):

													"""simple docstring"""
													super().__init__(lowerCAmelCase__					,     device_placement=lowerCAmelCase__					,     scaler=lowerCAmelCase__					)
													SCREAMING_SNAKE_CASE       :   Any         =      hasattr(self.optimizer					,     '''overflow'''					)







						def        __lowercase     (	self :   int					,     lowerCAmelCase__ :   List[Any]=None					):

													"""simple docstring"""
													pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed







						def        __lowercase     (	self :   Union[str, Any]					):

													"""simple docstring"""
													pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed







						@property
						def        __lowercase     (	self :   Dict					):

													"""simple docstring"""

													if self.__has_overflow__:
																				return self.optimizer.overflow
													return False


class 						lowerCamelCase_				(       snake_case_      ):







						def __init__(	self :   Dict					,     lowerCAmelCase__ :   List[Any]					,     lowerCAmelCase__ :   str					):

													"""simple docstring"""
													super().__init__(lowerCAmelCase__					,     lowerCAmelCase__					)







						def        __lowercase     (	self :   Union[str, Any]					):

													"""simple docstring"""
													pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed


class 						lowerCamelCase_				:







						def __init__(	self :   Optional[Any]					,     lowerCAmelCase__ :   Any					,     lowerCAmelCase__ :   List[Any]=0.001					,     lowerCAmelCase__ :   Dict=0					,     **lowerCAmelCase__ :   List[Any]					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   Any         =      params
													SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      lr
													SCREAMING_SNAKE_CASE       :   Dict         =      weight_decay
													SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      kwargs


class 						lowerCamelCase_				:







						def __init__(	self :   Optional[int]					,     lowerCAmelCase__ :   Any					,     lowerCAmelCase__ :   Optional[int]=None					,     lowerCAmelCase__ :   Optional[Any]=0					,     **lowerCAmelCase__ :   Any					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   Dict         =      optimizer
													SCREAMING_SNAKE_CASE       :   Any         =      total_num_steps
													SCREAMING_SNAKE_CASE       :   Optional[int]         =      warmup_num_steps
													SCREAMING_SNAKE_CASE       :   Dict         =      kwargs







"""simple docstring"""

from typing import Dict, List

from nltk.translate import gleu_score

import datasets
from datasets import MetricInfo


_UpperCamelCase		     =    """\
@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}
}
"""

_UpperCamelCase		     =    """\
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.
"""

_UpperCamelCase		     =    """\
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 			__a					(						datasets.Metric       ):





       """simple docstring"""


       def 			SCREAMING_SNAKE_CASE_	(   self   ):





        """simple docstring"""

        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			,					snake_case			,					snake_case			,					snake_case = 1			,					snake_case = 4			,					):





        """simple docstring"""

        return {
            "google_bleu": gleu_score.corpus_gleu(
                list_of_references=snake_case			,					hypotheses=snake_case			,					min_len=snake_case			,					max_len=snake_case   )
        }






