






'''simple docstring'''




import argparse
import json
import os
import re

import torch

from transformers import BloomConfig, BloomModel
from transformers.file_utils import CONFIG_NAME, WEIGHTS_NAME
from transformers.utils import logging


logging.set_verbosity_info()

__lowerCamelCase   :					Optional[int]   							=					[
    '''word_embeddings_layernorm.weight''',
    '''word_embeddings_layernorm.bias''',
    '''input_layernorm.weight''',
    '''input_layernorm.bias''',
    '''post_attention_layernorm.weight''',
    '''post_attention_layernorm.bias''',
    '''self_attention.dense.bias''',
    '''mlp.dense_4h_to_h.bias''',
    '''ln_f.weight''',
    '''ln_f.bias''',
]

__lowerCamelCase   :					Dict   							=					[
    '''mlp.dense_4h_to_h.weight''',
    '''self_attention.dense.weight''',
]

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__						)->    Optional[int]:



   """simple docstring"""



   snake_case_				:					Optional[int]   =       {
       "word_embeddings.weight": "word_embeddings.weight",
       "word_embeddings.norm.weight": "word_embeddings_layernorm.weight",
       "word_embeddings.norm.bias": "word_embeddings_layernorm.bias",
       "weight": "ln_f.weight",
       "bias": "ln_f.bias",
   }

   if key in layer_rename_map:
      return layer_rename_map[key]

   # Handle transformer blocks
   snake_case_				:					str   =       int(re.match(r".*layer_(\d*).*"     ,__magic_name__						)[1]						)
   layer_number -= 3
   return F'''h.{layer_number}.''' + key

def 	__UpperCAmelCase       ( __magic_name__						)->    Dict:



   """simple docstring"""



   if dtype == torch.bool:
      return 1 / 8
   snake_case_				:					str   =       re.search(r"[^\d](\d+)$"     ,str(__magic_name__						)						)
   if bit_search is None:
      raise ValueError(F'''`dtype` is not a valid dtype: {dtype}.'''						)
   snake_case_				:					Tuple   =       int(bit_search.groups()[0]						)
   return bit_size // 8

def 	__UpperCAmelCase       ( __magic_name__     ,__magic_name__     ,__magic_name__     ,__magic_name__     ,__magic_name__						)->    Tuple:



   """simple docstring"""



   if bloom_config_file == "":
      snake_case_				:					str   =       BloomConfig()
   else:
      snake_case_				:					Tuple   =       BloomConfig.from_json_file(__magic_name__						)

   if shard_model:
      snake_case_				:					str   =       os.listdir(__magic_name__						)
      snake_case_				:					List[str]   =       sorted(filter(lambda __magic_name__						: s.startswith("layer"						) and "model_00" in s     ,__magic_name__						)						)

      snake_case_				:					List[Any]   =       {"weight_map": {}, "metadata": {}}
      snake_case_				:					Union[str, Any]   =       0

      snake_case_				:					Tuple   =       None

      snake_case_				:					Optional[Any]   =       BloomConfig()

      for j, file in enumerate(__magic_name__						):
         print("Processing file: {}".format(__magic_name__						)						)
         snake_case_				:					List[Any]   =       None

         for i in range(__magic_name__						):
            # load all TP files
            snake_case_				:					List[Any]   =       file.replace("model_00"     ,F'''model_0{i}'''						)
            snake_case_				:					Optional[Any]   =       torch.load(os.path.join(__magic_name__     ,__magic_name__						)     ,map_location="cpu"						)

            # Rename keys in the transformers names
            snake_case_				:					Union[str, Any]   =       list(temp.keys()						)
            for key in keys:
               snake_case_				:					List[str]   =       temp.pop(__magic_name__						)

            if tensors is None:
               snake_case_				:					Union[str, Any]   =       temp
            else:
               for key in tensors.keys():
                  if any(key.endswith(__magic_name__						) for end in WEIGHTS_TO_AVERAGE_ENDSWITH						):
                     # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425)
                     tensors[key] += temp[key]
                  else:
                     # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel
                     snake_case_				:					Optional[Any]   =       1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN						) else 0
                     # We concatenate these weights accross TP ranks
                     snake_case_				:					List[Any]   =       torch.cat([tensors[key], temp[key]]     ,dim=__magic_name__						)

            # Divide by the number of TP the weights we want to average
         for key in tensors.keys():
            if any(key.endswith(__magic_name__						) for end in WEIGHTS_TO_AVERAGE_ENDSWITH						):
               snake_case_				:					int   =       tensors[key] / pretraining_tp
         torch.save(
             __magic_name__     ,os.path.join(
                 __magic_name__     ,"pytorch_model_{}-of-{}.bin".format(str(j + 1						).zfill(5						)     ,str(len(__magic_name__						)						).zfill(5						)						)     ,)     ,)

         for key in tensors.keys():
            snake_case_				:					Any   =       tensors[key]
            total_size += value.numel() * get_dtype_size(value.dtype						)
            if key not in index_dict["weight_map"]:
               snake_case_				:					int   =       "pytorch_model_{}-of-{}.bin".format(
                   str(j + 1						).zfill(5						)     ,str(len(__magic_name__						)						).zfill(5						)						)

      snake_case_				:					int   =       BloomConfig()
      snake_case_				:					Dict   =       pytorch_dump_folder_path + "/" + CONFIG_NAME
      snake_case_				:					Optional[Any]   =       total_size
      with open(__magic_name__     ,"w"     ,encoding="utf-8"						) as f:
         f.write(config.to_json_string()						)
      with open(os.path.join(__magic_name__     ,WEIGHTS_NAME + ".index.json"						)     ,"w"     ,encoding="utf-8"						) as f:
         snake_case_				:					Any   =       json.dumps(__magic_name__     ,indent=2     ,sort_keys=__magic_name__						) + "\n"
         f.write(__magic_name__						)
   else:
      snake_case_				:					Optional[Any]   =       BloomModel(__magic_name__						)

      snake_case_				:					str   =       os.listdir(__magic_name__						)
      snake_case_				:					Optional[int]   =       sorted(filter(lambda __magic_name__						: s.startswith("layer"						) and "model_00" in s     ,__magic_name__						)						)

      snake_case_				:					List[Any]   =       None
      for i, file in enumerate(__magic_name__						):
         snake_case_				:					Tuple   =       None
         for i in range(__magic_name__						):
            # load all TP files
            snake_case_				:					Tuple   =       file.replace("model_00"     ,F'''model_0{i}'''						)
            snake_case_				:					Dict   =       torch.load(os.path.join(__magic_name__     ,__magic_name__						)     ,map_location="cpu"						)

            # Rename keys in the transformers names
            snake_case_				:					Tuple   =       list(temp.keys()						)
            for key in keys:
               snake_case_				:					Tuple   =       temp.pop(__magic_name__						)

            if tensors is None:
               snake_case_				:					str   =       temp
            else:
               for key in tensors.keys():
                  # We average (sum and then divide) some weights accross TP ranks (see https://github.com/bigscience-workshop/Megatron-DeepSpeed/blob/olruwase/sync_layer_norms/megatron/training.py#L425)
                  if any(key.endswith(__magic_name__						) for end in WEIGHTS_TO_AVERAGE_ENDSWITH						):
                     tensors[key] += temp[key]
                  else:
                     # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel
                     snake_case_				:					Tuple   =       1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN						) else 0
                     # We concatenate these weights accross TP ranks
                     snake_case_				:					Union[str, Any]   =       torch.cat([tensors[key], temp[key]]     ,dim=__magic_name__						)

            # Divide by the number of TP the weights we want to average
         for key in tensors.keys():
            if any(key.endswith(__magic_name__						) for end in WEIGHTS_TO_AVERAGE_ENDSWITH						):
               snake_case_				:					List[str]   =       tensors[key] / pretraining_tp

         snake_case_				:					Optional[Any]   =       model.load_state_dict(__magic_name__     ,strict=__magic_name__						)
         assert not other_keys.unexpected_keys, F'''The keys {other_keys.unexpected_keys} are unexpected'''
         if missing_keys is None:
            snake_case_				:					Dict   =       set(other_keys.missing_keys						)
         else:
            snake_case_				:					Optional[int]   =       missing_keys.intersection(set(other_keys.missing_keys						)						)

      assert not missing_keys, F'''The keys {missing_keys} are missing'''

      # Save pytorch-model
      os.makedirs(__magic_name__     ,exist_ok=__magic_name__						)
      snake_case_				:					Dict   =       pytorch_dump_folder_path + "/" + WEIGHTS_NAME
      snake_case_				:					Optional[Any]   =       pytorch_dump_folder_path + "/" + CONFIG_NAME
      print(F'''Save PyTorch model to {pytorch_weights_dump_path} with dtype {config.torch_dtype}'''						)
      if config.torch_dtype is not None:
         snake_case_				:					int   =       model.to(config.torch_dtype						)
      torch.save(model.state_dict()     ,__magic_name__						)
      print(F'''Save configuration file to {pytorch_config_dump_path}'''						)
      with open(__magic_name__     ,"w"     ,encoding="utf-8"						) as f:
         f.write(config.to_json_string()						)


if __name__ == "__main__":
  __lowerCamelCase   :					Any   							=					argparse.ArgumentParser()
  # Required parameters
  parser.add_argument(
      '''--bloom_checkpoint_path''',
      default=None,
      type=str,
      required=True,
      help='''Path to the Megatron-LM checkpoint path.''',
  )
  parser.add_argument(
      '''--pytorch_dump_folder_path''', default=None, type=str, required=True, help='''Path to the output PyTorch model.'''
  )
  parser.add_argument(
      '''--bloom_config_file''',
      default='''''',
      type=str,
      help=(
          '''An optional config json file corresponding to the pre-trained model. \n'''
          '''This specifies the model architecture.'''
      ),
  )
  parser.add_argument(
      '''--shard_model''',
      action='''store_true''',
      help='''An optional setting to shard the output model \nThis enables sharding the converted checkpoint''',
  )
  parser.add_argument(
      '''--pretraining_tp''',
      default=4,
      type=int,
      help='''Pretraining TP rank that has been used when training the model in Megatron-LM \n''',
  )
  __lowerCamelCase   :					Union[str, Any]   							=					parser.parse_args()
  convert_bloom_checkpoint_to_pytorch(
      args.bloom_checkpoint_path,
      args.bloom_config_file,
      args.pytorch_dump_folder_path,
      args.shard_model,
      args.pretraining_tp,
  )












'''simple docstring'''




import sacrebleu as scb
from packaging import version
from sacrebleu import TER

import datasets


__lowerCamelCase   :					str   							=					'''\
@inproceedings{snover-etal-2006-study,
    title = "A Study of Translation Edit Rate with Targeted Human Annotation",
    author = "Snover, Matthew  and
      Dorr, Bonnie  and
      Schwartz, Rich  and
      Micciulla, Linnea  and
      Makhoul, John",
    booktitle = "Proceedings of the 7th Conference of the Association for Machine Translation in the Americas: Technical Papers",
    month = aug # " 8-12",
    year = "2006",
    address = "Cambridge, Massachusetts, USA",
    publisher = "Association for Machine Translation in the Americas",
    url = "https://aclanthology.org/2006.amta-papers.25",
    pages = "223--231",
}
@inproceedings{post-2018-call,
    title = "A Call for Clarity in Reporting {BLEU} Scores",
    author = "Post, Matt",
    booktitle = "Proceedings of the Third Conference on Machine Translation: Research Papers",
    month = oct,
    year = "2018",
    address = "Belgium, Brussels",
    publisher = "Association for Computational Linguistics",
    url = "https://www.aclweb.org/anthology/W18-6319",
    pages = "186--191",
}
'''

__lowerCamelCase   :					Dict   							=					'''\
TER (Translation Edit Rate, also called Translation Error Rate) is a metric to quantify the edit operations that a
hypothesis requires to match a reference translation. We use the implementation that is already present in sacrebleu
(https://github.com/mjpost/sacreBLEU#ter), which in turn is inspired by the TERCOM implementation, which can be found
here: https://github.com/jhclark/tercom.

The implementation here is slightly different from sacrebleu in terms of the required input format. The length of
the references and hypotheses lists need to be the same, so you may need to transpose your references compared to
sacrebleu\'s required input format. See https://github.com/huggingface/datasets/issues/3154#issuecomment-950746534

See the README.md file at https://github.com/mjpost/sacreBLEU#ter for more information.
'''

__lowerCamelCase   :					int   							=					'''
Produces TER scores alongside the number of edits and reference length.

Args:
    predictions (list of str): The system stream (a sequence of segments).
    references (list of list of str): A list of one or more reference streams (each a sequence of segments).
    normalized (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    ignore_punct (boolean): If `True`, applies basic tokenization and normalization to sentences. Defaults to `False`.
    support_zh_ja_chars (boolean): If `True`, tokenization/normalization supports processing of Chinese characters,
                                    as well as Japanese Kanji, Hiragana, Katakana, and Phonetic Extensions of Katakana.
                                    Only applies if `normalized = True`. Defaults to `False`.
    case_sensitive (boolean): If `False`, makes all predictions and references lowercase to ignore differences in case. Defaults to `False`.

Returns:
    \'score\' (float): TER score (num_edits / sum_ref_lengths * 100)
    \'num_edits\' (int): The cumulative number of edits
    \'ref_length\' (float): The cumulative average reference length

Examples:
    Example 1:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?",
        ...                     "What did the TER metric user say to the developer?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],
        ...             ["Your jokes are...", "...TERrible"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {\'score\': 150.0, \'num_edits\': 15, \'ref_length\': 10.0}

    Example 2:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         case_sensitive=True)
        >>> print(results)
        {\'score\': 62.5, \'num_edits\': 5, \'ref_length\': 8.0}

    Example 3:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         normalized=True,
        ...                         case_sensitive=True)
        >>> print(results)
        {\'score\': 57.14285714285714, \'num_edits\': 6, \'ref_length\': 10.5}

    Example 4:
        >>> predictions = ["does this sentence match??",
        ...                     "what about this sentence?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {\'score\': 0.0, \'num_edits\': 0, \'ref_length\': 8.0}

    Example 5:
        >>> predictions = ["does this sentence match??",
        ...                    "what about this sentence?",
        ...                    "What did the TER metric user say to the developer?"]
        >>> references = [["does this sentence match", "does this sentence match!?!"],
        ...             ["wHaT aBoUt ThIs SeNtEnCe?", "wHaT aBoUt ThIs SeNtEnCe?"],
        ...             ["Your jokes are...", "...TERrible"]]
        >>> ter = datasets.load_metric("ter")
        >>> results = ter.compute(predictions=predictions,
        ...                         references=references,
        ...                         ignore_punct=True,
        ...                         case_sensitive=False)
        >>> print(results)
        {\'score\': 100.0, \'num_edits\': 10, \'ref_length\': 10.0}
'''







@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,					_KWARGS_DESCRIPTION							)
class    A_	(datasets.Metric							):
							"""simple docstring"""




							def 							_A	(		self			:Optional[Any]				)				->  Optional[int]:


										'''simple docstring'''




										if version.parse(scb.__version__				) < version.parse("1.4.12"				):
													raise ImportWarning(
													    "To use `sacrebleu`, the module `sacrebleu>=1.4.12` is required, and the current version of `sacrebleu` doesn't match this condition.\n"
													    "You can install it with `pip install \"sacrebleu>=1.4.12\"`."				)
										return datasets.MetricInfo(
										    description=_DESCRIPTION       ,							citation=_CITATION       ,							homepage="http://www.cs.umd.edu/~snover/tercom/"       ,							inputs_description=_KWARGS_DESCRIPTION       ,							features=datasets.Features(
										        {
										            "predictions": datasets.Value("string"       ,							id="sequence"				),
										            "references": datasets.Sequence(datasets.Value("string"       ,							id="sequence"				)       ,							id="references"				),
										        }				)       ,							codebase_urls=["https://github.com/mjpost/sacreBLEU#ter"]       ,							reference_urls=[
										        "https://github.com/jhclark/tercom",
										    ]       ,							)






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


										'''simple docstring'''




										snake_case_				:					List[str]   =       len(references[0]				)
										if any(len(lowerCAmelCase__				) != references_per_prediction for refs in references				):
													raise ValueError("Sacrebleu requires the same number of references for each prediction"				)
										snake_case_				:					List[str]   =       [[refs[i] for refs in references] for i in range(lowerCAmelCase__				)]

										snake_case_				:					List[str]   =       TER(
										    normalized=lowerCAmelCase__       ,							no_punct=lowerCAmelCase__       ,							asian_support=lowerCAmelCase__       ,							case_sensitive=lowerCAmelCase__       ,							)
										snake_case_				:					Any   =       sb_ter.corpus_score(lowerCAmelCase__       ,							lowerCAmelCase__				)

										return {"score": output.score, "num_edits": output.num_edits, "ref_length": output.ref_length}




