



"""simple docstring"""




import argparse
import json
import re
import string
import sys
from collections import Counter



def  lowercase    (				SCREAMING_SNAKE_CASE__    :		Tuple			)					->       Dict:

 def remove_articles(SCREAMING_SNAKE_CASE__    :		List[str]			):
  return re.sub(R"""\b(a|an|the)\b"""			,    """ """			,    SCREAMING_SNAKE_CASE__			)

 def white_space_fix(SCREAMING_SNAKE_CASE__    :		Any			):
  return " ".join(text.split()			)

 def remove_punc(SCREAMING_SNAKE_CASE__    :		Any			):
  _snake_case      :					Optional[Any]					=   set(string.punctuation			)
  return "".join(ch for ch in text if ch not in exclude			)

 def lower(SCREAMING_SNAKE_CASE__    :		Tuple			):
  return text.lower()

 return white_space_fix(remove_articles(remove_punc(lower(SCREAMING_SNAKE_CASE__			)			)			)			)



def  lowercase    (				SCREAMING_SNAKE_CASE__    :		Optional[int]			,    SCREAMING_SNAKE_CASE__    :		List[Any]			)					->       List[Any]:
 _snake_case      :					int					=   normalize_answer(SCREAMING_SNAKE_CASE__			).split()
 _snake_case      :					List[str]					=   normalize_answer(SCREAMING_SNAKE_CASE__			).split()
 _snake_case      :					int					=   Counter(SCREAMING_SNAKE_CASE__			) & Counter(SCREAMING_SNAKE_CASE__			)
 _snake_case      :					Tuple					=   sum(common.values()			)
 if num_same == 0:
  return 0
 _snake_case      :					List[str]					=   1.0 * num_same / len(SCREAMING_SNAKE_CASE__			)
 _snake_case      :					Dict					=   1.0 * num_same / len(SCREAMING_SNAKE_CASE__			)
 _snake_case      :					Any					=   (2 * precision * recall) / (precision + recall)
 return fa



def  lowercase    (				SCREAMING_SNAKE_CASE__    :		Optional[Any]			,    SCREAMING_SNAKE_CASE__    :		Dict			)					->       str:
 return normalize_answer(SCREAMING_SNAKE_CASE__			) == normalize_answer(SCREAMING_SNAKE_CASE__			)



def  lowercase    (				SCREAMING_SNAKE_CASE__    :		Optional[int]			,    SCREAMING_SNAKE_CASE__    :		List[str]			,    SCREAMING_SNAKE_CASE__    :		int			)					->       Union[str, Any]:
 _snake_case      :					List[str]					=   []
 for ground_truth in ground_truths:
  _snake_case      :					Dict					=   metric_fn(SCREAMING_SNAKE_CASE__			,    SCREAMING_SNAKE_CASE__			)
  scores_for_ground_truths.append(SCREAMING_SNAKE_CASE__			)
 return max(SCREAMING_SNAKE_CASE__			)



def  lowercase    (				SCREAMING_SNAKE_CASE__    :		List[str]			,    SCREAMING_SNAKE_CASE__    :		Tuple			)					->       Any:
 _snake_case      :					Dict					=   0
 _snake_case      :					List[Any]					=   []
 for passage in dataset:
  for qa in passage["qas"]:
   total += 1
   if qa["id"] not in predictions:
    _snake_case      :					Dict					=   F'''Unanswered question {qa['id']} will receive score 0.'''
    print(SCREAMING_SNAKE_CASE__			,    file=sys.stderr			)
    continue

   _snake_case      :					Tuple					=   [x["""text"""] for x in qa["""answers"""]]
   _snake_case      :					Any					=   predictions[qa["""id"""]]

   _snake_case      :					str					=   metric_max_over_ground_truths(SCREAMING_SNAKE_CASE__			,    SCREAMING_SNAKE_CASE__			,    SCREAMING_SNAKE_CASE__			)
   if int(_exact_match			) == 1:
    correct_ids.append(qa["""id"""]			)
   exact_match += _exact_match

   fa += metric_max_over_ground_truths(SCREAMING_SNAKE_CASE__			,    SCREAMING_SNAKE_CASE__			,    SCREAMING_SNAKE_CASE__			)

 _snake_case      :					Dict					=   exact_match / total
 _snake_case      :					str					=   fa / total

 return {"exact_match": exact_match, "f1": fa}, correct_ids


if __name__ == "__main__":
  a__      =		"""1.0"""
  a__      =		argparse.ArgumentParser("""Official evaluation script for ReCoRD v1.0.""")
  parser.add_argument("""data_file""", help="""The dataset file in JSON format.""")
  parser.add_argument("""pred_file""", help="""The model prediction file in JSON format.""")
  parser.add_argument("""--output_correct_ids""", action="""store_true""", help="""Output the correctly answered query IDs.""")
  a__      =		parser.parse_args()

  with open(args.data_file) as data_file:
    a__      =		json.load(data_file)
    if dataset_json["version"] != expected_version:
      print(
          F'''Evaluation expects v-{expected_version}, but got dataset with v-{dataset_json['version']}''',
          file=sys.stderr,
      )
    a__      =		dataset_json["""data"""]

  with open(args.pred_file) as pred_file:
    a__      =		json.load(pred_file)

  a__,  a__      =		evaluate(dataset, predictions)

  if args.output_correct_ids:
    print(F'''Output {len(correct_ids)} correctly answered question IDs.''')
    with open("""correct_ids.json""", """w""") as f:
      json.dump(correct_ids, f)





import math
from collections import OrderedDict

import torch
from packaging import version
from torch import Tensor, nn

from .utils import logging


a__      =		logging.get_logger(__name__)







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def __init__(   self							:     Tuple)			->			Optional[int]:

    """simple docstring"""







    super().__init__()
    if version.parse(torch.__version__) < version.parse("""1.12.0"""):
     raise ImportError(
         F'''You are using torch=={torch.__version__}, but torch>=1.12.0 is required to use '''
         """PytorchGELUTanh. Please upgrade torch.""")


   def        UpperCamelCase_					(   self							:     Tuple			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return nn.functional.gelu(lowerCAmelCase			,						approximate="""tanh""")







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def        UpperCamelCase_					(   self							:     Optional[int]			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.044_715 * torch.pow(lowerCAmelCase			,						3.0))))







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def __init__(   self							:     str			,						lowerCAmelCase							:     bool = False)			->			Optional[Any]:

    """simple docstring"""







    super().__init__()
    if use_gelu_python:
     _snake_case      :					Optional[int]					=   self._gelu_python
    else:
     _snake_case      :					Any					=   nn.functional.gelu

   def        UpperCamelCase_					(   self							:     Union[str, Any]			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return input * 0.5 * (1.0 + torch.erf(input / math.sqrt(2.0)))


   def        UpperCamelCase_					(   self							:     str			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return self.act(lowerCAmelCase)







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def        UpperCamelCase_					(   self							:     int			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return 0.5 * input * (1.0 + torch.tanh(input * 0.7_978_845_608 * (1.0 + 0.044_715 * input * input)))







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def        UpperCamelCase_					(   self							:     int			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return input * torch.sigmoid(1.702 * input)







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def __init__(   self							:     int			,						lowerCAmelCase							:     float			,						lowerCAmelCase							:     float)			->			Optional[int]:

    """simple docstring"""







    if min > max:
     raise ValueError(F'''min should be < max (got min: {min}, max: {max})''')

    super().__init__()
    _snake_case      :					Dict					=   min
    _snake_case      :					Optional[int]					=   max


   def        UpperCamelCase_					(   self							:     Union[str, Any]			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return torch.clip(gelu(lowerCAmelCase)			,						self.min			,						self.max)







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def __init__(   self							:     Tuple)			->			List[str]:

    """simple docstring"""







    super().__init__()
    _snake_case      :					Union[str, Any]					=   math.sqrt(2 / math.pi)


   def        UpperCamelCase_					(   self							:     Dict			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return 0.5 * input * (1 + torch.tanh(self.precomputed_constant * (input + 0.044_715 * torch.pow(lowerCAmelCase			,						3))))







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def        UpperCamelCase_					(   self							:     Dict			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return nn.functional.silu(lowerCAmelCase)







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def __init__(   self							:     List[Any])			->			str:

    """simple docstring"""







    super().__init__()
    if version.parse(torch.__version__) < version.parse("""1.9.0"""):
     _snake_case      :					Optional[int]					=   self._mish_python
    else:
     _snake_case      :					List[str]					=   nn.functional.mish

   def        UpperCamelCase_					(   self							:     str			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return input * torch.tanh(nn.functional.softplus(lowerCAmelCase))


   def        UpperCamelCase_					(   self							:     str			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return self.act(lowerCAmelCase)







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def        UpperCamelCase_					(   self							:     Optional[Any]			,						lowerCAmelCase							:     Tensor)			->			Tensor:

    """simple docstring"""







    return input







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def        UpperCamelCase_					(   self							:     List[Any]			,						lowerCAmelCase							:     int			,						lowerCAmelCase							:     List[Any]=0.707_107			,						lowerCAmelCase							:     Optional[Any]=0.282_095)			->			List[Any]:

    """simple docstring"""







    _snake_case      :					List[str]					=   (input - mu).div(sigma * math.sqrt(2.0))
    return 0.5 * (1.0 + torch.erf(lowerCAmelCase))







class 						snake_case  (		nn.Module					):



   '''simple docstring'''






   def        UpperCamelCase_					(   self							:     Any			,						lowerCAmelCase							:     Dict)			->			Union[str, Any]:

    """simple docstring"""







    _snake_case      :					Dict					=   nn.functional.relu(lowerCAmelCase)
    _snake_case      :					Tuple					=   torch.square(lowerCAmelCase)
    return squared







class 						snake_case  (		SCREAMING_SNAKE_CASE_					):



   '''simple docstring'''






   def __getitem__(   self							:     Dict			,						lowerCAmelCase							:     Tuple)			->			str:

    """simple docstring"""







    _snake_case      :					Optional[Any]					=   super().__getitem__(lowerCAmelCase)
    _snake_case		,      _snake_case      :					List[str]					=   content if isinstance(lowerCAmelCase			,						lowerCAmelCase) else (content, {})
    return cls(**lowerCAmelCase)
a__      =		{
    """gelu""": GELUActivation,
    """gelu_10""": (ClippedGELUActivation, {"""min""": -10, """max""": 10}),
    """gelu_fast""": FastGELUActivation,
    """gelu_new""": NewGELUActivation,
    """gelu_python""": (GELUActivation, {"""use_gelu_python""": True}),
    """gelu_pytorch_tanh""": PytorchGELUTanh,
    """gelu_accurate""": AccurateGELUActivation,
    """laplace""": LaplaceActivation,
    """linear""": LinearActivation,
    """mish""": MishActivation,
    """quick_gelu""": QuickGELUActivation,
    """relu""": nn.ReLU,
    """relu2""": ReLUSquaredActivation,
    """relu6""": nn.ReLUa,
    """sigmoid""": nn.Sigmoid,
    """silu""": SiLUActivation,
    """swish""": SiLUActivation,
    """tanh""": nn.Tanh,
}
a__      =		ClassInstantier(ACTaCLS)



def  lowercase    (				SCREAMING_SNAKE_CASE__    :		Any			)					->       int:
 if activation_string in ACTaFN:
  return ACTaFN[activation_string]
 else:
  raise KeyError(F'''function {activation_string} not found in ACT2FN mapping {list(ACTaFN.keys()			)}'''			)


# For backwards compatibility with: from activations import gelu_python
a__      =		get_activation("""gelu_python""")
a__      =		get_activation("""gelu_new""")
a__      =		get_activation("""gelu""")
a__      =		get_activation("""gelu_fast""")
a__      =		get_activation("""quick_gelu""")
a__      =		get_activation("""silu""")
a__      =		get_activation("""mish""")

a__      =		get_activation("""linear""")
