
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 				a						(							snake_case__:					List[Any]						,   snake_case__:					Dict					):


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




def 				a						(							snake_case__:					int					):


				'''simple docstring'''


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




def 				a						(							snake_case__:					int						,   snake_case__:					List[str]						,   snake_case__:					Tuple						,   snake_case__:					Dict						,   snake_case__:					Optional[Any]					):


				'''simple docstring'''


				if bloom_config_file == "":
								lowercase_       =					BloomConfig()
				else:
								lowercase_       =					BloomConfig.from_json_file(_UpperCamelCase					)

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

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

								lowercase_       =					None

								lowercase_       =					BloomConfig()

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

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

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

																if tensors is None:
																				lowercase_       =					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
																												lowercase_       =					1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN					) else 0
																												# We concatenate these weights accross TP ranks
																												lowercase_       =					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					):
																				lowercase_       =					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():
																lowercase_       =					tensors[key]
																total_size += value.numel() * get_dtype_size(value.dtype					)
																if key not in index_dict["weight_map"]:
																				lowercase_       =					'''pytorch_model_{}-of-{}.bin'''.format(
																				    str(j + 1					).zfill(5					)						,   str(len(_UpperCamelCase					)					).zfill(5					)					)

								lowercase_       =					BloomConfig()
								lowercase_       =					pytorch_dump_folder_path + '''/''' + CONFIG_NAME
								lowercase_       =					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:
												lowercase_       =					json.dumps(_UpperCamelCase						,   indent=2						,   sort_keys=_UpperCamelCase					) + '''\n'''
												f.write(_UpperCamelCase					)
				else:
								lowercase_       =					BloomModel(_UpperCamelCase					)

								lowercase_       =					os.listdir(_UpperCamelCase					)
								lowercase_       =					sorted(filter(lambda snake_case__					: s.startswith('''layer'''					) and "model_00" in s						,   _UpperCamelCase					)					)

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

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

																if tensors is None:
																				lowercase_       =					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
																												lowercase_       =					1 if any(text in key for text in WEIGHTS_WITH_ROW_PARALLELISM_CONTAIN					) else 0
																												# We concatenate these weights accross TP ranks
																												lowercase_       =					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					):
																				lowercase_       =					tensors[key] / pretraining_tp

												lowercase_       =					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:
																lowercase_       =					set(other_keys.missing_keys					)
												else:
																lowercase_       =					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					)
								lowercase_       =					pytorch_dump_folder_path + '''/''' + WEIGHTS_NAME
								lowercase_       =					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:
												lowercase_       =					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__":
						__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 argparse
import logging
import os

import datasets
import tensorflow as tf

from transformers import AutoTokenizer


lowerCAmelCase_    =				logging.getLogger(__name__)






def      lowerCamelCase_						(				)		->						Optional[Any]:






				"""simple docstring"""


				snake_case_						:    List[str]				=  argparse.ArgumentParser(
				    description='''Prepare TFRecord shards from pre-tokenized samples of the wikitext dataset.''' )
				parser.add_argument(
				    '''--dataset_name''' ,				type=_UpperCamelCase ,				default='''wikitext''' ,				help='''Name of the training. Explore datasets at: hf.co/datasets.''' ,				)
				parser.add_argument(
				    '''--dataset_config''' ,				type=_UpperCamelCase ,				default='''wikitext-103-raw-v1''' ,				help='''Configuration name of the dataset.''' )
				parser.add_argument(
				    '''--tokenizer_name_or_path''' ,				type=_UpperCamelCase ,				default='''sayakpaul/unigram-tokenizer-wikitext''' ,				help='''Tokenizer identifier. Can be a local filepath or a Hub identifier.''' ,				)
				parser.add_argument(
				    '''--shard_size''' ,				type=_UpperCamelCase ,				default=1_000 ,				help='''Number of entries to go in a single shard.''' ,				)
				parser.add_argument('''--split''' ,				type=_UpperCamelCase ,				default='''train''' ,				choices=['''train''', '''test''', '''validation'''] )
				parser.add_argument(
				    '''--limit''' ,				default=_UpperCamelCase ,				type=_UpperCamelCase ,				help='''Limit the number of shards (used for debugging).''' ,				)
				parser.add_argument(
				    '''--max_length''' ,				type=_UpperCamelCase ,				default=512 ,				help='''Maximum sequence length. For training on TPUs, it helps to have a maximum'''
				    ''' sequence length that is a multiple of 8.''' ,				)
				parser.add_argument(
				    '''--output_dir''' ,				default='''tf-tpu''' ,				type=_UpperCamelCase ,				help='''Output directory where the TFRecord shards will be saved. If the'''
				    ''' path is appended with `gs://` (\'gs://tf-tpu\', for example) then the TFRecord'''
				    ''' shards will be directly saved to a Google Cloud Storage bucket.''' ,				)

				snake_case_						:    List[Any]				=  parser.parse_args()
				return args






def      lowerCamelCase_						(				_UpperCamelCase )		->						Tuple:






				"""simple docstring"""


				def fn(_UpperCamelCase ):
								return tokenizer(examples['''text'''] )

				return fn






def      lowerCamelCase_						(				_UpperCamelCase )		->						Union[str, Any]:






				"""simple docstring"""


				snake_case_						:    Any				=  []
				for i in range(len(tokenized_data['''input_ids'''] ) ):
								snake_case_						:    Any				=  {
								    '''input_ids''': tf.train.Feature(intaa_list=tf.train.IntaaList(value=tokenized_data['''input_ids'''][i] ) ),
								    '''attention_mask''': tf.train.Feature(
								        intaa_list=tf.train.IntaaList(value=tokenized_data['''attention_mask'''][i] ) ),
								}
								snake_case_						:    Optional[int]				=  tf.train.Features(feature=_UpperCamelCase )
								snake_case_						:    Optional[Any]				=  tf.train.Example(features=_UpperCamelCase )
								snake_case_						:    Optional[Any]				=  example.SerializeToString()
								records.append(_UpperCamelCase )
				return records






def      lowerCamelCase_						(				_UpperCamelCase )		->						Optional[int]:






				"""simple docstring"""


				snake_case_						:    int				=  datasets.load_dataset(args.dataset_name ,				args.dataset_config ,				split=args.split )

				if args.limit is not None:
								snake_case_						:    Union[str, Any]				=  min(len(_UpperCamelCase ) ,				args.limit )
								snake_case_						:    int				=  dataset.select(range(_UpperCamelCase ) )
								print(f'''Limiting the dataset to {args.limit} entries.''' )

				snake_case_						:    Dict				=  AutoTokenizer.from_pretrained(args.tokenizer_name_or_path )

				# Handle output directory creation.
				# For serializing into a Google Cloud Storage Bucket, one needs to first
				# create a bucket.
				if "gs" not in args.output_dir:
								if not os.path.exists(args.output_dir ):
												os.makedirs(args.output_dir )
								snake_case_						:    str				=  os.path.join(args.output_dir ,				args.split )
								if not os.path.exists(_UpperCamelCase ):
												os.makedirs(_UpperCamelCase )
				else:
								snake_case_						:    Optional[Any]				=  os.path.join(args.output_dir ,				args.split )

				# Tokenize the whole dataset at once.
				snake_case_						:    Optional[Any]				=  tokenize_function(_UpperCamelCase )
				snake_case_						:    List[Any]				=  dataset.map(_UpperCamelCase ,				batched=_UpperCamelCase ,				num_proc=4 ,				remove_columns=['''text'''] )

				# We need to concatenate all our texts together, and then split the result
				# into chunks of a fixed size, which we will call block_size. To do this, we
				# will use the map method again, with the option batched=True. When we use batched=True,
				# the function we pass to map() will be passed multiple inputs at once, allowing us
				# to group them into more or fewer examples than we had in the input.
				# This allows us to create our new fixed-length samples. The advantage of this
				# method is that we don't lose a whole lot of content from the dataset compared to the
				# case where we simply tokenize with a pre-defined max_length.

				def group_texts(_UpperCamelCase ):
								# Concatenate all texts.
								snake_case_						:    Tuple				=  {k: sum(examples[k] ,				[] ) for k in examples.keys()}
								snake_case_						:    List[str]				=  len(concatenated_examples[list(examples.keys() )[0]] )
								# We drop the small remainder, though you could add padding instead if the model supports it
								# In this, as in all things, we advise you to follow your heart 🫀
								snake_case_						:    int				=  (total_length // args.max_length) * args.max_length
								# Split by chunks of max_len.
								snake_case_						:    Union[str, Any]				=  {
								    k: [t[i : i + args.max_length] for i in range(0 ,				_UpperCamelCase ,				args.max_length )]
								    for k, t in concatenated_examples.items()
								}
								return result

				snake_case_						:    int				=  dataset_tokenized.map(_UpperCamelCase ,				batched=_UpperCamelCase ,				batch_size=1_000 ,				num_proc=4 )

				snake_case_						:    str				=  0
				snake_case_						:    Optional[Any]				=  0
				for shard in range(0 ,				len(_UpperCamelCase ) ,				args.shard_size ):
								snake_case_						:    Any				=  grouped_dataset[shard : shard + args.shard_size]
								snake_case_						:    str				=  len(dataset_snapshot['''input_ids'''] )
								snake_case_						:    Union[str, Any]				=  os.path.join(_UpperCamelCase ,				f'''dataset-{shard_count}-{records_containing}.tfrecord''' )
								snake_case_						:    Dict				=  get_serialized_examples(_UpperCamelCase )

								with tf.io.TFRecordWriter(_UpperCamelCase ) as out_file:
												for i in range(len(_UpperCamelCase ) ):
																snake_case_						:    List[str]				=  serialized_examples[i]
																out_file.write(_UpperCamelCase )
												print('''Wrote file {} containing {} records'''.format(_UpperCamelCase ,				_UpperCamelCase ) )

								shard_count += 1
								total_records += records_containing

				with open(f'''split-{args.split}-records-count.txt''' ,				'''w''' ) as f:
								print(f'''Total {args.split} records: {total_records}''' ,				file=_UpperCamelCase )


if __name__ == "__main__":
	lowerCAmelCase_    =				parse_args()
	main(args)
