






"""simple docstring"""



import argparse
import os
from os.path import isfile

import torch

from transformers import GPTaConfig
def 						_SCREAMING_SNAKE_CASE			(   __snake_case      :  Optional[Any]		, __snake_case      :  int		, __snake_case      :  Optional[Any]=0   ):





  '''simple docstring'''





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

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





  '''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(*__snake_case   )
  lowercase							   =	param.transpose(0		, 1   ).contiguous()
  lowercase							   =	param.view(*__snake_case   )
  return param
def 						_SCREAMING_SNAKE_CASE			(   __snake_case      :  Tuple		, __snake_case      :  Union[str, Any]   ):





  '''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(__snake_case   ):
    lowercase							   =	torch.tril(torch.ones((n_positions, n_positions)		, dtype=torch.bool   )   )
    lowercase							   =	causal_mask.view(1		, 1		, __snake_case		, __snake_case   )
    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(__snake_case		, 3		, __snake_case		, __snake_case   )
    lowercase							   =	vala.transpose(0		, 1   ).contiguous()

    lowercase							   =	sd_megatron[f'{pf}{i}.self_attention.query_key_value.bias']
    lowercase							   =	fix_query_key_value_ordering(__snake_case		, 3		, __snake_case		, __snake_case   )
    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 						_SCREAMING_SNAKE_CASE			(   __snake_case      :  List[Any]		, __snake_case      :  Any   ):





  '''simple docstring'''





  lowercase							   =	6_40_00
  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"] == 40_96:
    lowercase							   =	1  # <|endoftext|>
    lowercase							   =	1  # <|endoftext|>
    lowercase							   =	0  # <unk>
  else:
    lowercase							   =	2  # <s>
    lowercase							   =	3  # <|endoftext|>
    lowercase							   =	0  # <pad>

  return config_hf
def 						_SCREAMING_SNAKE_CASE			(   __snake_case      :  Tuple   ):





  '''simple docstring'''





  print(__snake_case   )

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

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

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

  lowercase							   =	checkpoint['state_dict']

  # Convert.
  print('Converting'   )
  lowercase							   =	convert_megatron_checkpoint(__snake_case		, __snake_case   )

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

  lowercase							   =	'GPTSw3Tokenizer'

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

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


if __name__ == "__main__":
    _UpperCamelCase		:  Tuple						=		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')
    _UpperCamelCase		:  Optional[int]						=		parser.parse_args()
    main(_args)










"""simple docstring"""



import json
import os
from functools import lru_cache
from typing import TYPE_CHECKING, List, Optional, Tuple

import regex as re

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...utils import logging


if TYPE_CHECKING:
    from transformers.pipelines.conversational import Conversation

_UpperCamelCase		:  Union[str, Any]						=		logging.get_logger(__name__)

_UpperCamelCase		:  Tuple						=		{
    'vocab_file': 'vocab.json',
    'merges_file': 'merges.txt',
}

_UpperCamelCase		:  Any						=		{
    'vocab_file': {
        'gpt2': 'https://huggingface.co/gpt2/resolve/main/vocab.json',
        'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/vocab.json',
        'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/vocab.json',
        'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/vocab.json',
        'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/vocab.json',
    },
    'merges_file': {
        'gpt2': 'https://huggingface.co/gpt2/resolve/main/merges.txt',
        'gpt2-medium': 'https://huggingface.co/gpt2-medium/resolve/main/merges.txt',
        'gpt2-large': 'https://huggingface.co/gpt2-large/resolve/main/merges.txt',
        'gpt2-xl': 'https://huggingface.co/gpt2-xl/resolve/main/merges.txt',
        'distilgpt2': 'https://huggingface.co/distilgpt2/resolve/main/merges.txt',
    },
}

_UpperCamelCase		:  str						=		{
    'gpt2': 1_0_2_4,
    'gpt2-medium': 1_0_2_4,
    'gpt2-large': 1_0_2_4,
    'gpt2-xl': 1_0_2_4,
    'distilgpt2': 1_0_2_4,
}
@lru_cache()
def 						_SCREAMING_SNAKE_CASE			(   ):





  '''simple docstring'''





  lowercase							   =	(
      list(range(ord('!'   )		, ord('~'   ) + 1   )   ) + list(range(ord('¡'   )		, ord('¬'   ) + 1   )   ) + list(range(ord('®'   )		, ord('ÿ'   ) + 1   )   )
  )
  lowercase							   =	bs[:]
  lowercase							   =	0
  for b in range(2**8   ):
    if b not in bs:
      bs.append(__snake_case   )
      cs.append(2**8 + n   )
      n += 1
  lowercase							   =	[chr(__snake_case   ) for n in cs]
  return dict(zip(__snake_case		, __snake_case   )   )
def 						_SCREAMING_SNAKE_CASE			(   __snake_case      :  int   ):





  '''simple docstring'''





  lowercase							   =	set()
  lowercase							   =	word[0]
  for char in word[1:]:
    pairs.add((prev_char, char)   )
    lowercase							   =	char
  return pairs



class 	a					(       a_     ):
    UpperCAmelCase_			:					int     					=VOCAB_FILES_NAMES
    UpperCAmelCase_			:					List[str]     					=PRETRAINED_VOCAB_FILES_MAP
    UpperCAmelCase_			:					Tuple     					=PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    UpperCAmelCase_			:					Any     					=["input_ids", "attention_mask"]







    def __init__(      self							,		_lowerCamelCase							,		_lowerCamelCase							,		_lowerCamelCase="replace"							,		_lowerCamelCase="<|endoftext|>"							,		_lowerCamelCase="<|endoftext|>"							,		_lowerCamelCase="<|endoftext|>"							,		_lowerCamelCase=None							,		_lowerCamelCase=False							,		_lowerCamelCase=False							,		**_lowerCamelCase							,		):
      lowercase							   =	AddedToken(_lowerCamelCase							,		lstrip=_lowerCamelCase							,		rstrip=_lowerCamelCase	) if isinstance(_lowerCamelCase							,		_lowerCamelCase	) else bos_token
      lowercase							   =	AddedToken(_lowerCamelCase							,		lstrip=_lowerCamelCase							,		rstrip=_lowerCamelCase	) if isinstance(_lowerCamelCase							,		_lowerCamelCase	) else eos_token
      lowercase							   =	AddedToken(_lowerCamelCase							,		lstrip=_lowerCamelCase							,		rstrip=_lowerCamelCase	) if isinstance(_lowerCamelCase							,		_lowerCamelCase	) else unk_token
      lowercase							   =	AddedToken(_lowerCamelCase							,		lstrip=_lowerCamelCase							,		rstrip=_lowerCamelCase	) if isinstance(_lowerCamelCase							,		_lowerCamelCase	) else pad_token
      super().__init__(
          errors=_lowerCamelCase							,		unk_token=_lowerCamelCase							,		bos_token=_lowerCamelCase							,		eos_token=_lowerCamelCase							,		pad_token=_lowerCamelCase							,		add_prefix_space=_lowerCamelCase							,		add_bos_token=_lowerCamelCase							,		**_lowerCamelCase							,		)
      lowercase							   =	add_bos_token

      with open(_lowerCamelCase							,		encoding='utf-8'	) as vocab_handle:
        lowercase							   =	json.load(_lowerCamelCase	)
      lowercase							   =	{v: k for k, v in self.encoder.items()}
      lowercase							   =	errors  # how to handle errors in decoding
      lowercase							   =	bytes_to_unicode()
      lowercase							   =	{v: k for k, v in self.byte_encoder.items()}
      with open(_lowerCamelCase							,		encoding='utf-8'	) as merges_handle:
        lowercase							   =	merges_handle.read().split('\n'	)[1:-1]
      lowercase							   =	[tuple(merge.split()	) for merge in bpe_merges]
      lowercase							   =	dict(zip(_lowerCamelCase							,		range(len(_lowerCamelCase	)	)	)	)
      lowercase							   =	{}
      lowercase							   =	add_prefix_space

      # Should have added re.IGNORECASE so BPE merges can happen for capitalized versions of contractions
      lowercase							   =	re.compile(R'\'s|\'t|\'re|\'ve|\'m|\'ll|\'d| ?\p{L}+| ?\p{N}+| ?[^\s\p{L}\p{N}]+|\s+(?!\S)|\s+'	)







    @property
    def       UpperCamelCase_				(      self	):
      return len(self.encoder	)







    def       UpperCamelCase_				(      self	):
      return dict(self.encoder							,		**self.added_tokens_encoder	)







    def       UpperCamelCase_				(      self							,		_lowerCamelCase	):
      if token in self.cache:
        return self.cache[token]
      lowercase							   =	tuple(_lowerCamelCase	)
      lowercase							   =	get_pairs(_lowerCamelCase	)

      if not pairs:
        return token

      while True:
        lowercase							   =	min(_lowerCamelCase							,		key=lambda _lowerCamelCase	: self.bpe_ranks.get(_lowerCamelCase							,		float('inf'	)	)	)
        if bigram not in self.bpe_ranks:
          break
        lowercase   ,					lowercase							   =	bigram
        lowercase							   =	[]
        lowercase							   =	0
        while i < len(_lowerCamelCase	):
          try:
            lowercase							   =	word.index(_lowerCamelCase							,		_lowerCamelCase	)
          except ValueError:
            new_word.extend(word[i:]	)
            break
          else:
            new_word.extend(word[i:j]	)
            lowercase							   =	j

          if word[i] == first and i < len(_lowerCamelCase	) - 1 and word[i + 1] == second:
            new_word.append(first + second	)
            i += 2
          else:
            new_word.append(word[i]	)
            i += 1
        lowercase							   =	tuple(_lowerCamelCase	)
        lowercase							   =	new_word
        if len(_lowerCamelCase	) == 1:
          break
        else:
          lowercase							   =	get_pairs(_lowerCamelCase	)
      lowercase							   =	' '.join(_lowerCamelCase	)
      lowercase							   =	word
      return word







    def       UpperCamelCase_				(      self							,		_lowerCamelCase							,		_lowerCamelCase=None	):
      if self.add_bos_token:
        lowercase							   =	[self.bos_token_id]
      else:
        lowercase							   =	[]

      lowercase							   =	bos_token_ids + token_ids_a

      if token_ids_a is None:
        return output

      return output + bos_token_ids + token_ids_a







    def       UpperCamelCase_				(      self							,		_lowerCamelCase							,		_lowerCamelCase = None							,		_lowerCamelCase = False	):
      if already_has_special_tokens:
        return super().get_special_tokens_mask(
            token_ids_a=_lowerCamelCase							,		token_ids_a=_lowerCamelCase							,		already_has_special_tokens=_lowerCamelCase	)

      if not self.add_bos_token:
        return super().get_special_tokens_mask(
            token_ids_a=_lowerCamelCase							,		token_ids_a=_lowerCamelCase							,		already_has_special_tokens=_lowerCamelCase	)

      if token_ids_a is None:
        return [1] + ([0] * len(_lowerCamelCase	))
      return [1] + ([0] * len(_lowerCamelCase	)) + [1] + ([0] * len(_lowerCamelCase	))







    def       UpperCamelCase_				(      self							,		_lowerCamelCase	):
      lowercase							   =	[]
      for token in re.findall(self.pat							,		_lowerCamelCase	):
        lowercase							   =	''.join(
            self.byte_encoder[b] for b in token.encode('utf-8'	)	)  # Maps all our bytes to unicode strings, avoiding control tokens of the BPE (spaces in our case)
        bpe_tokens.extend(bpe_token for bpe_token in self.bpe(_lowerCamelCase	).split(' '	)	)
      return bpe_tokens







    def       UpperCamelCase_				(      self							,		_lowerCamelCase	):
      return self.encoder.get(_lowerCamelCase							,		self.encoder.get(self.unk_token	)	)







    def       UpperCamelCase_				(      self							,		_lowerCamelCase	):
      return self.decoder.get(_lowerCamelCase	)







    def       UpperCamelCase_				(      self							,		_lowerCamelCase	):
      lowercase							   =	''.join(_lowerCamelCase	)
      lowercase							   =	bytearray([self.byte_decoder[c] for c in text]	).decode('utf-8'							,		errors=self.errors	)
      return text







    def       UpperCamelCase_				(      self							,		_lowerCamelCase							,		_lowerCamelCase = None	):
      if not os.path.isdir(_lowerCamelCase	):
        logger.error(F'Vocabulary path ({save_directory}) should be a directory'	)
        return
      lowercase							   =	os.path.join(
          _lowerCamelCase							,		(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['vocab_file']	)
      lowercase							   =	os.path.join(
          _lowerCamelCase							,		(filename_prefix + '-' if filename_prefix else '') + VOCAB_FILES_NAMES['merges_file']	)

      with open(_lowerCamelCase							,		'w'							,		encoding='utf-8'	) as f:
        f.write(json.dumps(self.encoder							,		indent=2							,		sort_keys=_lowerCamelCase							,		ensure_ascii=_lowerCamelCase	) + '\n'	)

      lowercase							   =	0
      with open(_lowerCamelCase							,		'w'							,		encoding='utf-8'	) as writer:
        writer.write('#version: 0.2\n'	)
        for bpe_tokens, token_index in sorted(self.bpe_ranks.items()							,		key=lambda _lowerCamelCase	: kv[1]	):
          if index != token_index:
            logger.warning(
                F'Saving vocabulary to {merge_file}: BPE merge indices are not consecutive.'
                ' Please check that the tokenizer is not corrupted!'	)
            lowercase							   =	token_index
          writer.write(' '.join(_lowerCamelCase	) + '\n'	)
          index += 1

      return vocab_file, merge_file







    def       UpperCamelCase_				(      self							,		_lowerCamelCase							,		_lowerCamelCase=False							,		**_lowerCamelCase	):
      lowercase							   =	kwargs.pop('add_prefix_space'							,		self.add_prefix_space	)
      if is_split_into_words or add_prefix_space:
        lowercase							   =	' ' + text
      return (text, kwargs)







    def       UpperCamelCase_				(      self							,		_lowerCamelCase	):
      lowercase							   =	[]
      for is_user, text in conversation.iter_texts():
        input_ids.extend(self.encode(_lowerCamelCase							,		add_special_tokens=_lowerCamelCase	) + [self.eos_token_id]	)
      if len(_lowerCamelCase	) > self.model_max_length:
        lowercase							   =	input_ids[-self.model_max_length :]
      return input_ids


