"""simple docstring"""




import argparse
import os
import re
import zipfile

import torch

from transformers import MegatronBertConfig



def 				__a       (			_lowercase							, _lowercase							, _lowercase=0						):







					"""simple docstring"""





					if name is None:
										lowerCamelCase__		:   Union[str, Any]  				=					None
					else:
										lowerCamelCase__		:   List[str]  				=					'''.''' * max(0							, spaces - 2						) + '''# {:''' + str(50 - spaces						) + '''s}'''
										lowerCamelCase__		:   Union[str, Any]  				=					fmt.format(lowerCamelCase_						)

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



def 				__a       (			_lowercase							, _lowercase							, _lowercase							, _lowercase							, _lowercase						):







					"""simple docstring"""





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



def 				__a       (			_lowercase							, _lowercase							, _lowercase						):







					"""simple docstring"""





					lowerCamelCase__		:   Tuple  				=					{}

					# old versions did not store training args
					lowerCamelCase__		:   Optional[Any]  				=					input_state_dict.get('''args'''							, lowerCamelCase_						)
					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))

										lowerCamelCase__		:   Dict  				=					ds_args.tokenizer_type
										lowerCamelCase__		:   Union[str, Any]  				=					ds_args.padded_vocab_size
										lowerCamelCase__		:   Optional[int]  				=					ds_args.max_position_embeddings
										lowerCamelCase__		:   Tuple  				=					ds_args.hidden_size
										lowerCamelCase__		:   List[Any]  				=					ds_args.num_layers
										lowerCamelCase__		:   Any  				=					ds_args.num_attention_heads
										lowerCamelCase__		:   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.
					lowerCamelCase__		:   int  				=					config.num_attention_heads
					# The hidden_size per head.
					lowerCamelCase__		:   List[str]  				=					config.hidden_size // heads
					# Megatron-LM checkpoint version
					if "checkpoint_version" in input_state_dict.keys():
										lowerCamelCase__		:   Optional[Any]  				=					input_state_dict['''checkpoint_version''']
					else:
										lowerCamelCase__		:   Dict  				=					0.0

					# The model.
					lowerCamelCase__		:   Tuple  				=					input_state_dict['''model''']
					# The language model.
					lowerCamelCase__		:   Optional[int]  				=					model['''language_model''']
					# The embeddings.
					lowerCamelCase__		:   int  				=					lm['''embedding''']

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

					# The position embeddings.
					lowerCamelCase__		:   List[str]  				=					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.
					lowerCamelCase__		:   Optional[Any]  				=					pos_embeddings

					# The token-type embeddings.
					lowerCamelCase__		:   Optional[Any]  				=					embeddings['''tokentype_embeddings''']['''weight''']
					# Store the position embeddings.
					lowerCamelCase__		:   Dict  				=					tokentype_embeddings

					# The transformer.
					lowerCamelCase__		:   str  				=					lm['''transformer'''] if '''transformer''' in lm.keys() else lm['''encoder''']

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

					# The simple map of names for "automated" rules.
					lowerCamelCase__		:   Dict  				=					{
					    '''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.
					lowerCamelCase__		:   int  				=					None

					# Extract the layers.
					for key, val in transformer.items():
										# Match the name.
										lowerCamelCase__		:   int  				=					layer_re.match(lowerCamelCase_						)

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

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

										# The name of the layer.
										lowerCamelCase__		:   List[Any]  				=					f"""bert.encoder.layer.{layer_idx}"""

										# For layernorm(s), simply store the layer norm.
										if op_name.endswith('''layernorm'''						):
															lowerCamelCase__		:   Tuple  				=					'''attention.ln''' if op_name.startswith('''input'''						) else '''ln'''
															lowerCamelCase__		:   List[Any]  				=					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, ""

															lowerCamelCase__		:   Any  				=					fix_query_key_value_ordering(lowerCamelCase_							, lowerCamelCase_							, 3							, lowerCamelCase_							, lowerCamelCase_						)
															# Store the tensor as we need the bias as well to interleave QKV and biases.
															lowerCamelCase__		:   List[str]  				=					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.
															lowerCamelCase__		:   Optional[Any]  				=					attention_qkv_weight[0 * config.hidden_size : 1 * config.hidden_size, :]
															lowerCamelCase__		:   List[Any]  				=					attention_qkv_weight[1 * config.hidden_size : 2 * config.hidden_size, :]
															lowerCamelCase__		:   Any  				=					attention_qkv_weight[2 * config.hidden_size : 3 * config.hidden_size, :]

															lowerCamelCase__		:   str  				=					fix_query_key_value_ordering(lowerCamelCase_							, lowerCamelCase_							, 3							, lowerCamelCase_							, lowerCamelCase_						)
															# Split the bias.
															lowerCamelCase__		:   List[Any]  				=					out_val[0 * config.hidden_size : 1 * config.hidden_size]
															lowerCamelCase__		:   str  				=					out_val[1 * config.hidden_size : 2 * config.hidden_size]
															lowerCamelCase__		:   Tuple  				=					out_val[2 * config.hidden_size : 3 * config.hidden_size]

															# Store.
															lowerCamelCase__		:   Dict  				=					q
															lowerCamelCase__		:   Union[str, Any]  				=					q_bias
															lowerCamelCase__		:   str  				=					k
															lowerCamelCase__		:   Optional[int]  				=					k_bias
															lowerCamelCase__		:   Any  				=					v
															lowerCamelCase__		:   int  				=					v_bias

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

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

    # The final layernorm.
					lowerCamelCase__		:   int  				=					transformer['''final_layernorm.weight''']
					lowerCamelCase__		:   Dict  				=					transformer['''final_layernorm.bias''']

					# The pooler.
					lowerCamelCase__		:   Union[str, Any]  				=					lm['''pooler''']

					# Store the matrix and the bias.
					lowerCamelCase__		:   Union[str, Any]  				=					pooler['''dense.weight''']
					lowerCamelCase__		:   Union[str, Any]  				=					pooler['''dense.bias''']

					# The LM head from Megatron (for RACE).
					lowerCamelCase__		:   Dict  				=					model['''lm_head''']

					# The transform matrix.
					lowerCamelCase__		:   Optional[Any]  				=					lm_head['''dense.weight''']
					lowerCamelCase__		:   Optional[int]  				=					lm_head['''dense.bias''']

					# The transform LN.
					lowerCamelCase__		:   Any  				=					lm_head['''layernorm.weight''']
					lowerCamelCase__		:   str  				=					lm_head['''layernorm.bias''']

					# For the decoder, we replicate the weights.
					lowerCamelCase__		:   Union[str, Any]  				=					word_embeddings
					lowerCamelCase__		:   Dict  				=					lm_head['''bias''']

					# The classifier from Megatron (for MLNI).
					lowerCamelCase__		:   str  				=					model['''binary_head''']

					# Store the classifier.
					lowerCamelCase__		:   Dict  				=					binary_head['''weight''']
					lowerCamelCase__		:   List[str]  				=					binary_head['''bias''']

					# It should be done!
					return output_state_dict



def 				__a       (			):







					"""simple docstring"""





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

					# Extract the basename.
					lowerCamelCase__		:   Any  				=					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:
																				lowerCamelCase__		:   Tuple  				=					torch.load(lowerCamelCase_							, map_location='''cpu'''						)
					else:
										lowerCamelCase__		:   List[str]  				=					torch.load(args.path_to_checkpoint							, map_location='''cpu'''						)

					if args.config_file == "":
										# Default config of megatron-bert 345m
										lowerCamelCase__		:   Tuple  				=					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
										lowerCamelCase__		:   Any  				=					input_state_dict['''model''']['''lm_head''']['''bias'''].numel()
					else:
										lowerCamelCase__		:   Tuple  				=					MegatronBertConfig.from_json_file(args.config_file						)

					# Convert.
					print('''Converting'''						)
					lowerCamelCase__		:   int  				=					convert_megatron_checkpoint(lowerCamelCase_							, lowerCamelCase_							, lowerCamelCase_						)

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

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

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


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

if __name__ == "__main__":
					main()

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










"""simple docstring"""






from __future__ import annotations

from collections.abc import Generator


def __lowercase  (   lowerCamelCase_	:   int	):
				if not isinstance(lowerCamelCase_    ,       lowerCamelCase_	) or n < 1:
								raise Exception("Sequence only defined for positive integers"	)

				yield n
				while n != 1:
								if n % 2 == 0:
												n //= 2
								else:
												SCREAMING_SNAKE_CASE__  				=					3 * n + 1
								yield n


def __lowercase  (   ):
				SCREAMING_SNAKE_CASE__  				=					43
				SCREAMING_SNAKE_CASE__  				=					tuple(collatz_sequence(lowerCamelCase_	)	)
				print(lowerCamelCase_	)
				print(F'''Collatz sequence from {n} took {len(lowerCamelCase_	)} steps.'''	)


if __name__ == "__main__":
	main()
