





import argparse
import json
import os
from collections import OrderedDict

import numpy as np
import tensorflow as tf
import torch



def     _lowerCAmelCase		(  _lowerCAmelCase     ):
   '''simple docstring'''


   A_     :				List[str]			      =	os.path.join(args.tf_model_dir  ,"""parameters.json"""     )
   A_     :				Any			      =	json.loads(open(a__     ).read()     )
   if not params:
      raise ValueError(
          f"""It seems that the json file at {parameter_file} is empty. Make sure you have a correct json file."""     )
   if not args.output.endswith(""".pt"""     ):
      A_     :				Tuple			      =	args.output + """.pt"""
   A_     :				Optional[Any]			      =	OrderedDict()
   with tf.device("""/CPU:0"""     ):
      A_     :				Dict			      =	tf.train.load_checkpoint(args.tf_model_dir     )
      A_     :				Any			      =	reader.get_variable_to_shape_map()
      for key_name in shapes.keys():
         A_     :				Union[str, Any]			      =	reader.get_tensor(a__     ).astype(np.floataa     )
         if key_name.endswith("""/adam_m"""     ) or key_name.endswith("""/adam_v"""     ):
            continue
         if key_name.startswith("""pasts/"""     ):
            if key_name.startswith("""pasts/mlp"""     ):
               A_     :				Any			      =	int(key_name[9]     )
            elif key_name.startswith("""pasts/out"""     ):
               A_     :				Union[str, Any]			      =	8
            A_     :				Optional[int]			      =	"""model.sqout.%d.weight""" % (player * 2)  # enter to nn.Sequencial with Tanh, so 2 at a time
            A_     :				List[Any]			      =	vnp.transpose([1, 0]     ).copy()  # Mesh-Tensorflow is a diagonal matrix
            A_     :				Optional[int]			      =	torch.tensor(a__     )
         elif key_name.startswith("""model/moe"""     ):
            A_     :				List[str]			      =	int(key_name[9:].split("""/"""     )[0]     )
            if key_name.endswith("""/switch_gating/kernel"""     ):
               A_     :				Optional[Any]			      =	"""model.blocks.%d.feed_forward.mlp.router.classifier.weight""" % player
               A_     :				int			      =	vnp.transpose([1, 0]     ).copy()  # Mesh-Tensorflow is a diagonal matrix
               A_     :				List[str]			      =	torch.tensor(a__     )
            elif key_name.endswith("""/softmlp/kernel"""     ):
               A_     :				Optional[int]			      =	"""model.blocks.%d.feed_forward.soft_bypass_mlp.weight""" % player
               A_     :				Tuple			      =	vnp.transpose([1, 0]     ).copy()  # Mesh-Tensorflow is a diagonal matrix
               A_     :				Any			      =	torch.tensor(a__     )
            elif key_name.endswith("""/wo/kernel"""     ) or key_name.endswith("""/wi/kernel"""     ):
               A_     :				Optional[Any]			      =	key_name[-9:-7]
               for i in range(1_6     ):
                  A_     :				Optional[int]			      =	"""model.blocks.%d.feed_forward.mlp.experts.expert_%d.%s.weight""" % (player, i, nlayer)
                  A_     :				List[str]			      =	(
                      vnp[i].transpose([1, 0]     ).copy()
                  )  # In Mesh-Tensorflow, it is one array, so it is divided
                  A_     :				Union[str, Any]			      =	torch.tensor(a__     )
         elif key_name.startswith("""model/mlp"""     ):
            A_     :				List[str]			      =	int(key_name[9:].split("""/"""     )[0]     )
            if key_name.endswith("""/p1/kernel"""     ):
               A_     :				Optional[int]			      =	"""model.blocks.%d.feed_forward.mlp.wi.weight""" % player
               A_     :				Dict			      =	vnp.transpose([1, 0]     ).copy()  # Mesh-Tensorflow is a diagonal matrix
               A_     :				List[str]			      =	torch.tensor(a__     )
            elif key_name.endswith("""/p1/bias"""     ):
               A_     :				int			      =	"""model.blocks.%d.feed_forward.mlp.wi.bias""" % player
               A_     :				Union[str, Any]			      =	vnp.copy()  # same because it is one dimensional
               A_     :				List[Any]			      =	torch.tensor(a__     )
            elif key_name.endswith("""/p2/kernel"""     ):
               A_     :				Tuple			      =	"""model.blocks.%d.feed_forward.mlp.wo.weight""" % player
               A_     :				str			      =	vnp.transpose([1, 0]     ).copy()  # Mesh-Tensorflow is a diagonal matrix
               A_     :				List[str]			      =	torch.tensor(a__     )
            elif key_name.endswith("""/p2/bias"""     ):
               A_     :				Tuple			      =	"""model.blocks.%d.feed_forward.mlp.wo.bias""" % player
               A_     :				List[str]			      =	vnp.copy()  # same because it is one dimensional
               A_     :				Optional[int]			      =	torch.tensor(a__     )
         elif key_name.startswith("""model/ln"""     ):
            A_     :				Tuple			      =	int(key_name[8:].split("""/"""     )[0]     )
            if key_name.endswith("""/b"""     ):
               A_     :				List[str]			      =	"""model.blocks.%d.feed_forward.norm.bias""" % player
               A_     :				str			      =	vnp.copy()  # same because it is one dimensional
               A_     :				Union[str, Any]			      =	torch.tensor(a__     )
            elif key_name.endswith("""/g"""     ):
               A_     :				int			      =	"""model.blocks.%d.feed_forward.norm.weight""" % player
               A_     :				Dict			      =	vnp.copy()  # same because it is one dimensional
               A_     :				Tuple			      =	torch.tensor(a__     )
         elif key_name.startswith("""model/att"""     ):
            A_     :				int			      =	int(key_name[9:].split("""/"""     )[0]     )
            if key_name.endswith("""/qkv/kernel"""     ):
               A_     :				int			      =	vnp.copy()  # Compute same dimension as Mesh-tensorflow using einsum
               A_     :				Any			      =	state[:, 0, :, :]
               A_     :				int			      =	state[:, 1, :, :]
               A_     :				Dict			      =	state[:, 2, :, :]
               A_     :				Union[str, Any]			      =	(
                   state_q.reshape([state_q.shape[0], state_q.shape[1] * state_q.shape[2]]     )
                   .transpose([1, 0]     )
                   .copy()
               )  # Mesh-Tensorflow is a diagonal matrix
               A_     :				List[str]			      =	(
                   state_k.reshape([state_k.shape[0], state_k.shape[1] * state_k.shape[2]]     )
                   .transpose([1, 0]     )
                   .copy()
               )  # Mesh-Tensorflow is a diagonal matrix
               A_     :				Any			      =	(
                   state_v.reshape([state_v.shape[0], state_v.shape[1] * state_v.shape[2]]     )
                   .transpose([1, 0]     )
                   .copy()
               )  # Mesh-Tensorflow is a diagonal matrix
               A_     :				Union[str, Any]			      =	"""model.blocks.%d.self_attn.self_attn.q_proj.weight""" % player
               A_     :				List[Any]			      =	torch.tensor(a__     )
               A_     :				Tuple			      =	"""model.blocks.%d.self_attn.self_attn.k_proj.weight""" % player
               A_     :				int			      =	torch.tensor(a__     )
               A_     :				Union[str, Any]			      =	"""model.blocks.%d.self_attn.self_attn.v_proj.weight""" % player
               A_     :				Optional[int]			      =	torch.tensor(a__     )
            elif key_name.endswith("""/o/kernel"""     ):
               A_     :				Dict			      =	"""model.blocks.%d.self_attn.self_attn.out_proj.weight""" % player
               A_     :				int			      =	(
                   vnp.reshape([vnp.shape[0] * vnp.shape[1], vnp.shape[2]]     ).transpose([1, 0]     ).copy()
               )  # Mesh-Tensorflow is a diagonal matrix
               A_     :				Tuple			      =	torch.tensor(a__     )
         elif key_name.startswith("""model/an"""     ):
            A_     :				List[Any]			      =	int(key_name[8:].split("""/"""     )[0]     )
            if key_name.endswith("""/b"""     ):
               A_     :				List[str]			      =	"""model.blocks.%d.self_attn.norm.bias""" % player
               A_     :				Optional[int]			      =	vnp.copy()  # same because it is one dimensional
               A_     :				int			      =	torch.tensor(a__     )
            elif key_name.endswith("""/g"""     ):
               A_     :				Tuple			      =	"""model.blocks.%d.self_attn.norm.weight""" % player
               A_     :				Union[str, Any]			      =	vnp.copy()  # same because it is one dimensional
               A_     :				List[str]			      =	torch.tensor(a__     )
         elif (
             key_name.startswith("""model/wte"""     )
             or key_name.startswith("""model/wpe"""     )
             or key_name.startswith("""model/ete"""     )
         ):
            A_     :				int			      =	{"""wte""": """embed_tokens""", """wpe""": """position_embeddings""", """ete""": """extra_position_embeddings"""}[
                key_name[-3:]
            ]
            A_     :				Tuple			      =	"""model.%s.weight""" % nlayer
            A_     :				Tuple			      =	vnp.copy()  # same in embedded
            A_     :				List[Any]			      =	torch.tensor(a__     )
            if key_name.startswith("""model/wte"""     ):
               A_     :				Optional[Any]			      =	"""lm_head.weight"""
               A_     :				Any			      =	vnp.copy()  # same in embedded
               A_     :				Union[str, Any]			      =	torch.tensor(a__     )
         elif key_name.startswith("""model/wob"""     ):
            A_     :				Dict			      =	"""final_logits_bias"""
            A_     :				Optional[Any]			      =	vnp.copy()  # same in embedded
            A_     :				Dict			      =	state.reshape((1, -1)     )
            A_     :				Optional[Any]			      =	torch.tensor(a__     )
         elif key_name == "model/dense/kernel":
            A_     :				int			      =	"""model.last_project.weight"""
            A_     :				List[Any]			      =	vnp.transpose([1, 0]     ).copy()  # Mesh-Tensorflow is a diagonal matrix
            A_     :				Optional[int]			      =	torch.tensor(a__     )
         elif key_name == "model/dense_1/bias":
            A_     :				Any			      =	"""model.last_project.bias"""
            A_     :				Any			      =	vnp.copy()  # same because it is one dimensional
            A_     :				Tuple			      =	torch.tensor(a__     )
   torch.save(a__  ,args.output     )


if __name__ == "__main__":
      _lowerCAmelCase 				=     argparse.ArgumentParser(
          description="""model converter.""", formatter_class=argparse.ArgumentDefaultsHelpFormatter
      )
      parser.add_argument("""--tf_model_dir""", metavar="""PATH""", type=str, required=True, help="""import model""")
      parser.add_argument("""--output""", metavar="""PATH""", type=str, required=True, help="""output model""")
      _lowerCAmelCase 				=     parser.parse_args()
      convert_tf_gptsan_to_pt(args)













import datasets

from .evaluate import evaluate


_lowerCAmelCase 				=     """\
@inproceedings{Rajpurkar2016SQuAD10,
  title={SQuAD: 100, 000+ Questions for Machine Comprehension of Text},
  author={Pranav Rajpurkar and Jian Zhang and Konstantin Lopyrev and Percy Liang},
  booktitle={EMNLP},
  year={2016}
}
"""

_lowerCAmelCase 				=     """
This metric wrap the official scoring script for version 1 of the Stanford Question Answering Dataset (SQuAD).

Stanford Question Answering Dataset (SQuAD) is a reading comprehension dataset, consisting of questions posed by
crowdworkers on a set of Wikipedia articles, where the answer to every question is a segment of text, or span,
from the corresponding reading passage, or the question might be unanswerable.
"""

_lowerCAmelCase 				=     """
Computes SQuAD scores (F1 and EM).
Args:
    predictions: List of question-answers dictionaries with the following key-values:
        - 'id': id of the question-answer pair as given in the references (see below)
        - 'prediction_text': the text of the answer
    references: List of question-answers dictionaries with the following key-values:
        - 'id': id of the question-answer pair (see above),
        - 'answers': a Dict in the SQuAD dataset format
            {
                'text': list of possible texts for the answer, as a list of strings
                'answer_start': list of start positions for the answer, as a list of ints
            }
            Note that answer_start values are not taken into account to compute the metric.
Returns:
    'exact_match': Exact match (the normalized answer exactly match the gold answer)
    'f1': The F-score of predicted tokens versus the gold answer
Examples:

    >>> predictions = [{'prediction_text': '1976', 'id': '56e10a3be3433e1400422b22'}]
    >>> references = [{'answers': {'answer_start': [97], 'text': ['1976']}, 'id': '56e10a3be3433e1400422b22'}]
    >>> squad_metric = datasets.load_metric(\"squad\")
    >>> results = squad_metric.compute(predictions=predictions, references=references)
    >>> print(results)
    {'exact_match': 100.0, 'f1': 100.0}
"""

@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION			,       _KWARGS_DESCRIPTION     )
class    _UpperCAmelCase							(		datasets.Metric     ):
      def 		_lowerCamelCase      (		self       ):
         return datasets.MetricInfo(
             description=_DESCRIPTION      ,       citation=_CITATION      ,       inputs_description=_KWARGS_DESCRIPTION      ,       features=datasets.Features(
                 {
                     """predictions""": {"""id""": datasets.Value("""string"""       ), """prediction_text""": datasets.Value("""string"""       )},
                     """references""": {
                         """id""": datasets.Value("""string"""       ),
                         """answers""": datasets.features.Sequence(
                             {
                                 """text""": datasets.Value("""string"""       ),
                                 """answer_start""": datasets.Value("""int32"""       ),
                             }       ),
                     },
                 }       )      ,       codebase_urls=["""https://rajpurkar.github.io/SQuAD-explorer/"""]      ,       reference_urls=["""https://rajpurkar.github.io/SQuAD-explorer/"""]      ,       )






      def 		_lowerCamelCase      (		self      ,       a__      ,       a__       ):
         A_     :				Union[str, Any]			      =	{prediction["""id"""]: prediction["""prediction_text"""] for prediction in predictions}
         A_     :				Optional[Any]			      =	[
             {
                 """paragraphs""": [
                     {
                         """qas""": [
                             {
                                 """answers""": [{"""text""": answer_text} for answer_text in ref["""answers"""]["""text"""]],
                                 """id""": ref["""id"""],
                             }
                             for ref in references
                         ]
                     }
                 ]
             }
         ]
         A_     :				Union[str, Any]			      =	evaluate(dataset=a__      ,       predictions=a__       )
         return score






