




import numpy as np
from nltk.translate import meteor_score

import datasets
from datasets.config import importlib_metadata, version


lowerCAmelCase_					    = version.parse(importlib_metadata.version("""nltk"""))
if NLTK_VERSION >= version.Version("""3.6.4"""):
     from nltk import word_tokenize


lowerCAmelCase_					    = """\
@inproceedings{banarjee2005,
  title     = {{METEOR}: An Automatic Metric for {MT} Evaluation with Improved Correlation with Human Judgments},
  author    = {Banerjee, Satanjeev  and Lavie, Alon},
  booktitle = {Proceedings of the {ACL} Workshop on Intrinsic and Extrinsic Evaluation Measures for Machine Translation and/or Summarization},
  month     = jun,
  year      = {2005},
  address   = {Ann Arbor, Michigan},
  publisher = {Association for Computational Linguistics},
  url       = {https://www.aclweb.org/anthology/W05-0909},
  pages     = {65--72},
}
"""

lowerCAmelCase_					    = """\
METEOR, an automatic metric for machine translation evaluation
that is based on a generalized concept of unigram matching between the
machine-produced translation and human-produced reference translations.
Unigrams can be matched based on their surface forms, stemmed forms,
and meanings; furthermore, METEOR can be easily extended to include more
advanced matching strategies. Once all generalized unigram matches
between the two strings have been found, METEOR computes a score for
this matching using a combination of unigram-precision, unigram-recall, and
a measure of fragmentation that is designed to directly capture how
well-ordered the matched words in the machine translation are in relation
to the reference.

METEOR gets an R correlation value of 0.347 with human evaluation on the Arabic
data and 0.331 on the Chinese data. This is shown to be an improvement on
using simply unigram-precision, unigram-recall and their harmonic F1
combination.
"""

lowerCAmelCase_					    = """
Computes METEOR score of translated segments against one or more references.
Args:
    predictions: list of predictions to score. Each prediction
        should be a string with tokens separated by spaces.
    references: list of reference for each prediction. Each
        reference should be a string with tokens separated by spaces.
    alpha: Parameter for controlling relative weights of precision and recall. default: 0.9
    beta: Parameter for controlling shape of penalty as a function of fragmentation. default: 3
    gamma: Relative weight assigned to fragmentation penalty. default: 0.5
Returns:
    'meteor': meteor score.
Examples:

    >>> meteor = datasets.load_metric('meteor')
    >>> predictions = [\"It is a guide to action which ensures that the military always obeys the commands of the party\"]
    >>> references = [\"It is a guide to action that ensures that the military will forever heed Party commands\"]
    >>> results = meteor.compute(predictions=predictions, references=references)
    >>> print(round(results[\"meteor\"], 4))
    0.6944
"""






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

      def 	__magic_name__(   self		):
        return datasets.MetricInfo(
            description=_DESCRIPTION      ,				citation=_CITATION      ,				inputs_description=_KWARGS_DESCRIPTION      ,				features=datasets.Features(
                {
                    '''predictions''': datasets.Value('''string'''      ,				id='''sequence'''		),
                    '''references''': datasets.Value('''string'''      ,				id='''sequence'''		),
                }		)      ,				codebase_urls=['''https://github.com/nltk/nltk/blob/develop/nltk/translate/meteor_score.py''']      ,				reference_urls=[
                '''https://www.nltk.org/api/nltk.translate.html#module-nltk.translate.meteor_score''',
                '''https://en.wikipedia.org/wiki/METEOR''',
            ]      ,				)

      def 	__magic_name__(   self      ,				__UpperCAmelCase		):
        import nltk

        nltk.download('''wordnet'''		)
        if NLTK_VERSION >= version.Version('''3.6.5'''		):
          nltk.download('''punkt'''		)
        if NLTK_VERSION >= version.Version('''3.6.6'''		):
          nltk.download('''omw-1.4'''		)







      def 	__magic_name__(   self      ,				__UpperCAmelCase      ,				__UpperCAmelCase      ,				__UpperCAmelCase=0.9      ,				__UpperCAmelCase=3      ,				__UpperCAmelCase=0.5		):
        if NLTK_VERSION >= version.Version('''3.6.5'''		):
          lowerCAmelCase__				:  int		       =     [
              meteor_score.single_meteor_score(
                  word_tokenize(__UpperCAmelCase		)      ,				word_tokenize(__UpperCAmelCase		)      ,				alpha=__UpperCAmelCase      ,				beta=__UpperCAmelCase      ,				gamma=__UpperCAmelCase		)
              for ref, pred in zip(__UpperCAmelCase      ,				__UpperCAmelCase		)
          ]
        else:
          lowerCAmelCase__				:  Any		       =     [
              meteor_score.single_meteor_score(__UpperCAmelCase      ,				__UpperCAmelCase      ,				alpha=__UpperCAmelCase      ,				beta=__UpperCAmelCase      ,				gamma=__UpperCAmelCase		)
              for ref, pred in zip(__UpperCAmelCase      ,				__UpperCAmelCase		)
          ]

        return {"meteor": np.mean(__UpperCAmelCase		)}







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      ,				__UpperCAmelCase		):
        if isinstance(__UpperCAmelCase      ,				__UpperCAmelCase		):
          # 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
          lowerCAmelCase__				:  Union[str, Any]		       =     deepcopy(__UpperCAmelCase		)
        elif os.path.exists(__UpperCAmelCase		):
          with io.open(__UpperCAmelCase      ,				'''r'''      ,				encoding='''utf-8'''		) as f:
            lowerCAmelCase__				:  int		       =     json.load(__UpperCAmelCase		)
        else:
          try:
            lowerCAmelCase__				:  Union[str, Any]		       =     baseaa.urlsafe_baadecode(__UpperCAmelCase		).decode('''utf-8'''		)
            lowerCAmelCase__				:  Optional[int]		       =     json.loads(__UpperCAmelCase		)
          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}"""		)

        lowerCAmelCase__				:  Optional[Any]		       =     config

        self.set_stage_and_offload()

      def 	__magic_name__(   self		):
        # zero stage - this is done as early as possible, before model is created, to allow
        # ``is_deepspeed_zero3_enabled`` query and getting to the early deepspeed config object
        # during ``zero.Init()`` which needs to know the dtype, and some other hparams.
        lowerCAmelCase__				:  Optional[Any]		       =     self.get_value('''zero_optimization.stage'''      ,				-1		)

        # offload
        lowerCAmelCase__				:  Dict		       =     False
        if self.is_zeroa() or self.is_zeroa():
          lowerCAmelCase__				:  Dict		       =     set(['''cpu''', '''nvme''']		)
          lowerCAmelCase__				:  Optional[Any]		       =     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:
            lowerCAmelCase__				:  List[Any]		       =     True

      def 	__magic_name__(   self      ,				__UpperCAmelCase		):
        lowerCAmelCase__				:  int		       =     self.config

        # find the config node of interest if it exists
        lowerCAmelCase__				:  Tuple		       =     ds_key_long.split('''.'''		)
        lowerCAmelCase__				:  int		       =     nodes.pop()
        for node in nodes:
          lowerCAmelCase__				:  int		       =     config.get(__UpperCAmelCase		)
          if config is None:
            return None, ds_key

        return config, ds_key

      def 	__magic_name__(   self      ,				__UpperCAmelCase      ,				__UpperCAmelCase=None		):
        lowerCAmelCase__       ,			lowerCAmelCase__				:  Optional[int]		       =     self.find_config_node(__UpperCAmelCase		)
        if config is None:
          return default
        return config.get(__UpperCAmelCase      ,				__UpperCAmelCase		)

      def 	__magic_name__(   self      ,				__UpperCAmelCase      ,				__UpperCAmelCase=False		):
        lowerCAmelCase__				:  Dict		       =     self.config

        # find the config node of interest if it exists
        lowerCAmelCase__				:  str		       =     ds_key_long.split('''.'''		)
        for node in nodes:
          lowerCAmelCase__				:  Dict		       =     config
          lowerCAmelCase__				:  List[str]		       =     config.get(__UpperCAmelCase		)
          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(__UpperCAmelCase		)

      def 	__magic_name__(   self      ,				__UpperCAmelCase		):
        lowerCAmelCase__				:  Union[str, Any]		       =     self.get_value(__UpperCAmelCase		)
        return False if value is None else bool(__UpperCAmelCase		)

      def 	__magic_name__(   self      ,				__UpperCAmelCase		):
        lowerCAmelCase__				:  Optional[Any]		       =     self.get_value(__UpperCAmelCase		)
        return False if value is None else not bool(__UpperCAmelCase		)

      def 	__magic_name__(   self		):
        return self._stage == 2

      def 	__magic_name__(   self		):
        return self._stage == 3







      def 	__magic_name__(   self		):
        return self._offload






class  _lowerCAmelCase     :

      def __init__(   self      ,				__UpperCAmelCase		):
        lowerCAmelCase__				:  int		       =     engine







      def 	__magic_name__(   self      ,				__UpperCAmelCase      ,				**__UpperCAmelCase		):
        # runs backpropagation and handles mixed precision
        self.engine.backward(__UpperCAmelCase      ,				**__UpperCAmelCase		)

        # 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     (  _lowercase	):

      def __init__(   self      ,				__UpperCAmelCase		):
        super().__init__(__UpperCAmelCase      ,				device_placement=__UpperCAmelCase      ,				scaler=__UpperCAmelCase		)
        lowerCAmelCase__				:  Optional[int]		       =     hasattr(self.optimizer      ,				'''overflow'''		)

      def 	__magic_name__(   self      ,				__UpperCAmelCase=None		):
        pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed

      def 	__magic_name__(   self		):
        pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed







      @property
      def 	__magic_name__(   self		):
        if self.__has_overflow__:
          return self.optimizer.overflow
        return False






class  _lowerCAmelCase     (  _lowercase	):

      def __init__(   self      ,				__UpperCAmelCase      ,				__UpperCAmelCase		):
        super().__init__(__UpperCAmelCase      ,				__UpperCAmelCase		)







      def 	__magic_name__(   self		):
        pass  # `accelerator.backward(loss)` is doing that automatically. Therefore, its implementation is not needed






class  _lowerCAmelCase     :

      def __init__(   self      ,				__UpperCAmelCase      ,				__UpperCAmelCase=0.001      ,				__UpperCAmelCase=0      ,				**__UpperCAmelCase		):
        lowerCAmelCase__				:  Any		       =     params
        lowerCAmelCase__				:  str		       =     lr
        lowerCAmelCase__				:  List[str]		       =     weight_decay
        lowerCAmelCase__				:  Dict		       =     kwargs






class  _lowerCAmelCase     :

      def __init__(   self      ,				__UpperCAmelCase      ,				__UpperCAmelCase=None      ,				__UpperCAmelCase=0      ,				**__UpperCAmelCase		):
        lowerCAmelCase__				:  Union[str, Any]		       =     optimizer
        lowerCAmelCase__				:  Optional[Any]		       =     total_num_steps
        lowerCAmelCase__				:  str		       =     warmup_num_steps
        lowerCAmelCase__				:  Dict		       =     kwargs

