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()

a_							=      [
    """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""",
]

a_							=      [
    """mlp.dense_4h_to_h.weight""",
    """self_attention.dense.weight""",
]




def       __lowerCAmelCase      (						A_   : Optional[Any]						,	A_   : List[str]					)    ->  Optional[Any]:
  __UpperCAmelCase						    =       {
      "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
  __UpperCAmelCase						    =       int(re.match(r".*layer_(\d*).*"						,	A_					)[1]					)
  layer_number -= 3
  return F'''h.{layer_number}.''' + key




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




def       __lowerCAmelCase      (						A_   : Optional[int]						,	A_   : List[str]						,	A_   : Any						,	A_   : Optional[int]						,	A_   : int					)    ->  Dict:
  # Construct model
  if bloom_config_file == "":
    __UpperCAmelCase						    =       BloomConfig()
  else:
    __UpperCAmelCase						    =       BloomConfig.from_json_file(A_					)

  if shard_model:
    __UpperCAmelCase						    =       os.listdir(A_					)
    __UpperCAmelCase						    =       sorted(filter(lambda A_					: s.startswith("layer"					) and "model_00" in s						,	A_					)					)

    __UpperCAmelCase						    =       {"weight_map": {}, "metadata": {}}
    __UpperCAmelCase						    =       0

    __UpperCAmelCase						    =       None

    __UpperCAmelCase						    =       BloomConfig()

    for j, file in enumerate(A_					):
      print("Processing file: {}".format(A_					)					)
      __UpperCAmelCase						    =       None

      for i in range(A_					):
        # load all TP files
        __UpperCAmelCase						    =       file.replace("model_00"						,	F'''model_0{i}'''					)
        __UpperCAmelCase						    =       torch.load(os.path.join(A_						,	A_					)						,	map_location="cpu"					)

        # Rename keys in the transformers names
        __UpperCAmelCase						    =       list(temp.keys()					)
        for key in keys:
          __UpperCAmelCase						    =       temp.pop(A_					)

        if tensors is None:
          __UpperCAmelCase						    =       temp
        else:
          for key in tensors.keys():
            if any(key.endswith(A_					) 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
              __UpperCAmelCase						    =       1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN					) else 0
              # We concatenate these weights accross TP ranks
              __UpperCAmelCase						    =       torch.cat([tensors[key], temp[key]]						,	dim=A_					)

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

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

    __UpperCAmelCase						    =       BloomConfig()
    __UpperCAmelCase						    =       pytorch_dump_folder_path + "/" + CONFIG_NAME
    __UpperCAmelCase						    =       total_size
    with open(A_						,	"w"						,	encoding="utf-8"					) as f:
      f.write(config.to_json_string()					)
    with open(os.path.join(A_						,	WEIGHTS_NAME + ".index.json"					)						,	"w"						,	encoding="utf-8"					) as f:
      __UpperCAmelCase						    =       json.dumps(A_						,	indent=2						,	sort_keys=A_					) + "\n"
      f.write(A_					)
  else:
    __UpperCAmelCase						    =       BloomModel(A_					)

    __UpperCAmelCase						    =       os.listdir(A_					)
    __UpperCAmelCase						    =       sorted(filter(lambda A_					: s.startswith("layer"					) and "model_00" in s						,	A_					)					)

    __UpperCAmelCase						    =       None
    for i, file in enumerate(A_					):
      __UpperCAmelCase						    =       None
      for i in range(A_					):
        # load all TP files
        __UpperCAmelCase						    =       file.replace("model_00"						,	F'''model_0{i}'''					)
        __UpperCAmelCase						    =       torch.load(os.path.join(A_						,	A_					)						,	map_location="cpu"					)

        # Rename keys in the transformers names
        __UpperCAmelCase						    =       list(temp.keys()					)
        for key in keys:
          __UpperCAmelCase						    =       temp.pop(A_					)

        if tensors is None:
          __UpperCAmelCase						    =       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(A_					) for end in WEIGHTS_TO_AVERAGE_ENDSWITH					):
              tensors[key] += temp[key]
            else:
              # Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel
              __UpperCAmelCase						    =       1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN					) else 0
              # We concatenate these weights accross TP ranks
              __UpperCAmelCase						    =       torch.cat([tensors[key], temp[key]]						,	dim=A_					)

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

      __UpperCAmelCase						    =       model.load_state_dict(A_						,	strict=A_					)
      assert not other_keys.unexpected_keys, F'''The keys {other_keys.unexpected_keys} are unexpected'''
      if missing_keys is None:
        __UpperCAmelCase						    =       set(other_keys.missing_keys					)
      else:
        __UpperCAmelCase						    =       missing_keys.intersection(set(other_keys.missing_keys					)					)

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

    # Save pytorch-model
    os.makedirs(A_						,	exist_ok=A_					)
    __UpperCAmelCase						    =       pytorch_dump_folder_path + "/" + WEIGHTS_NAME
    __UpperCAmelCase						    =       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:
      __UpperCAmelCase						    =       model.to(config.torch_dtype					)
    torch.save(model.state_dict()						,	A_					)
    print(F'''Save configuration file to {pytorch_config_dump_path}'''					)
    with open(A_						,	"w"						,	encoding="utf-8"					) as f:
      f.write(config.to_json_string()					)


if __name__ == "__main__":
       a_							=      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""",
       )
       a_							=      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,
       )




import unittest

from transformers import AlbertTokenizer, AlbertTokenizerFast
from transformers.testing_utils import get_tests_dir, require_sentencepiece, require_tokenizers, slow

from ...test_tokenization_common import TokenizerTesterMixin


a_							=      get_tests_dir("""fixtures/spiece.model""")


@require_sentencepiece
@require_tokenizers
class 			UpperCAmelCase__    (		snake_case		,	unittest.TestCase					):



  """simple docstring"""






  lowerCAmelCase__		:	List[Any]    		= AlbertTokenizer
  lowerCAmelCase__		:	int    		= AlbertTokenizerFast
  lowerCAmelCase__		:	str    		= True
  lowerCAmelCase__		:	Union[str, Any]    		= True
  lowerCAmelCase__		:	int    		= True






  def 	_UpperCAmelCase				(				self:			Union[str, Any]   ) -> str:




    '''simple docstring'''




    super().setUp()

    # We have a SentencePiece fixture for testing
    __UpperCAmelCase						    =       AlbertTokenizer(__lowerCAmelCase   )
    tokenizer.save_pretrained(self.tmpdirname   )






  def 	_UpperCAmelCase				(				self:			Any				,				__lowerCAmelCase:			Tuple   ) -> Union[str, Any]:




    '''simple docstring'''




    __UpperCAmelCase						    =       "this is a test"
    __UpperCAmelCase						    =       "this is a test"
    return input_text, output_text






  def 	_UpperCAmelCase				(				self:			Dict   ) -> List[Any]:




    '''simple docstring'''




    __UpperCAmelCase						    =       "<pad>"
    __UpperCAmelCase						    =       0

    self.assertEqual(self.get_tokenizer()._convert_token_to_id(__lowerCAmelCase   )				,				__lowerCAmelCase   )
    self.assertEqual(self.get_tokenizer()._convert_id_to_token(__lowerCAmelCase   )				,				__lowerCAmelCase   )






  def 	_UpperCAmelCase				(				self:			str   ) -> Optional[Any]:




    '''simple docstring'''




    __UpperCAmelCase						    =       list(self.get_tokenizer().get_vocab().keys()   )

    self.assertEqual(vocab_keys[0]				,				"<pad>"   )
    self.assertEqual(vocab_keys[1]				,				"<unk>"   )
    self.assertEqual(vocab_keys[-1]				,				"▁eloquent"   )
    self.assertEqual(len(__lowerCAmelCase   )				,				30_000   )






  def 	_UpperCAmelCase				(				self:			Union[str, Any]   ) -> List[str]:




    '''simple docstring'''




    self.assertEqual(self.get_tokenizer().vocab_size				,				30_000   )






  def 	_UpperCAmelCase				(				self:			str   ) -> int:




    '''simple docstring'''




    if not self.test_rust_tokenizer:
      return

    __UpperCAmelCase						    =       self.get_tokenizer()
    __UpperCAmelCase						    =       self.get_rust_tokenizer()

    __UpperCAmelCase						    =       "I was born in 92000, and this is falsé."

    __UpperCAmelCase						    =       tokenizer.tokenize(__lowerCAmelCase   )
    __UpperCAmelCase						    =       rust_tokenizer.tokenize(__lowerCAmelCase   )
    self.assertListEqual(__lowerCAmelCase				,				__lowerCAmelCase   )

    __UpperCAmelCase						    =       tokenizer.encode(__lowerCAmelCase				,				add_special_tokens=__lowerCAmelCase   )
    __UpperCAmelCase						    =       rust_tokenizer.encode(__lowerCAmelCase				,				add_special_tokens=__lowerCAmelCase   )
    self.assertListEqual(__lowerCAmelCase				,				__lowerCAmelCase   )

    __UpperCAmelCase						    =       self.get_rust_tokenizer()
    __UpperCAmelCase						    =       tokenizer.encode(__lowerCAmelCase   )
    __UpperCAmelCase						    =       rust_tokenizer.encode(__lowerCAmelCase   )
    self.assertListEqual(__lowerCAmelCase				,				__lowerCAmelCase   )






  def 	_UpperCAmelCase				(				self:			Optional[Any]   ) -> Any:




    '''simple docstring'''




    __UpperCAmelCase						    =       AlbertTokenizer(__lowerCAmelCase				,				keep_accents=__lowerCAmelCase   )

    __UpperCAmelCase						    =       tokenizer.tokenize("This is a test"   )
    self.assertListEqual(__lowerCAmelCase				,				["▁this", "▁is", "▁a", "▁test"]   )

    self.assertListEqual(tokenizer.convert_tokens_to_ids(__lowerCAmelCase   )				,				[48, 25, 21, 1_289]   )

    __UpperCAmelCase						    =       tokenizer.tokenize("I was born in 92000, and this is falsé."   )
    self.assertListEqual(
        __lowerCAmelCase				,				["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "é", "."]   )
    __UpperCAmelCase						    =       tokenizer.convert_tokens_to_ids(__lowerCAmelCase   )
    self.assertListEqual(__lowerCAmelCase				,				[31, 23, 386, 19, 561, 3_050, 15, 17, 48, 25, 8_256, 18, 1, 9]   )

    __UpperCAmelCase						    =       tokenizer.convert_ids_to_tokens(__lowerCAmelCase   )
    self.assertListEqual(
        __lowerCAmelCase				,				["▁i", "▁was", "▁born", "▁in", "▁9", "2000", ",", "▁and", "▁this", "▁is", "▁fal", "s", "<unk>", "."]				,				)






  def 	_UpperCAmelCase				(				self:			str   ) -> Dict:




    '''simple docstring'''




    __UpperCAmelCase						    =       AlbertTokenizer(__lowerCAmelCase   )

    __UpperCAmelCase						    =       tokenizer.encode("sequence builders"   )
    __UpperCAmelCase						    =       tokenizer.encode("multi-sequence build"   )

    __UpperCAmelCase						    =       tokenizer.build_inputs_with_special_tokens(__lowerCAmelCase   )
    __UpperCAmelCase						    =       tokenizer.build_inputs_with_special_tokens(__lowerCAmelCase				,				__lowerCAmelCase   )

    assert encoded_sentence == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id]
    assert encoded_pair == [tokenizer.cls_token_id] + text + [tokenizer.sep_token_id] + text_a + [
        tokenizer.sep_token_id
    ]






  @slow
  def 	_UpperCAmelCase				(				self:			Optional[int]   ) -> str:




    '''simple docstring'''




    __UpperCAmelCase						    =       {"attention_mask": [[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], "input_ids": [[2, 21_970, 13, 5, 6_092, 167, 28, 7_103, 2_153, 673, 8, 7_028, 12_051, 18, 17, 7_103, 2_153, 673, 8, 3_515, 18_684, 8, 4_461, 6, 1_927, 297, 8, 12_060, 2_607, 18, 13, 5, 4_461, 15, 10_538, 38, 8, 135, 15, 822, 58, 15, 993, 10_363, 15, 1_460, 8_005, 4_461, 15, 993, 255, 2_328, 9, 9, 9, 6, 26, 1_112, 816, 3_260, 13, 5, 103, 2_377, 6, 17, 1_112, 816, 2_782, 13, 5, 103, 10_641, 6, 29, 84, 2_512, 2_430, 782, 18_684, 2_761, 19, 808, 2_430, 2_556, 17, 855, 1_480, 9_477, 4_091, 128, 11_712, 15, 7_103, 2_153, 673, 17, 24_883, 9_990, 9, 3], [2, 11_502, 25, 1_006, 20, 782, 8, 11_809, 855, 1_732, 19_393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, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]}  # noqa: E501
    # fmt: on

    self.tokenizer_integration_test_util(
        expected_encoding=__lowerCAmelCase				,				model_name="albert-base-v2"				,				revision="6b6560eaf5ff2e250b00c50f380c5389a9c2d82e"				,				)



