
'''simple docstring'''





import argparse
import os
import re
import zipfile

import torch

from transformers import MegatronBertConfig





def 							_lowerCamelCase			(					lowerCamelCase_:  Optional[Any]				,	lowerCamelCase_:  Union[str, Any]				,	lowerCamelCase_:  Dict=0		):



				'''simple docstring'''







				if name is None:
								A     :  int   =				None
				else:
								A     :  Optional[Any]   =				'''.''' * max(0				,	spaces - 2		) + '''# {:''' + str(50 - spaces		) + '''s}'''
								A     :  Any   =				fmt.format(UpperCamelCase__		)

				# Print and recurse (if needed).
				if isinstance(UpperCamelCase__				,	UpperCamelCase__		):
								if msg is not None:
												print(UpperCamelCase__		)
								for k in val.keys():
												recursive_print(UpperCamelCase__				,	val[k]				,	spaces + 2		)
				elif isinstance(UpperCamelCase__				,	torch.Tensor		):
								print(UpperCamelCase__				,	''':'''				,	val.size()		)
				else:
								print(UpperCamelCase__				,	''':'''				,	UpperCamelCase__		)





def 							_lowerCamelCase			(					lowerCamelCase_:  Dict				,	lowerCamelCase_:  List[str]				,	lowerCamelCase_:  List[str]				,	lowerCamelCase_:  Union[str, Any]				,	lowerCamelCase_:  Tuple		):



				'''simple docstring'''







				A     :  List[str]   =				param.size()
				if checkpoint_version == 1.0:
								# version 1.0 stores [num_heads * hidden_size * num_splits, :]
								A     :  Any   =				(num_heads, hidden_size, num_splits) + input_shape[1:]
								A     :  Any   =				param.view(*UpperCamelCase__		)
								A     :  List[str]   =				param.transpose(0				,	2		)
								A     :  Dict   =				param.transpose(1				,	2		).contiguous()
				elif checkpoint_version >= 2.0:
								# other versions store [num_heads * num_splits * hidden_size, :]
								A     :  str   =				(num_heads, num_splits, hidden_size) + input_shape[1:]
								A     :  Dict   =				param.view(*UpperCamelCase__		)
								A     :  Dict   =				param.transpose(0				,	1		).contiguous()
				A     :  str   =				param.view(*UpperCamelCase__		)
				return param





def 							_lowerCamelCase			(					lowerCamelCase_:  List[Any]				,	lowerCamelCase_:  List[Any]				,	lowerCamelCase_:  List[Any]		):



				'''simple docstring'''







				A     :  Optional[Any]   =				{}

				# old versions did not store training args
				A     :  List[str]   =				input_state_dict.get('''args'''				,	UpperCamelCase__		)
				if ds_args is not None:
								# do not make the user write a config file when the exact dimensions/sizes are already in the checkpoint
								# from pprint import pprint
								# pprint(vars(ds_args))

								A     :  int   =				ds_args.tokenizer_type
								A     :  str   =				ds_args.padded_vocab_size
								A     :  Optional[Any]   =				ds_args.max_position_embeddings
								A     :  Optional[int]   =				ds_args.hidden_size
								A     :  Union[str, Any]   =				ds_args.num_layers
								A     :  Optional[Any]   =				ds_args.num_attention_heads
								A     :  Dict   =				ds_args.ffn_hidden_size if '''ffn_hidden_size''' in ds_args else 4 * ds_args.hidden_size
								# pprint(config)

				# The number of heads.
				A     :  Tuple   =				config.num_attention_heads
				# The hidden_size per head.
				A     :  Optional[int]   =				config.hidden_size // heads
				# Megatron-LM checkpoint version
				if "checkpoint_version" in input_state_dict.keys():
								A     :  Dict   =				input_state_dict['''checkpoint_version''']
				else:
								A     :  Tuple   =				0.0

				# The model.
				A     :  Union[str, Any]   =				input_state_dict['''model''']
				# The language model.
				A     :  Dict   =				model['''language_model''']
				# The embeddings.
				A     :  List[Any]   =				lm['''embedding''']

				# The word embeddings.
				A     :  int   =				embeddings['''word_embeddings''']['''weight''']
				# Truncate the embedding table to vocab_size rows.
				A     :  Optional[Any]   =				word_embeddings[: config.vocab_size, :]
				# Store the word embeddings.
				A     :  str   =				word_embeddings

				# The position embeddings.
				A     :  List[Any]   =				embeddings['''position_embeddings''']['''weight''']
				assert pos_embeddings.size(0		) == config.max_position_embeddings and pos_embeddings.size(1		) == config.hidden_size
				# Store the position embeddings.
				A     :  Optional[int]   =				pos_embeddings

				# The token-type embeddings.
				A     :  Optional[int]   =				embeddings['''tokentype_embeddings''']['''weight''']
				# Store the position embeddings.
				A     :  str   =				tokentype_embeddings

				# The transformer.
				A     :  Optional[int]   =				lm['''transformer'''] if '''transformer''' in lm.keys() else lm['''encoder''']

				# The regex to extract layer names.
				A     :  int   =				re.compile(r'''layers\.(\d+)\.([a-z0-9_.]+)\.([a-z]+)'''		)

				# The simple map of names for "automated" rules.
				A     :  Any   =				{
				    '''attention.dense''': '''.attention.output.dense.''',
				    '''self_attention.dense''': '''.attention.output.dense.''',
				    '''mlp.dense_h_to_4h''': '''.intermediate.dense.''',
				    '''mlp.dense_4h_to_h''': '''.output.dense.''',
				}

				# Keep track of the attention/query/value tensor.
				A     :  Union[str, Any]   =				None

				# Extract the layers.
				for key, val in transformer.items():
								# Match the name.
								A     :  str   =				layer_re.match(UpperCamelCase__		)

								# Stop if that's not a layer
								if m is None:
												break

								# The index of the layer.
								A     :  Any   =				int(m.group(1		)		)
								# The name of the operation.
								A     :  Optional[Any]   =				m.group(2		)
								# Is it a weight or a bias?
								A     :  Any   =				m.group(3		)

								# The name of the layer.
								A     :  str   =				f"""bert.encoder.layer.{layer_idx}"""

								# For layernorm(s), simply store the layer norm.
								if op_name.endswith('''layernorm'''		):
												A     :  Optional[Any]   =				'''attention.ln''' if op_name.startswith('''input'''		) else '''ln'''
												A     :  List[str]   =				val

								# Transpose the QKV matrix.
								elif (
								    op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
								) and weight_or_bias == "weight":
												# Make sure the QKV pointer is nil.
												assert attention_qkv_weight is None, ""

												A     :  str   =				fix_query_key_value_ordering(UpperCamelCase__				,	UpperCamelCase__				,	3				,	UpperCamelCase__				,	UpperCamelCase__		)
												# Store the tensor as we need the bias as well to interleave QKV and biases.
												A     :  int   =				out_val

								# Transpose the bias.
								elif (
								    op_name == "attention.query_key_value" or op_name == "self_attention.query_key_value"
								) and weight_or_bias == "bias":
												# Make sure we read the weight tensor.
												assert attention_qkv_weight is not None, ""

												# Split the QKV matrix into Q, K and V. Megatron stores Q,K,V interleaved.
												A     :  List[Any]   =				attention_qkv_weight[0 * config.hidden_size : 1 * config.hidden_size, :]
												A     :  Any   =				attention_qkv_weight[1 * config.hidden_size : 2 * config.hidden_size, :]
												A     :  str   =				attention_qkv_weight[2 * config.hidden_size : 3 * config.hidden_size, :]

												A     :  int   =				fix_query_key_value_ordering(UpperCamelCase__				,	UpperCamelCase__				,	3				,	UpperCamelCase__				,	UpperCamelCase__		)
												# Split the bias.
												A     :  int   =				out_val[0 * config.hidden_size : 1 * config.hidden_size]
												A     :  Optional[Any]   =				out_val[1 * config.hidden_size : 2 * config.hidden_size]
												A     :  Optional[Any]   =				out_val[2 * config.hidden_size : 3 * config.hidden_size]

												# Store.
												A     :  str   =				q
												A     :  List[str]   =				q_bias
												A     :  Optional[int]   =				k
												A     :  Any   =				k_bias
												A     :  List[str]   =				v
												A     :  int   =				v_bias

												# Clear the stored tensor.
												A     :  Optional[Any]   =				None

								# Copy weights and biases as is.
								elif weight_or_bias in ["weight", "bias"]:
												A     :  List[Any]   =				megatron_to_transformers[op_name]
												A     :  Any   =				val

    # The final layernorm.
				A     :  Dict   =				transformer['''final_layernorm.weight''']
				A     :  List[str]   =				transformer['''final_layernorm.bias''']

				# The pooler.
				A     :  Dict   =				lm['''pooler''']

				# Store the matrix and the bias.
				A     :  Tuple   =				pooler['''dense.weight''']
				A     :  Any   =				pooler['''dense.bias''']

				# The LM head from Megatron (for RACE).
				A     :  Optional[int]   =				model['''lm_head''']

				# The transform matrix.
				A     :  List[str]   =				lm_head['''dense.weight''']
				A     :  int   =				lm_head['''dense.bias''']

				# The transform LN.
				A     :  Union[str, Any]   =				lm_head['''layernorm.weight''']
				A     :  Optional[int]   =				lm_head['''layernorm.bias''']

				# For the decoder, we replicate the weights.
				A     :  List[Any]   =				word_embeddings
				A     :  List[Any]   =				lm_head['''bias''']

				# The classifier from Megatron (for MLNI).
				A     :  Optional[int]   =				model['''binary_head''']

				# Store the classifier.
				A     :  Union[str, Any]   =				binary_head['''weight''']
				A     :  Dict   =				binary_head['''bias''']

				# It should be done!
				return output_state_dict





def 							_lowerCamelCase			(					):



				'''simple docstring'''







				A     :  Optional[Any]   =				argparse.ArgumentParser()
				parser.add_argument('''--print-checkpoint-structure'''				,	action='''store_true'''		)
				parser.add_argument('''path_to_checkpoint'''				,	type=UpperCamelCase__				,	help='''Path to the ZIP file containing the checkpoint'''		)
				parser.add_argument(
				    '''--config_file'''				,	default=''''''				,	type=UpperCamelCase__				,	help='''An optional config json file describing the pre-trained model.'''				,	)
				A     :  List[str]   =				parser.parse_args()

				# Extract the basename.
				A     :  Dict   =				os.path.dirname(args.path_to_checkpoint		)

				# Load the model.
				# the .zip is very optional, let's keep it for backward compatibility
				print(f"""Extracting PyTorch state dictionary from \"{args.path_to_checkpoint}\""""		)
				if args.path_to_checkpoint.endswith('''.zip'''		):
								with zipfile.ZipFile(args.path_to_checkpoint				,	'''r'''		) as checkpoint:
												with checkpoint.open('''release/mp_rank_00/model_optim_rng.pt'''		) as pytorch_dict:
																A     :  Optional[Any]   =				torch.load(UpperCamelCase__				,	map_location='''cpu'''		)
				else:
								A     :  Optional[int]   =				torch.load(args.path_to_checkpoint				,	map_location='''cpu'''		)

				if args.config_file == "":
								# Default config of megatron-bert 345m
								A     :  List[str]   =				MegatronBertConfig()

								# different megatron-bert-*-345m models have different vocab sizes, so override the default
								# config (which is for megatron-bert-cased-345m) with the actual vocab dimension
								A     :  List[str]   =				input_state_dict['''model''']['''lm_head''']['''bias'''].numel()
				else:
								A     :  List[Any]   =				MegatronBertConfig.from_json_file(args.config_file		)

				# Convert.
				print('''Converting'''		)
				A     :  int   =				convert_megatron_checkpoint(UpperCamelCase__				,	UpperCamelCase__				,	UpperCamelCase__		)

				# Print the structure of converted state dict.
				if args.print_checkpoint_structure:
								recursive_print(UpperCamelCase__				,	UpperCamelCase__		)

				# Store the config to file.
				print('''Saving config'''		)
				config.save_pretrained(UpperCamelCase__		)

				# Store the state_dict to file.
				A     :  List[str]   =				os.path.join(UpperCamelCase__				,	'''pytorch_model.bin'''		)
				print(f"""Saving checkpoint to \"{output_checkpoint_file}\""""		)
				torch.save(UpperCamelCase__				,	UpperCamelCase__		)


####################################################################################################

if __name__ == "__main__":
					main()

####################################################################################################

UpperCamelCase_  =	10_00





def 							_lowerCamelCase			(					lowerCamelCase_:  float		):



				'''simple docstring'''







				return x * x





def 							_lowerCamelCase			(					lowerCamelCase_:  Tuple				,	lowerCamelCase_:  float				,	lowerCamelCase_:  float				,	lowerCamelCase_:  int = 4		):



				'''simple docstring'''







				assert callable(
				    lowerCamelCase_		), f"""the function(object) passed should be callable your input : {function}"""
				assert isinstance(lowerCamelCase_				,	(float, int)		), f"""a should be float or integer your input : {a}"""
				assert isinstance(function(lowerCamelCase_		)				,	(float, int)		), (
				    "the function should return integer or float return type of your function, "
				    f"""{type(lowerCamelCase_		)}"""
				)
				assert isinstance(lowerCamelCase_				,	(float, int)		), f"""b should be float or integer your input : {b}"""
				assert (
				    isinstance(lowerCamelCase_				,	lowerCamelCase_		) and precision > 0
				), f"""precision should be positive integer your input : {precision}"""

				# just applying the formula of simpson for approximate integration written in
				# mentioned article in first comment of this file and above this function

				A     :  Tuple   =				(b - a) / N_STEPS
				A     :  List[str]   =				function(lowerCamelCase_		) + function(lowerCamelCase_		)

				for i in range(1				,	lowerCamelCase_		):
								A     :  int   =				a + h * i
								result += function(lowerCamelCase_		) * (4 if i % 2 else 2)

				result *= h / 3
				return round(lowerCamelCase_				,	lowerCamelCase_		)


if __name__ == "__main__":
					import doctest

					doctest.testmod()