





import math
from enum import Enum
from typing import Optional, Union

from torch.optim import Optimizer
from torch.optim.lr_scheduler import LambdaLR

from .utils import logging


snake_case_           =      logging.get_logger(__name__)

class 		SCREAMING_SNAKE_CASE__    (	_UpperCAmelCase  ):
      A_						:    Any							=   'linear'
      A_						:    str							=   'cosine'
      A_						:    Tuple							=   'cosine_with_restarts'
      A_						:    Optional[int]							=   'polynomial'
      A_						:    Union[str, Any]							=   'constant'
      A_						:    Dict							=   'constant_with_warmup'
      A_						:    Optional[int]							=   'piecewise_constant'






def lowerCamelCase__   (							snake_case_     :  Optimizer	,				snake_case_     :  int = -1	)				->    Optional[int]:
   return LambdaLR(snake_case_	,				lambda snake_case_	: 1	,				last_epoch=snake_case_	)






def lowerCamelCase__   (							snake_case_     :  Optimizer	,				snake_case_     :  int	,				snake_case_     :  int = -1	)				->    Optional[Any]:

   def lr_lambda(snake_case_     :  int	):
      if current_step < num_warmup_steps:
         return float(snake_case_	) / float(max(1.0	,				snake_case_	)	)
      return 1.0

   return LambdaLR(snake_case_	,				snake_case_	,				last_epoch=snake_case_	)






def lowerCamelCase__   (							snake_case_     :  Optimizer	,				snake_case_     :  str	,				snake_case_     :  int = -1	)				->    Any:
   __snake_case								=       {}
   __snake_case								=       step_rules.split(''','''	)
   for rule_str in rule_list[:-1]:
      __snake_case	,     __snake_case								=       rule_str.split(''':'''	)
      __snake_case								=       int(snake_case_	)
      __snake_case								=       float(snake_case_	)
      __snake_case								=       value
   __snake_case								=       float(rule_list[-1]	)

   def create_rules_function(snake_case_     :  Optional[Any]	,				snake_case_     :  str	):
      def rule_func(snake_case_     :  int	) -> float:
         __snake_case								=       sorted(rules_dict.keys()	)
         for i, sorted_step in enumerate(snake_case_	):
            if steps < sorted_step:
               return rules_dict[sorted_steps[i]]
         return last_lr_multiple

      return rule_func

   __snake_case								=       create_rules_function(snake_case_	,				snake_case_	)

   return LambdaLR(snake_case_	,				snake_case_	,				last_epoch=snake_case_	)






def lowerCamelCase__   (							snake_case_     :  Optional[int]	,				snake_case_     :  str	,				snake_case_     :  Optional[Any]	,				snake_case_     :  Dict=-1	)				->    Dict:

   def lr_lambda(snake_case_     :  int	):
      if current_step < num_warmup_steps:
         return float(snake_case_	) / float(max(1	,				snake_case_	)	)
      return max(
          0.0	,				float(num_training_steps - current_step	) / float(max(1	,				num_training_steps - num_warmup_steps	)	)	)

   return LambdaLR(snake_case_	,				snake_case_	,				snake_case_	)






def lowerCamelCase__   (							snake_case_     :  Optimizer	,				snake_case_     :  int	,				snake_case_     :  int	,				snake_case_     :  float = 0.5	,				snake_case_     :  int = -1	)				->    Union[str, Any]:

   def lr_lambda(snake_case_     :  Dict	):
      if current_step < num_warmup_steps:
         return float(snake_case_	) / float(max(1	,				snake_case_	)	)
      __snake_case								=       float(current_step - num_warmup_steps	) / float(max(1	,				num_training_steps - num_warmup_steps	)	)
      return max(0.0	,				0.5 * (1.0 + math.cos(math.pi * float(snake_case_	) * 2.0 * progress	))	)

   return LambdaLR(snake_case_	,				snake_case_	,				snake_case_	)






def lowerCamelCase__   (							snake_case_     :  Optimizer	,				snake_case_     :  int	,				snake_case_     :  int	,				snake_case_     :  int = 1	,				snake_case_     :  int = -1	)				->    Any:

   def lr_lambda(snake_case_     :  int	):
      if current_step < num_warmup_steps:
         return float(snake_case_	) / float(max(1	,				snake_case_	)	)
      __snake_case								=       float(current_step - num_warmup_steps	) / float(max(1	,				num_training_steps - num_warmup_steps	)	)
      if progress >= 1.0:
         return 0.0
      return max(0.0	,				0.5 * (1.0 + math.cos(math.pi * ((float(snake_case_	) * progress) % 1.0)	))	)

   return LambdaLR(snake_case_	,				snake_case_	,				snake_case_	)






def lowerCamelCase__   (							snake_case_     :  List[str]	,				snake_case_     :  Optional[Any]	,				snake_case_     :  Optional[Any]	,				snake_case_     :  int=1e-7	,				snake_case_     :  Any=1.0	,				snake_case_     :  Optional[Any]=-1	)				->    List[Any]:
   __snake_case								=       optimizer.defaults['''lr''']
   if not (lr_init > lr_end):
      raise ValueError(f"""lr_end ({lr_end}) must be be smaller than initial lr ({lr_init})"""	)

   def lr_lambda(snake_case_     :  int	):
      if current_step < num_warmup_steps:
         return float(snake_case_	) / float(max(1	,				snake_case_	)	)
      elif current_step > num_training_steps:
         return lr_end / lr_init  # as LambdaLR multiplies by lr_init
      else:
         __snake_case								=       lr_init - lr_end
         __snake_case								=       num_training_steps - num_warmup_steps
         __snake_case								=       1 - (current_step - num_warmup_steps) / decay_steps
         __snake_case								=       lr_range * pct_remaining**power + lr_end
         return decay / lr_init  # as LambdaLR multiplies by lr_init

   return LambdaLR(snake_case_	,				snake_case_	,				snake_case_	)


snake_case_           =      {
    SchedulerType.LINEAR: get_linear_schedule_with_warmup,
    SchedulerType.COSINE: get_cosine_schedule_with_warmup,
    SchedulerType.COSINE_WITH_RESTARTS: get_cosine_with_hard_restarts_schedule_with_warmup,
    SchedulerType.POLYNOMIAL: get_polynomial_decay_schedule_with_warmup,
    SchedulerType.CONSTANT: get_constant_schedule,
    SchedulerType.CONSTANT_WITH_WARMUP: get_constant_schedule_with_warmup,
    SchedulerType.PIECEWISE_CONSTANT: get_piecewise_constant_schedule,
}







def lowerCamelCase__   (							snake_case_     :  Union[str, SchedulerType]	,				snake_case_     :  Optimizer	,				snake_case_     :  Optional[str] = None	,				snake_case_     :  Optional[int] = None	,				snake_case_     :  Optional[int] = None	,				snake_case_     :  int = 1	,				snake_case_     :  float = 1.0	,				snake_case_     :  int = -1	,				)				->    int:
   __snake_case								=       SchedulerType(snake_case_	)
   __snake_case								=       TYPE_TO_SCHEDULER_FUNCTION[name]
   if name == SchedulerType.CONSTANT:
      return schedule_func(snake_case_	,				last_epoch=snake_case_	)

   if name == SchedulerType.PIECEWISE_CONSTANT:
      return schedule_func(snake_case_	,				step_rules=snake_case_	,				last_epoch=snake_case_	)

   # All other schedulers require `num_warmup_steps`
   if num_warmup_steps is None:
      raise ValueError(f"""{name} requires `num_warmup_steps`, please provide that argument."""	)

   if name == SchedulerType.CONSTANT_WITH_WARMUP:
      return schedule_func(snake_case_	,				num_warmup_steps=snake_case_	,				last_epoch=snake_case_	)

   # All other schedulers require `num_training_steps`
   if num_training_steps is None:
      raise ValueError(f"""{name} requires `num_training_steps`, please provide that argument."""	)

   if name == SchedulerType.COSINE_WITH_RESTARTS:
      return schedule_func(
          snake_case_	,				num_warmup_steps=snake_case_	,				num_training_steps=snake_case_	,				num_cycles=snake_case_	,				last_epoch=snake_case_	,				)

   if name == SchedulerType.POLYNOMIAL:
      return schedule_func(
          snake_case_	,				num_warmup_steps=snake_case_	,				num_training_steps=snake_case_	,				power=snake_case_	,				last_epoch=snake_case_	,				)

   return schedule_func(
       snake_case_	,				num_warmup_steps=snake_case_	,				num_training_steps=snake_case_	,				last_epoch=snake_case_	)








import re
import string

import numpy as np

import datasets


snake_case_           =      '\nReturns the rate at which the input predicted strings exactly match their references, ignoring any strings input as part of the regexes_to_ignore list.\n'

snake_case_           =      '\nArgs:\n    predictions: List of predicted texts.\n    references: List of reference texts.\n    regexes_to_ignore: List, defaults to None. Regex expressions of characters to\n        ignore when calculating the exact matches. Note: these regexes are removed\n        from the input data before the changes based on the options below (e.g. ignore_case,\n        ignore_punctuation, ignore_numbers) are applied.\n    ignore_case: Boolean, defaults to False. If true, turns everything\n        to lowercase so that capitalization differences are ignored.\n    ignore_punctuation: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\n    ignore_numbers: Boolean, defaults to False. If true, removes all punctuation before\n        comparing predictions and references.\nReturns:\n    exact_match: Dictionary containing exact_match rate. Possible values are between 0.0 and 100.0, inclusive.\nExamples:\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    25.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    50.0\n\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True)\n    >>> print(round(results["exact_match"], 1))\n    75.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["the cat", "theater", "YELLING", "agent007"]\n    >>> preds = ["cat?", "theater", "yelling", "agent"]\n    >>> results = exact_match.compute(references=refs, predictions=preds, regexes_to_ignore=["the ", "yell", "YELL"], ignore_case=True, ignore_punctuation=True, ignore_numbers=True)\n    >>> print(round(results["exact_match"], 1))\n    100.0\n\n    >>> exact_match = datasets.load_metric("exact_match")\n    >>> refs = ["The cat sat on the mat.", "Theaters are great.", "It\'s like comparing oranges and apples."]\n    >>> preds = ["The cat sat on the mat?", "Theaters are great.", "It\'s like comparing apples and oranges."]\n    >>> results = exact_match.compute(references=refs, predictions=preds)\n    >>> print(round(results["exact_match"], 1))\n    33.3\n\n'

snake_case_           =      '\n'

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


      def        a			(self	:				Optional[Any]				):





         """simple docstring"""



         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'''				),
                 }				)    ,      reference_urls=[]    ,      )


      def        a			(self	:				List[Any]    ,      a__	:				int    ,      a__	:				Optional[int]    ,      a__	:				Optional[Any]=None    ,      a__	:				Any=False    ,      a__	:				Dict=False    ,      a__	:				Tuple=False    ,      ):





         """simple docstring"""



         if regexes_to_ignore is not None:
            for s in regexes_to_ignore:
               __snake_case								=       np.array([re.sub(a__    ,      ''''''    ,      a__				) for x in predictions]				)
               __snake_case								=       np.array([re.sub(a__    ,      ''''''    ,      a__				) for x in references]				)
         else:
            __snake_case								=       np.asarray(a__				)
            __snake_case								=       np.asarray(a__				)

         if ignore_case:
            __snake_case								=       np.char.lower(a__				)
            __snake_case								=       np.char.lower(a__				)

         if ignore_punctuation:
            __snake_case								=       string.punctuation.maketrans(''''''    ,      ''''''    ,      string.punctuation				)
            __snake_case								=       np.char.translate(a__    ,      table=a__				)
            __snake_case								=       np.char.translate(a__    ,      table=a__				)

         if ignore_numbers:
            __snake_case								=       string.digits.maketrans(''''''    ,      ''''''    ,      string.digits				)
            __snake_case								=       np.char.translate(a__    ,      table=a__				)
            __snake_case								=       np.char.translate(a__    ,      table=a__				)

         __snake_case								=       predictions == references

         return {"exact_match": np.mean(a__				) * 100}

