"""simple docstring"""



import argparse
import os
import re
import zipfile

import torch

from transformers import AutoTokenizer, GPTaConfig





def    SCREAMING_SNAKE_CASE   (     snake_case,      snake_case,      snake_case=0):
     # Format the message.
     if name is None:
          __snake_case				=							None
     else:
          __snake_case				=							'''.''' * max(0,      spaces - 2) + '''# {:''' + str(50 - spaces) + '''s}'''
          __snake_case				=							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,      snake_case,      snake_case,      snake_case,      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.
     __snake_case				=							param.size()
     if checkpoint_version == 1.0:
          # version 1.0 stores [num_heads * hidden_size * num_splits, :]
          __snake_case				=							(num_heads, hidden_size, num_splits) + input_shape[1:]
          __snake_case				=							param.view(*snake_case)
          __snake_case				=							param.transpose(0,      2)
          __snake_case				=							param.transpose(1,      2).contiguous()
     elif checkpoint_version >= 2.0:
          # other versions store [num_heads * num_splits * hidden_size, :]
          __snake_case				=							(num_heads, num_splits, hidden_size) + input_shape[1:]
          __snake_case				=							param.view(*snake_case)
          __snake_case				=							param.transpose(0,      1).contiguous()
     __snake_case				=							param.view(*snake_case)
     return param





def    SCREAMING_SNAKE_CASE   (     snake_case,      snake_case,      snake_case):
     # The converted output model.
     __snake_case				=							{}

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

          __snake_case				=							ds_args.padded_vocab_size
          __snake_case				=							ds_args.max_position_embeddings
          __snake_case				=							ds_args.hidden_size
          __snake_case				=							ds_args.num_layers
          __snake_case				=							ds_args.num_attention_heads
          __snake_case				=							ds_args.ffn_hidden_size
          # pprint(config)

     # The number of heads.
     __snake_case				=							config.n_head
     # The hidden_size per head.
     __snake_case				=							config.n_embd // config.n_head
     # Megatron-LM checkpoint version
     if "checkpoint_version" in input_state_dict.keys():
          __snake_case				=							input_state_dict['''checkpoint_version''']
     else:
          __snake_case				=							0.0

     # The model.
     __snake_case				=							input_state_dict['''model''']
     # The language model.
     __snake_case				=							model['''language_model''']
     # The embeddings.
     __snake_case				=							lm['''embedding''']

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

     # The position embeddings.
     __snake_case				=							embeddings['''position_embeddings''']['''weight''']
     # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size]
     __snake_case				=							pos_embeddings.size(0)
     if n_positions != config.n_positions:
          raise ValueError(
              f"pos_embeddings.max_sequence_length={n_positions} and config.n_positions={config.n_positions} don't match")
     # Store the position embeddings.
     __snake_case				=							pos_embeddings

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

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

     # The simple map of names for "automated" rules.
     __snake_case				=							{
         '''attention.dense''': '''.attn.c_proj.''',
         '''self_attention.dense''': '''.attn.c_proj.''',
         '''mlp.dense_h_to_4h''': '''.mlp.c_fc.''',
         '''mlp.dense_4h_to_h''': '''.mlp.c_proj.''',
     }

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

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

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

          # The name of the layer.
          __snake_case				=							f"transformer.h.{layer_idx}"

          # For layernorm(s), simply store the layer norm.
          if op_name.endswith('''layernorm'''):
               __snake_case				=							'''ln_1''' if op_name.startswith('''input''') else '''ln_2'''
               __snake_case				=							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":
               # Insert a tensor of 1x1xDxD bias.
               __snake_case				=							torch.tril(torch.ones((n_positions, n_positions),      dtype=torch.floataa)).view(
                   1,      1,      snake_case,      snake_case)
               __snake_case				=							causal_mask

               # Insert a "dummy" tensor for masked_bias.
               __snake_case				=							torch.tensor(-1E4,      dtype=torch.floataa)
               __snake_case				=							masked_bias

               __snake_case				=							fix_query_key_value_ordering(snake_case,      snake_case,      3,      snake_case,      snake_case)
               # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D.
               __snake_case				=							out_val.transpose(0,      1).contiguous()
               # Store.
               __snake_case				=							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":
               __snake_case				=							fix_query_key_value_ordering(snake_case,      snake_case,      3,      snake_case,      snake_case)
               # Store. No change of shape.
               __snake_case				=							out_val

          # Transpose the weights.
          elif weight_or_bias == "weight":
               __snake_case				=							megatron_to_transformers[op_name]
               __snake_case				=							val.transpose(0,      1)

          # Copy the bias.
          elif weight_or_bias == "bias":
               __snake_case				=							megatron_to_transformers[op_name]
               __snake_case				=							val

    # DEBUG.
     assert config.n_layer == layer_idx + 1

     # The final layernorm.
     __snake_case				=							transformer['''final_layernorm.weight''']
     __snake_case				=							transformer['''final_layernorm.bias''']

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

     # It should be done!
     return output_state_dict





def    SCREAMING_SNAKE_CASE   (     ):
     # Create the argument parser.
     __snake_case				=							argparse.ArgumentParser()
     parser.add_argument('''--print-checkpoint-structure''',      action='''store_true''')
     parser.add_argument(
         '''path_to_checkpoint''',      type=snake_case,      help='''Path to the checkpoint file (.zip archive or direct .pt file)''',      )
     parser.add_argument(
         '''--config_file''',      default='''''',      type=snake_case,      help='''An optional config json file describing the pre-trained model.''',      )
     __snake_case				=							parser.parse_args()

     # Extract the basename.
     __snake_case				=							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:
                    __snake_case				=							torch.load(snake_case,      map_location='''cpu''')
     else:
          __snake_case				=							torch.load(args.path_to_checkpoint,      map_location='''cpu''')

     __snake_case				=							input_state_dict.get('''args''',      snake_case)

     # Read the config, or default to the model released by NVIDIA.
     if args.config_file == "":
          if ds_args is not None:
               if ds_args.bias_gelu_fusion:
                    __snake_case				=							'''gelu_fast'''
               elif ds_args.openai_gelu:
                    __snake_case				=							'''gelu_new'''
               else:
                    __snake_case				=							'''gelu'''
          else:
               # in the very early days this used to be "gelu_new"
               __snake_case				=							'''gelu_new'''

          # Spell out all parameters in case the defaults change.
          __snake_case				=							GPTaConfig(
              vocab_size=5_02_57,      n_positions=10_24,      n_embd=10_24,      n_layer=24,      n_head=16,      n_inner=40_96,      activation_function=snake_case,      resid_pdrop=0.1,      embd_pdrop=0.1,      attn_pdrop=0.1,      layer_norm_epsilon=1E-5,      initializer_range=0.02,      summary_type='''cls_index''',      summary_use_proj=snake_case,      summary_activation=snake_case,      summary_proj_to_labels=snake_case,      summary_first_dropout=0.1,      scale_attn_weights=snake_case,      use_cache=snake_case,      bos_token_id=5_02_56,      eos_token_id=5_02_56,      )
     else:
          __snake_case				=							GPTaConfig.from_json_file(args.config_file)

     __snake_case				=							['''GPT2LMHeadModel''']

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

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

     # Add tokenizer class info to config
     # see https://github.com/huggingface/transformers/issues/13906)
     if ds_args is not None:
          __snake_case				=							ds_args.tokenizer_type
          if tokenizer_type == "GPT2BPETokenizer":
               __snake_case				=							'''gpt2'''
          elif tokenizer_type == "PretrainedFromHF":
               __snake_case				=							ds_args.tokenizer_name_or_path
          else:
               raise ValueError(f"Unrecognized tokenizer_type {tokenizer_type}")
     else:
          __snake_case				=							'''gpt2'''

     __snake_case				=							AutoTokenizer.from_pretrained(snake_case)
     __snake_case				=							type(snake_case).__name__
     __snake_case				=							tokenizer_class

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

     # Save tokenizer based on args
     print(f"Adding {tokenizer_class} tokenizer files")
     tokenizer.save_pretrained(snake_case)

     # Store the state_dict to file.
     __snake_case				=							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__":
       main()

####################################################################################################
"""simple docstring"""



import os
import re
from shutil import copyfile
from typing import List, Optional, Tuple

from ...tokenization_utils import PreTrainedTokenizer
from ...utils import logging


__lowercase		:		List[str]														=							logging.get_logger(__name__)

__lowercase		:		Union[str, Any]														=							{
    "vocab_file": "vocab.txt",
    "merges_file": "bpe.codes",
}

__lowercase		:		Optional[int]														=							{
    "vocab_file": {
        "vinai/phobert-base": "https://huggingface.co/vinai/phobert-base/resolve/main/vocab.txt",
        "vinai/phobert-large": "https://huggingface.co/vinai/phobert-large/resolve/main/vocab.txt",
    },
    "merges_file": {
        "vinai/phobert-base": "https://huggingface.co/vinai/phobert-base/resolve/main/bpe.codes",
        "vinai/phobert-large": "https://huggingface.co/vinai/phobert-large/resolve/main/bpe.codes",
    },
}

__lowercase		:		Dict														=							{
    "vinai/phobert-base": 256,
    "vinai/phobert-large": 256,
}





def    SCREAMING_SNAKE_CASE       (     snake_case):
     __snake_case				=							set()
     __snake_case				=							word[0]
     for char in word[1:]:
          pairs.add((prev_char, char))
          __snake_case				=							char

     __snake_case				=							set(snake_case)
     return pairs




class      _A	(						_UpperCAmelCase					):




    """simple docstring"""




    UpperCamelCase_	:					Union[str, Any]							=					VOCAB_FILES_NAMES
    UpperCamelCase_	:					Any							=					PRETRAINED_VOCAB_FILES_MAP
    UpperCamelCase_	:					Optional[Any]							=					PRETRAINED_POSITIONAL_EMBEDDINGS_SIZES
    def __init__(		self							:     Union[str, Any]	,      A_							:     Optional[Any]	,      A_							:     Optional[int]	,      A_							:     str="<s>"	,      A_							:     List[str]="</s>"	,      A_							:     List[Any]="</s>"	,      A_							:     List[str]="<s>"	,      A_							:     Optional[int]="<unk>"	,      A_							:     List[str]="<pad>"	,      A_							:     Any="<mask>"	,      **A_							:     int	,      )    ->       Tuple:
         super().__init__(
             bos_token=A_	,      eos_token=A_	,      unk_token=A_	,      sep_token=A_	,      cls_token=A_	,      pad_token=A_	,      mask_token=A_	,      **A_	,      )

         __snake_case				=							vocab_file
         __snake_case				=							merges_file

         __snake_case				=							{}
         __snake_case				=							0
         __snake_case				=							1
         __snake_case				=							2
         __snake_case				=							3

         self.add_from_file(A_    )

         __snake_case				=							{v: k for k, v in self.encoder.items()}

         with open(A_	,      encoding='''utf-8'''    ) as merges_handle:
              __snake_case				=							merges_handle.read().split('''\n'''    )[:-1]
         __snake_case				=							[tuple(merge.split()[:-1]    ) for merge in merges]
         __snake_case				=							dict(zip(A_	,      range(len(A_    )    )    )    )
         __snake_case				=							{}
    def  lowercase					(		self							:     str	,      A_							:     List[int]	,      A_							:     Optional[List[int]] = None    )    ->       List[int]:

         if token_ids_a is None:
              return [self.cls_token_id] + token_ids_a + [self.sep_token_id]
         __snake_case				=							[self.cls_token_id]
         __snake_case				=							[self.sep_token_id]
         return cls + token_ids_a + sep + sep + token_ids_a + sep
    def  lowercase					(		self							:     Dict	,      A_							:     List[int]	,      A_							:     Optional[List[int]] = None	,      A_							:     bool = False    )    ->       List[int]:

         if already_has_special_tokens:
              return super().get_special_tokens_mask(
                  token_ids_a=A_	,      token_ids_a=A_	,      already_has_special_tokens=A_    )

         if token_ids_a is None:
              return [1] + ([0] * len(A_    )) + [1]
         return [1] + ([0] * len(A_    )) + [1, 1] + ([0] * len(A_    )) + [1]
    def  lowercase					(		self							:     Optional[Any]	,      A_							:     List[int]	,      A_							:     Optional[List[int]] = None    )    ->       List[int]:
         __snake_case				=							[self.sep_token_id]
         __snake_case				=							[self.cls_token_id]

         if token_ids_a is None:
              return len(cls + token_ids_a + sep    ) * [0]
         return len(cls + token_ids_a + sep + sep + token_ids_a + sep    ) * [0]
    @property
    def  lowercase					(		self							:     List[Any]    )    ->       str:
         return len(self.encoder    )
    def  lowercase					(		self							:     Union[str, Any]    )    ->       Optional[int]:
         return dict(self.encoder	,      **self.added_tokens_encoder    )
    def  lowercase					(		self							:     str	,      A_							:     List[Any]    )    ->       Optional[int]:
         if token in self.cache:
              return self.cache[token]
         __snake_case				=							tuple(A_    )
         __snake_case				=							tuple(list(word[:-1]    ) + [word[-1] + '''</w>''']    )
         __snake_case				=							get_pairs(A_    )

         if not pairs:
              return token

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

                   if word[i] == first and i < len(A_    ) - 1 and word[i + 1] == second:
                        new_word.append(first + second    )
                        i += 2
                   else:
                        new_word.append(word[i]    )
                        i += 1
              __snake_case				=							tuple(A_    )
              __snake_case				=							new_word
              if len(A_    ) == 1:
                   break
              else:
                   __snake_case				=							get_pairs(A_    )
         __snake_case				=							'''@@ '''.join(A_    )
         __snake_case				=							word[:-4]
         __snake_case				=							word
         return word
    def  lowercase					(		self							:     int	,      A_							:     Tuple    )    ->       int:
         __snake_case				=							[]

         __snake_case				=							re.findall(R'''\S+\n?'''	,      A_    )

         for token in words:
              split_tokens.extend(list(self.bpe(A_    ).split(''' '''    )    )    )
         return split_tokens
    def  lowercase					(		self							:     Union[str, Any]	,      A_							:     Tuple    )    ->       int:
         return self.encoder.get(A_	,      self.encoder.get(self.unk_token    )    )
    def  lowercase					(		self							:     int	,      A_							:     Dict    )    ->       Optional[Any]:
         return self.decoder.get(A_	,      self.unk_token    )
    def  lowercase					(		self							:     Union[str, Any]	,      A_							:     int    )    ->       Tuple:
         __snake_case				=							''' '''.join(A_    ).replace('''@@ '''	,      ''''''    ).strip()
         return out_string
    def  lowercase					(		self							:     str	,      A_							:     str	,      A_							:     Optional[str] = None    )    ->       Tuple[str]:
         if not os.path.isdir(A_    ):
              logger.error(f"Vocabulary path ({save_directory}) should be a directory"    )
              return
         __snake_case				=							os.path.join(
             A_	,      (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''vocab_file''']    )
         __snake_case				=							os.path.join(
             A_	,      (filename_prefix + '''-''' if filename_prefix else '''''') + VOCAB_FILES_NAMES['''merges_file''']    )

         if os.path.abspath(self.vocab_file    ) != os.path.abspath(A_    ):
              copyfile(self.vocab_file	,      A_    )

         if os.path.abspath(self.merges_file    ) != os.path.abspath(A_    ):
              copyfile(self.merges_file	,      A_    )

         return out_vocab_file, out_merge_file







    def  lowercase					(		self							:     Optional[int]	,      A_							:     Union[str, Any]    )    ->       Dict:
         if isinstance(A_	,      A_    ):
              try:
                   with open(A_	,      '''r'''	,      encoding='''utf-8'''    ) as fd:
                        self.add_from_file(A_    )
              except FileNotFoundError as fnfe:
                   raise fnfe
              except UnicodeError:
                   raise Exception(f"Incorrect encoding detected in {f}, please rebuild the dataset"    )
              return

         __snake_case				=							f.readlines()
         for lineTmp in lines:
              __snake_case				=							lineTmp.strip()
              __snake_case				=							line.rfind(''' '''    )
              if idx == -1:
                   raise ValueError('''Incorrect dictionary format, expected \'<token> <cnt>\''''    )
              __snake_case				=							line[:idx]
              __snake_case				=							len(self.encoder    )