





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

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

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





def   lowerCamelCase__       (       UpperCamelCase__     :    int    ,      UpperCamelCase__     :    Any  )     ->	Dict:



					'''simple docstring'''




					_snake_case													=			{
					    '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													=			int(re.match(R'.*layer_(\d*).*'    ,      UpperCamelCase__  )[1]  )
					layer_number -= 3
					return F'''h.{layer_number}.''' + key





def   lowerCamelCase__       (       UpperCamelCase__     :    Tuple  )     ->	Union[str, Any]:



					'''simple docstring'''




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





def   lowerCamelCase__       (       UpperCamelCase__     :    int    ,      UpperCamelCase__     :    List[str]    ,      UpperCamelCase__     :    Optional[Any]    ,      UpperCamelCase__     :    List[str]    ,      UpperCamelCase__     :    List[Any]  )     ->	Union[str, Any]:



					'''simple docstring'''




					if bloom_config_file == "":
										_snake_case													=			BloomConfig()
					else:
										_snake_case													=			BloomConfig.from_json_file(UpperCamelCase__  )

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

										_snake_case													=			{'weight_map': {}, 'metadata': {}}
										_snake_case													=			0

										_snake_case													=			None

										_snake_case													=			BloomConfig()

										for j, file in enumerate(UpperCamelCase__  ):
															print('Processing file: {}'.format(UpperCamelCase__  )  )
															_snake_case													=			None

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

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

																				if tensors is None:
																									_snake_case													=			temp
																				else:
																									for key in tensors.keys():
																														if any(key.endswith(UpperCamelCase__  ) 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													=			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													=			torch.cat([tensors[key], temp[key]]    ,      dim=UpperCamelCase__  )

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

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

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

										_snake_case													=			os.listdir(UpperCamelCase__  )
										_snake_case													=			sorted(filter(lambda UpperCamelCase__  : s.startswith('layer'  ) and "model_00" in s    ,      UpperCamelCase__  )  )

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

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

																				if tensors is None:
																									_snake_case													=			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(UpperCamelCase__  ) for end in WEIGHTS_TO_AVERAGE_ENDSWITH  ):
																																			tensors[key] += temp[key]
																														else:
																																			# Some weights are RowParallelLinear in Megatron-Deepspeed, others are ColumnParallel
																																			_snake_case													=			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													=			torch.cat([tensors[key], temp[key]]    ,      dim=UpperCamelCase__  )

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

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

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

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


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










from collections import OrderedDict
from typing import Any, Mapping, Optional

from ... import PreTrainedTokenizer, TensorType, is_torch_available
from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfigWithPast
from ...utils import logging


UpperCAmelCase_ 							=       logging.get_logger(__name__)

UpperCAmelCase_ 							=       {
    """EleutherAI/gpt-neo-1.3B""": """https://huggingface.co/EleutherAI/gpt-neo-1.3B/resolve/main/config.json""",
    # See all GPTNeo models at https://huggingface.co/models?filter=gpt_neo
}
class      UpperCamelCase_						(					_lowerCamelCase   ):
					lowerCAmelCase_							=		'''gpt_neo'''
					lowerCAmelCase_							=		['''past_key_values''']
					lowerCAmelCase_							=		{'''num_attention_heads''': '''num_heads''', '''num_hidden_layers''': '''num_layers'''}




					def __init__(						self			,  lowerCAmelCase_=5_0257			,  lowerCAmelCase_=2048			,  lowerCAmelCase_=2048			,  lowerCAmelCase_=24			,  lowerCAmelCase_=[[["global", "local"], 12]]			,  lowerCAmelCase_=16			,  lowerCAmelCase_=None			,  lowerCAmelCase_=256			,  lowerCAmelCase_="gelu_new"			,  lowerCAmelCase_=0.0			,  lowerCAmelCase_=0.0			,  lowerCAmelCase_=0.0			,  lowerCAmelCase_=0.1			,  lowerCAmelCase_=1E-5			,  lowerCAmelCase_=0.02			,  lowerCAmelCase_=True			,  lowerCAmelCase_=5_0256			,  lowerCAmelCase_=5_0256			,  **lowerCAmelCase_			,  )						->							Tuple:
										_snake_case													=			vocab_size
										_snake_case													=			max_position_embeddings
										_snake_case													=			hidden_size
										_snake_case													=			num_layers
										_snake_case													=			num_heads
										_snake_case													=			intermediate_size
										_snake_case													=			window_size
										_snake_case													=			activation_function
										_snake_case													=			resid_dropout
										_snake_case													=			embed_dropout
										_snake_case													=			attention_dropout
										_snake_case													=			classifier_dropout
										_snake_case													=			layer_norm_epsilon
										_snake_case													=			initializer_range
										_snake_case													=			use_cache

										_snake_case													=			bos_token_id
										_snake_case													=			eos_token_id

										_snake_case													=			attention_types
										_snake_case													=			self.expand_attention_types_params(lowerCAmelCase_					)

										if len(self.attention_layers					) != self.num_layers:
															raise ValueError(
															    'Configuration for convolutional module is incorrect. '
															    'It is required that `len(config.attention_layers)` == `config.num_layers` '
															    F'''but is `len(config.attention_layers) = {len(self.attention_layers					)}`, '''
															    F'''`config.num_layers = {self.num_layers}`. '''
															    '`config.attention_layers` is prepared using `config.attention_types`. '
															    'Please verify the value of `config.attention_types` argument.'					)

										super().__init__(bos_token_id=lowerCAmelCase_			,  eos_token_id=lowerCAmelCase_			,  **lowerCAmelCase_					)






					@staticmethod
					def 		lowerCAmelCase     (						lowerCAmelCase_					)						->							Any:
										_snake_case													=			[]
										for item in attention_types:
															for _ in range(item[1]					):
																				attentions.extend(item[0]					)
										return attentions





def   lowerCamelCase__       (       UpperCamelCase__     :    Tuple    ,      UpperCamelCase__     :    int    ,      UpperCamelCase__     :    Tuple    ,      UpperCamelCase__     :    Optional[int]  )     ->	Any:



					'''simple docstring'''




					import torch

					_snake_case													=			input.size()
					_snake_case													=			len(UpperCamelCase__  )
					_snake_case													=			shape[dimension]

					_snake_case													=			torch.arange(0    ,      UpperCamelCase__    ,      UpperCamelCase__  )
					_snake_case													=			torch.div(sizedim - size    ,      UpperCamelCase__    ,      rounding_mode='floor'  ) + 1
					_snake_case													=			torch.arange(UpperCamelCase__  ) + low_indices[:min_length][:, None]

					_snake_case													=			[slice(UpperCamelCase__  )] * rank
					_snake_case													=			indices
					_snake_case													=			input[s]

					_snake_case													=			list(range(0    ,      rank + 1  )  )
					perm.append(perm.pop(dimension + 1  )  )

					return sliced.permute(UpperCamelCase__  )





def   lowerCamelCase__       (       UpperCamelCase__     :    Tuple    ,      UpperCamelCase__     :    Dict  )     ->	str:



					'''simple docstring'''




					import torch

					_snake_case													=			torch.arange(1    ,      UpperCamelCase__  )
					_snake_case													=			torch.remainder(UpperCamelCase__    ,      UpperCamelCase__  )
					_snake_case													=			remainders == 0
					_snake_case													=			candidates[divisor_indices]
					_snake_case													=			torch.max(UpperCamelCase__  )
					return largest_divisor, torch.div(UpperCamelCase__    ,      UpperCamelCase__    ,      rounding_mode='floor'  )




class      UpperCamelCase_						(					_lowerCamelCase   ):




					@property
					def 		lowerCAmelCase     (						self					)						->							Mapping[str, Mapping[int, str]]:
										_snake_case													=			OrderedDict({'input_ids': {0: 'batch', 1: 'sequence'}}					)
										if self.use_past:
															self.fill_with_past_key_values_(lowerCAmelCase_			,  direction='inputs'					)
															_snake_case													=			{0: 'batch', 1: 'past_sequence + sequence'}
										else:
															_snake_case													=			{0: 'batch', 1: 'sequence'}

										return common_inputs




					@property
					def 		lowerCAmelCase     (						self					)						->							int:
										return self._config.num_heads




					def 		lowerCAmelCase     (						self			,  lowerCAmelCase_			,  lowerCAmelCase_ = -1			,  lowerCAmelCase_ = -1			,  lowerCAmelCase_ = False			,  lowerCAmelCase_ = None			,  )						->							Mapping[str, Any]:
										_snake_case													=			super(lowerCAmelCase_			,  self					).generate_dummy_inputs(
										    lowerCAmelCase_			,  batch_size=lowerCAmelCase_			,  seq_length=lowerCAmelCase_			,  is_pair=lowerCAmelCase_			,  framework=lowerCAmelCase_					)

										# We need to order the input in the way they appears in the forward()
										_snake_case													=			OrderedDict({'input_ids': common_inputs['input_ids']}					)

										# Need to add the past_keys
										if self.use_past:
															if not is_torch_available():
																				raise ValueError('Cannot generate dummy past_keys inputs without PyTorch installed.'					)
															else:
																				import torch

																				_snake_case							,       _snake_case													=			common_inputs['input_ids'].shape
																				# Not using the same length for past_key_values
																				_snake_case													=			seqlen + 2
																				_snake_case													=			(
																				    batch,
																				    self.num_attention_heads,
																				    past_key_values_length,
																				    self._config.hidden_size // self.num_attention_heads,
																				)
																				_snake_case													=			[
																				    (torch.zeros(lowerCAmelCase_					), torch.zeros(lowerCAmelCase_					)) for _ in range(self.num_layers					)
																				]

										_snake_case													=			common_inputs['attention_mask']
										if self.use_past:
															_snake_case													=			ordered_inputs['attention_mask'].dtype
															_snake_case													=			torch.cat(
															    [ordered_inputs['attention_mask'], torch.ones(lowerCAmelCase_			,  lowerCAmelCase_			,  dtype=lowerCAmelCase_					)]			,  dim=1					)

										return ordered_inputs






					@property
					def 		lowerCAmelCase     (						self					)						->							int:
										return 13



