






import argparse
import os
from os.path import isfile

import torch

from transformers import GPTaConfig
def 							UpperCAmelCase   ( _lowercase,   _lowercase,   _lowercase=0   ):


    '''simple docstring'''



    if name is None:
        _lowercase     			=						None
    else:
        _lowercase     			=						'.' * max(0,   spaces - 2   ) + '# {:' + str(50 - spaces   ) + 's}'
        _lowercase     			=						fmt.format(_lowercase   )

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


    '''simple docstring'''



    _lowercase     			=						param.size()
    # other versions store [num_heads * num_splits * hidden_size, :]
    _lowercase     			=						(num_heads, num_splits, hidden_size) + input_shape[1:]
    _lowercase     			=						param.view(*_lowercase   )
    _lowercase     			=						param.transpose(0,   1   ).contiguous()
    _lowercase     			=						param.view(*_lowercase   )
    return param
def 							UpperCAmelCase   ( _lowercase,   _lowercase   ):


    '''simple docstring'''



    _lowercase     			=						config.n_positions
    _lowercase     			=						config.n_layer
    _lowercase     			=						config.vocab_size
    _lowercase     			=						config.n_head
    _lowercase     			=						config.n_embd // config.n_head

    _lowercase     			=						sd_megatron['model.language_model.embedding.word_embeddings.weight'][:vocab_size, :]
    _lowercase     			=						{
        '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'],
    }

    _lowercase     			=						'model.language_model.encoder.layers.'
    for i in range(_lowercase   ):
        _lowercase     			=						torch.tril(torch.ones((n_positions, n_positions),   dtype=torch.bool   )   )
        _lowercase     			=						causal_mask.view(1,   1,   _lowercase,   _lowercase   )
        _lowercase     			=						causal_mask
        _lowercase     			=						torch.tensor(-1e4,   dtype=torch.bfloataa   )

        _lowercase     			=						sd_megatron[f'''{pf}{i}.input_layernorm.weight''']
        _lowercase     			=						sd_megatron[f'''{pf}{i}.input_layernorm.bias''']

        _lowercase     			=						sd_megatron[f'''{pf}{i}.self_attention.query_key_value.weight''']
        _lowercase     			=						fix_query_key_value_ordering(_lowercase,   3,   _lowercase,   _lowercase   )
        _lowercase     			=						vala.transpose(0,   1   ).contiguous()

        _lowercase     			=						sd_megatron[f'''{pf}{i}.self_attention.query_key_value.bias''']
        _lowercase     			=						fix_query_key_value_ordering(_lowercase,   3,   _lowercase,   _lowercase   )
        _lowercase     			=						vala

        _lowercase     			=						sd_megatron[f'''{pf}{i}.self_attention.dense.weight'''].transpose(
            0,   1   )
        _lowercase     			=						sd_megatron[f'''{pf}{i}.self_attention.dense.bias''']
        _lowercase     			=						sd_megatron[f'''{pf}{i}.post_attention_layernorm.weight''']
        _lowercase     			=						sd_megatron[f'''{pf}{i}.post_attention_layernorm.bias''']
        _lowercase     			=						sd_megatron[f'''{pf}{i}.mlp.dense_h_to_4h.weight'''].transpose(0,   1   )
        _lowercase     			=						sd_megatron[f'''{pf}{i}.mlp.dense_h_to_4h.bias''']
        _lowercase     			=						sd_megatron[f'''{pf}{i}.mlp.dense_4h_to_h.weight'''].transpose(
            0,   1   )
        _lowercase     			=						sd_megatron[f'''{pf}{i}.mlp.dense_4h_to_h.bias''']

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

    return sd_hf
def 							UpperCAmelCase   ( _lowercase,   _lowercase   ):


    '''simple docstring'''



    _lowercase     			=						64000
    _lowercase     			=						config_megatron['encoder_seq_length']
    _lowercase     			=						config_megatron['hidden_size']
    _lowercase     			=						config_megatron['num_layers']
    _lowercase     			=						config_megatron['num_attention_heads']
    _lowercase     			=						config_megatron['ffn_hidden_size']
    _lowercase     			=						'gelu'
    _lowercase     			=						0.1
    _lowercase     			=						0.1
    _lowercase     			=						0.1
    _lowercase     			=						config_megatron['layernorm_epsilon']  # 1e-5
    _lowercase     			=						config_megatron['init_method_std']  # 0.02
    _lowercase     			=						config_megatron['apply_query_key_layer_scaling']  # True
    _lowercase     			=						True
    _lowercase     			=						True

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

    return config_hf
def 							UpperCAmelCase   ( _lowercase   ):


    '''simple docstring'''



    print(_lowercase   )

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

    # Load the model.
    _lowercase     			=						torch.load(_lowercase,   map_location='cpu'   )

    # Load the config.
    _lowercase     			=						checkpoint['hyper_parameters']['cfg']
    _lowercase     			=						GPTaConfig()
    _lowercase     			=						copy_config(config_hf=_lowercase,   config_megatron=_lowercase   )
    _lowercase     			=						['GPT2LMHeadModel']

    _lowercase     			=						checkpoint['state_dict']

    # Convert.
    print('Converting'   )
    _lowercase     			=						convert_megatron_checkpoint(_lowercase,   _lowercase   )

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

    _lowercase     			=						'GPTSw3Tokenizer'

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

    # Store the state_dict to file.
    _lowercase     			=						os.path.join(_lowercase,   'pytorch_model.bin'   )
    print(f'''Saving checkpoint to "{output_checkpoint_file}"'''   )
    torch.save(_lowercase,   _lowercase   )


if __name__ == "__main__":
   lowerCamelCase					    =	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''')
   lowerCamelCase					    =	parser.parse_args()
   main(_args)








from __future__ import annotations

from enum import Enum, unique
from typing import TypeVar

# Create a generic variable that can be 'Enum', or any subclass.
lowerCamelCase					    =	TypeVar('''T''', bound='''Enum''')

@unique
class        snake_case_				(							lowercase_   ):







   """simple docstring"""



   __lowerCAmelCase  =    80
   __lowerCAmelCase  =    70
   __lowerCAmelCase  =    60
   __lowerCAmelCase  =    50
   __lowerCAmelCase  =    40
   __lowerCAmelCase  =    30
   __lowerCAmelCase  =    20
   __lowerCAmelCase  =    10






@unique
class        snake_case_				(							lowercase_   ):







   """simple docstring"""



   __lowerCAmelCase  =    24
   __lowerCAmelCase  =    21
   __lowerCAmelCase  =    18
   __lowerCAmelCase  =    15
   __lowerCAmelCase  =    12
   __lowerCAmelCase  =    9
   __lowerCAmelCase  =    6
   __lowerCAmelCase  =    3
   __lowerCAmelCase  =    2
   __lowerCAmelCase  =    1
   __lowerCAmelCase  =    -1
   __lowerCAmelCase  =    -2
   __lowerCAmelCase  =    -3
   __lowerCAmelCase  =    -6
   __lowerCAmelCase  =    -9
   __lowerCAmelCase  =    -12
   __lowerCAmelCase  =    -15
   __lowerCAmelCase  =    -18
   __lowerCAmelCase  =    -21
   __lowerCAmelCase  =    -24

   @classmethod
   def       SCREAMING_SNAKE_CASE__					(     cls:						type[T]						)	->		dict:


       """simple docstring"""



       return {unit.name: unit.value for unit in cls if unit.value > 0}

   @classmethod
   def       SCREAMING_SNAKE_CASE__					(     cls:						type[T]						)	->		dict:


       """simple docstring"""



       return {unit.name: unit.value for unit in cls if unit.value < 0}






def 							UpperCAmelCase   ( _lowercase   ):


    '''simple docstring'''



    _lowercase     			=						SIUnit.get_positive() if value > 0 else SIUnit.get_negative()
    for name_prefix, value_prefix in prefixes.items():
        _lowercase     			=						value / (10**value_prefix)
        if numerical_part > 1:
            return f'''{numerical_part!s} {name_prefix}'''
    return str(_lowercase   )
def 							UpperCAmelCase   ( _lowercase   ):


    '''simple docstring'''



    for prefix in BinaryUnit:
        _lowercase     			=						value / (2**prefix.value)
        if numerical_part > 1:
            return f'''{numerical_part!s} {prefix.name}'''
    return str(_lowercase   )


if __name__ == "__main__":
   import doctest

   doctest.testmod()
