






'''simple docstring'''


import argparse
import os
from os.path import isfile

import torch

from transformers import GPTaConfig






def   lowerCAmelCase__			(					SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__=0		):
 # Format the message.
 if name is None:
  __a    :	Optional[int]									=						None
 else:
  __a    :	List[Any]									=						'.' * max(0       ,		spaces - 2		) + '# {:' + str(50 - spaces		) + 's}'
  __a    :	List[Any]									=						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   lowerCAmelCase__			(					SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__		):
 # Permutes layout of param tensor to [num_splits * num_heads * hidden_size, :]
 # for compatibility with later versions of NVIDIA Megatron-LM.
 # The inverse operation is performed inside Megatron-LM to read checkpoints:
 # https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/checkpointing.py#L209
 # If param is the weight tensor of the self-attention block, the returned tensor
 # will have to be transposed one more time to be read by HuggingFace GPT2.
 __a    :	Dict									=						param.size()
 # other versions store [num_heads * num_splits * hidden_size, :]
 __a    :	Union[str, Any]									=						(num_heads, num_splits, hidden_size) + input_shape[1:]
 __a    :	Tuple									=						param.view(*SCREAMING_SNAKE_CASE__		)
 __a    :	Union[str, Any]									=						param.transpose(0       ,		1		).contiguous()
 __a    :	Tuple									=						param.view(*SCREAMING_SNAKE_CASE__		)
 return param






def   lowerCAmelCase__			(					SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__		):
 __a    :	Any									=						config.n_positions
 __a    :	List[str]									=						config.n_layer
 __a    :	int									=						config.vocab_size
 __a    :	Tuple									=						config.n_head
 __a    :	str									=						config.n_embd // config.n_head

 __a    :	Dict									=						sd_megatron['model.language_model.embedding.word_embeddings.weight'][:vocab_size, :]
 __a    :	Dict									=						{
     'transformer.wte.weight': word_embeddings,
     'transformer.wpe.weight': sd_megatron['model.language_model.embedding.position_embeddings.weight'],
     'transformer.ln_f.weight': sd_megatron['model.language_model.encoder.final_layernorm.weight'],
     'transformer.ln_f.bias': sd_megatron['model.language_model.encoder.final_layernorm.bias'],
 }

 __a    :	Optional[int]									=						'model.language_model.encoder.layers.'
 for i in range(SCREAMING_SNAKE_CASE__		):
  __a    :	Union[str, Any]									=						torch.tril(torch.ones((n_positions, n_positions)       ,		dtype=torch.bool		)		)
  __a    :	str									=						causal_mask.view(1       ,		1       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__		)
  __a    :	Union[str, Any]									=						causal_mask
  __a    :	Optional[int]									=						torch.tensor(-1E4       ,		dtype=torch.bfloataa		)

  __a    :	int									=						sd_megatron[f'''{pf}{i}.input_layernorm.weight''']
  __a    :	str									=						sd_megatron[f'''{pf}{i}.input_layernorm.bias''']

  __a    :	Union[str, Any]									=						sd_megatron[f'''{pf}{i}.self_attention.query_key_value.weight''']
  __a    :	int									=						fix_query_key_value_ordering(SCREAMING_SNAKE_CASE__       ,		3       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__		)
  __a    :	int									=						vala.transpose(0       ,		1		).contiguous()

  __a    :	Any									=						sd_megatron[f'''{pf}{i}.self_attention.query_key_value.bias''']
  __a    :	str									=						fix_query_key_value_ordering(SCREAMING_SNAKE_CASE__       ,		3       ,		SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__		)
  __a    :	Optional[Any]									=						vala

  __a    :	int									=						sd_megatron[f'''{pf}{i}.self_attention.dense.weight'''].transpose(
      0       ,		1		)
  __a    :	str									=						sd_megatron[f'''{pf}{i}.self_attention.dense.bias''']
  __a    :	int									=						sd_megatron[f'''{pf}{i}.post_attention_layernorm.weight''']
  __a    :	Dict									=						sd_megatron[f'''{pf}{i}.post_attention_layernorm.bias''']
  __a    :	str									=						sd_megatron[f'''{pf}{i}.mlp.dense_h_to_4h.weight'''].transpose(0       ,		1		)
  __a    :	Optional[Any]									=						sd_megatron[f'''{pf}{i}.mlp.dense_h_to_4h.bias''']
  __a    :	List[Any]									=						sd_megatron[f'''{pf}{i}.mlp.dense_4h_to_h.weight'''].transpose(
      0       ,		1		)
  __a    :	Dict									=						sd_megatron[f'''{pf}{i}.mlp.dense_4h_to_h.bias''']

 # For LM head, transformers' wants the matrix to weight embeddings.
 __a    :	Any									=						word_embeddings

 return sd_hf






def   lowerCAmelCase__			(					SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__		):
 __a    :	int									=						64000
 __a    :	Optional[int]									=						config_megatron['encoder_seq_length']
 __a    :	Union[str, Any]									=						config_megatron['hidden_size']
 __a    :	int									=						config_megatron['num_layers']
 __a    :	Tuple									=						config_megatron['num_attention_heads']
 __a    :	List[Any]									=						config_megatron['ffn_hidden_size']
 __a    :	List[str]									=						'gelu'
 __a    :	Dict									=						0.1
 __a    :	List[Any]									=						0.1
 __a    :	Dict									=						0.1
 __a    :	str									=						config_megatron['layernorm_epsilon']  # 1e-5
 __a    :	List[Any]									=						config_megatron['init_method_std']  # 0.02
 __a    :	Tuple									=						config_megatron['apply_query_key_layer_scaling']  # True
 __a    :	Any									=						True
 __a    :	List[Any]									=						True

 # This identifies the 6.7B (7B) model which uses a different tokenizer
 if config_megatron["hidden_size"] == 4096:
  __a    :	Optional[Any]									=						1  # <|endoftext|>
  __a    :	str									=						1  # <|endoftext|>
  __a    :	Any									=						0  # <unk>
 else:
  __a    :	Dict									=						2  # <s>
  __a    :	Any									=						3  # <|endoftext|>
  __a    :	Dict									=						0  # <pad>

 return config_hf






def   lowerCAmelCase__			(					SCREAMING_SNAKE_CASE__		):
 print(SCREAMING_SNAKE_CASE__		)

 __a    :	Dict									=						args.checkpoint_path
 __a    :	Tuple									=						args.save_path
 if isfile(SCREAMING_SNAKE_CASE__		):
  raise FileNotFoundError(f'''ERROR! could not find file {checkpoint_path}'''		)

 # Load the model.
 __a    :	Any									=						torch.load(SCREAMING_SNAKE_CASE__       ,		map_location='cpu'		)

 # Load the config.
 __a    :	Optional[int]									=						checkpoint['hyper_parameters']['cfg']
 __a    :	List[str]									=						GPTaConfig()
 __a    :	str									=						copy_config(config_hf=SCREAMING_SNAKE_CASE__       ,		config_megatron=SCREAMING_SNAKE_CASE__		)
 __a    :	Optional[Any]									=						['GPT2LMHeadModel']

 __a    :	Optional[int]									=						checkpoint['state_dict']

 # Convert.
 print('Converting'		)
 __a    :	Dict									=						convert_megatron_checkpoint(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__		)

 __a    :	List[str]									=						'GPTSw3Tokenizer'

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

 # Store the state_dict to file.
 __a    :	Tuple									=						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__":
  SCREAMING_SNAKE_CASE_				      =							argparse.ArgumentParser()
  parser.add_argument(
      "--checkpoint_path",
      type=str,
      required=True,
      help="e.g. megatron_gpt--val_loss=2.42-step=38000-consumed_samples=54720000",
  )
  parser.add_argument("--save_path", type=str, required=True, help="e.g. /home/user/gpt-sw3/hf")
  parser.add_argument("--print-checkpoint-structure", action="store_true")
  SCREAMING_SNAKE_CASE_				      =							parser.parse_args()
  main(_args)












'''simple docstring'''


import math
from timeit import timeit






def   lowerCAmelCase__			(					SCREAMING_SNAKE_CASE__		):
 __a    :	Any									=						0
 __a    :	List[Any]									=						abs(SCREAMING_SNAKE_CASE__		)
 while True:
  __a    :	int									=						n // 10
  digits += 1
  if n == 0:
   break
 return digits






def   lowerCAmelCase__			(					SCREAMING_SNAKE_CASE__		):
 return 1 if n == 0 else math.floor(math.log(abs(SCREAMING_SNAKE_CASE__		)       ,		10		) + 1		)






def   lowerCAmelCase__			(					SCREAMING_SNAKE_CASE__		):
 return len(str(abs(SCREAMING_SNAKE_CASE__		)		)		)






def   lowerCAmelCase__			(					):
 from collections.abc import Callable

 def benchmark_a_function(SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__		) -> None:
  __a    :	Tuple									=						f'''{func.__name__}({value})'''
  __a    :	List[Any]									=						timeit(f'''__main__.{call}'''       ,		setup='import __main__'		)
  print(f'''{call}: {func(SCREAMING_SNAKE_CASE__		)} -- {timing} seconds'''		)

 for value in (262144, 1125899906842624, 1267650600228229401496703205376):
  for func in (num_digits, num_digits_fast, num_digits_faster):
   benchmark_a_function(SCREAMING_SNAKE_CASE__       ,		SCREAMING_SNAKE_CASE__		)
  print()


if __name__ == "__main__":
  import doctest

  doctest.testmod()
  benchmark()




