






import argparse
import os
import re
import zipfile

import torch

from transformers import MegatronBertConfig






def 				A	(			a_				,a_				,a_=0   )	->		Any:


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

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






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






def 				A	(			a_				,a_				,a_   )	->		List[Any]:
					__UpperCamelCase :   Optional[int]									={}

					# old versions did not store training args
					__UpperCamelCase :   Tuple									=input_state_dict.get('args'				,_SCREAMING_SNAKE_CASE   )
					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))

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

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

					# The model.
					__UpperCamelCase :   List[Any]									=input_state_dict['model']
					# The language model.
					__UpperCamelCase :   Tuple									=model['language_model']
					# The embeddings.
					__UpperCamelCase :   int									=lm['embedding']

					# The word embeddings.
					__UpperCamelCase :   str									=embeddings['word_embeddings']['weight']
					# Truncate the embedding table to vocab_size rows.
					__UpperCamelCase :   str									=word_embeddings[: config.vocab_size, :]
					# Store the word embeddings.
					__UpperCamelCase :   Dict									=word_embeddings

					# The position embeddings.
					__UpperCamelCase :   Union[str, 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.
					__UpperCamelCase :   Optional[int]									=pos_embeddings

					# The token-type embeddings.
					__UpperCamelCase :   Union[str, Any]									=embeddings['tokentype_embeddings']['weight']
					# Store the position embeddings.
					__UpperCamelCase :   List[Any]									=tokentype_embeddings

					# The transformer.
					__UpperCamelCase :   List[Any]									=lm['transformer'] if 'transformer' in lm.keys() else lm['encoder']

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

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

					# Extract the layers.
					for key, val in transformer.items():
										# Match the name.
										__UpperCamelCase :   Optional[int]									=layer_re.match(_SCREAMING_SNAKE_CASE   )

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

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

										# The name of the layer.
										__UpperCamelCase :   Optional[int]									=F'bert.encoder.layer.{layer_idx}'

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

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

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

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

															# Clear the stored tensor.
															__UpperCamelCase :   Tuple									=None

										# Copy weights and biases as is.
										elif weight_or_bias in ["weight", "bias"]:
															__UpperCamelCase :   Optional[int]									=megatron_to_transformers[op_name]
															__UpperCamelCase :   Tuple									=val

    # The final layernorm.
					__UpperCamelCase :   List[str]									=transformer['final_layernorm.weight']
					__UpperCamelCase :   Optional[int]									=transformer['final_layernorm.bias']

					# The pooler.
					__UpperCamelCase :   List[str]									=lm['pooler']

					# Store the matrix and the bias.
					__UpperCamelCase :   str									=pooler['dense.weight']
					__UpperCamelCase :   Optional[Any]									=pooler['dense.bias']

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

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

					# The transform LN.
					__UpperCamelCase :   int									=lm_head['layernorm.weight']
					__UpperCamelCase :   List[Any]									=lm_head['layernorm.bias']

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

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

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

					# It should be done!
					return output_state_dict






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

					# Extract the basename.
					__UpperCamelCase :   str									=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:
																				__UpperCamelCase :   int									=torch.load(_SCREAMING_SNAKE_CASE				,map_location='cpu'   )
					else:
										__UpperCamelCase :   Optional[int]									=torch.load(args.path_to_checkpoint				,map_location='cpu'   )

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

					# Convert.
					print('Converting'   )
					__UpperCamelCase :   Optional[Any]									=convert_megatron_checkpoint(_SCREAMING_SNAKE_CASE				,_SCREAMING_SNAKE_CASE				,_SCREAMING_SNAKE_CASE   )

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

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

					# Store the state_dict to file.
					__UpperCamelCase :   List[Any]									=os.path.join(_SCREAMING_SNAKE_CASE				,'pytorch_model.bin'   )
					print(F'Saving checkpoint to \"{output_checkpoint_file}\"'   )
					torch.save(_SCREAMING_SNAKE_CASE				,_SCREAMING_SNAKE_CASE   )


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

if __name__ == "__main__":
							main()

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








"""simple docstring"""





def    a__       (       _SCREAMING_SNAKE_CASE	,						_SCREAMING_SNAKE_CASE     ):




		"""simple docstring"""


		UpperCamelCase =						sorted(_SCREAMING_SNAKE_CASE	,						key=lambda _SCREAMING_SNAKE_CASE     : value[2]	,						reverse=_SCREAMING_SNAKE_CASE     )

		# Create a list of size equal to the maximum deadline
		# and initialize it with -1
		UpperCamelCase =						max(_SCREAMING_SNAKE_CASE	,						key=lambda _SCREAMING_SNAKE_CASE     : value[1]     )[1]
		UpperCamelCase =						[-1] * max_deadline

		# Finding the maximum profit and the count of jobs
		UpperCamelCase =						0
		UpperCamelCase =						0
		for job in jobs:
				# Find a free time slot for this job
				# (Note that we start from the last possible slot)
				for i in range(job[1] - 1	,						-1	,						-1     ):
						if time_slots[i] == -1:
								UpperCamelCase =						job[0]
								count += 1
								max_profit += job[2]
								break
		return [count, max_profit]


if __name__ == "__main__":
						import doctest

						doctest.testmod()






