

"""simple docstring"""


import argparse
import os
import re
import zipfile

import torch

from transformers import AutoTokenizer, GPTaConfig




def  _lowercase					(    __lowerCAmelCase  ,					__lowerCAmelCase  ,					__lowerCAmelCase=0							)       ->				Any:
      # Format the message.
      if name is None:
            SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	None
      else:
            SCREAMING_SNAKE_CASE__   :      str      		=	""".""" * max(0  ,					spaces - 2							) + """# {:""" + str(50 - spaces							) + """s}"""
            SCREAMING_SNAKE_CASE__   :      Dict      		=	fmt.format(__lowerCAmelCase							)

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




def  _lowercase					(    __lowerCAmelCase  ,					__lowerCAmelCase  ,					__lowerCAmelCase  ,					__lowerCAmelCase  ,					__lowerCAmelCase							)       ->				List[Any]:
      # 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.
      SCREAMING_SNAKE_CASE__   :      Tuple      		=	param.size()
      if checkpoint_version == 1.0:
            # version 1.0 stores [num_heads * hidden_size * num_splits, :]
            SCREAMING_SNAKE_CASE__   :      int      		=	(num_heads, hidden_size, num_splits) + input_shape[1:]
            SCREAMING_SNAKE_CASE__   :      List[str]      		=	param.view(*__lowerCAmelCase							)
            SCREAMING_SNAKE_CASE__   :      List[str]      		=	param.transpose(0  ,					2							)
            SCREAMING_SNAKE_CASE__   :      List[Any]      		=	param.transpose(1  ,					2							).contiguous()
      elif checkpoint_version >= 2.0:
            # other versions store [num_heads * num_splits * hidden_size, :]
            SCREAMING_SNAKE_CASE__   :      List[str]      		=	(num_heads, num_splits, hidden_size) + input_shape[1:]
            SCREAMING_SNAKE_CASE__   :      Dict      		=	param.view(*__lowerCAmelCase							)
            SCREAMING_SNAKE_CASE__   :      int      		=	param.transpose(0  ,					1							).contiguous()
      SCREAMING_SNAKE_CASE__   :      Any      		=	param.view(*__lowerCAmelCase							)
      return param




def  _lowercase					(    __lowerCAmelCase  ,					__lowerCAmelCase  ,					__lowerCAmelCase							)       ->				Tuple:
      # The converted output model.
      SCREAMING_SNAKE_CASE__   :      List[str]      		=	{}

      # old versions did not store training args
      SCREAMING_SNAKE_CASE__   :      List[str]      		=	input_state_dict.get("""args"""  ,					__lowerCAmelCase							)
      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))

            SCREAMING_SNAKE_CASE__   :      List[Any]      		=	ds_args.padded_vocab_size
            SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	ds_args.max_position_embeddings
            SCREAMING_SNAKE_CASE__   :      List[Any]      		=	ds_args.hidden_size
            SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	ds_args.num_layers
            SCREAMING_SNAKE_CASE__   :      Dict      		=	ds_args.num_attention_heads
            SCREAMING_SNAKE_CASE__   :      List[str]      		=	ds_args.ffn_hidden_size
            # pprint(config)

      # The number of heads.
      SCREAMING_SNAKE_CASE__   :      List[str]      		=	config.n_head
      # The hidden_size per head.
      SCREAMING_SNAKE_CASE__   :      str      		=	config.n_embd // config.n_head
      # Megatron-LM checkpoint version
      if "checkpoint_version" in input_state_dict.keys():
            SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	input_state_dict["""checkpoint_version"""]
      else:
            SCREAMING_SNAKE_CASE__   :      Tuple      		=	0.0

      # The model.
      SCREAMING_SNAKE_CASE__   :      Any      		=	input_state_dict["""model"""]
      # The language model.
      SCREAMING_SNAKE_CASE__   :      Any      		=	model["""language_model"""]
      # The embeddings.
      SCREAMING_SNAKE_CASE__   :      str      		=	lm["""embedding"""]

      # The word embeddings.
      SCREAMING_SNAKE_CASE__   :      int      		=	embeddings["""word_embeddings"""]["""weight"""]
      # Truncate the embedding table to vocab_size rows.
      SCREAMING_SNAKE_CASE__   :      Any      		=	word_embeddings[: config.vocab_size, :]
      SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	word_embeddings

      # The position embeddings.
      SCREAMING_SNAKE_CASE__   :      Any      		=	embeddings["""position_embeddings"""]["""weight"""]
      # Read the causal mask dimension (seqlen). [max_sequence_length, hidden_size]
      SCREAMING_SNAKE_CASE__   :      Tuple      		=	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.
      SCREAMING_SNAKE_CASE__   :      List[Any]      		=	pos_embeddings

      # The transformer.
      SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	lm["""transformer"""] if """transformer""" in lm.keys() else lm["""encoder"""]

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

      # The simple map of names for "automated" rules.
      SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	{
          """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.
            SCREAMING_SNAKE_CASE__   :      str      		=	layer_re.match(__lowerCAmelCase							)

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

            # The index of the layer.
            SCREAMING_SNAKE_CASE__   :      Dict      		=	int(m.group(1							)							)
            # The name of the operation.
            SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	m.group(2							)
            # Is it a weight or a bias?
            SCREAMING_SNAKE_CASE__   :      str      		=	m.group(3							)

            # The name of the layer.
            SCREAMING_SNAKE_CASE__   :      List[Any]      		=	F'''transformer.h.{layer_idx}'''

            # For layernorm(s), simply store the layer norm.
            if op_name.endswith("""layernorm"""							):
                  SCREAMING_SNAKE_CASE__   :      Dict      		=	"""ln_1""" if op_name.startswith("""input"""							) else """ln_2"""
                  SCREAMING_SNAKE_CASE__   :      List[Any]      		=	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.
                  SCREAMING_SNAKE_CASE__   :      Any      		=	torch.tril(torch.ones((n_positions, n_positions)  ,					dtype=torch.floataa							)							).view(
                      1  ,					1  ,					__lowerCAmelCase  ,					__lowerCAmelCase							)
                  SCREAMING_SNAKE_CASE__   :      str      		=	causal_mask

                  # Insert a "dummy" tensor for masked_bias.
                  SCREAMING_SNAKE_CASE__   :      List[Any]      		=	torch.tensor(-1E4  ,					dtype=torch.floataa							)
                  SCREAMING_SNAKE_CASE__   :      List[str]      		=	masked_bias

                  SCREAMING_SNAKE_CASE__   :      List[str]      		=	fix_query_key_value_ordering(__lowerCAmelCase  ,					__lowerCAmelCase  ,					3  ,					__lowerCAmelCase  ,					__lowerCAmelCase							)
                  # Megatron stores (3*D) x D but transformers-GPT2 expects D x 3*D.
                  SCREAMING_SNAKE_CASE__   :      str      		=	out_val.transpose(0  ,					1							).contiguous()
                  # Store.
                  SCREAMING_SNAKE_CASE__   :      Dict      		=	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":
                  SCREAMING_SNAKE_CASE__   :      Any      		=	fix_query_key_value_ordering(__lowerCAmelCase  ,					__lowerCAmelCase  ,					3  ,					__lowerCAmelCase  ,					__lowerCAmelCase							)
                  # Store. No change of shape.
                  SCREAMING_SNAKE_CASE__   :      str      		=	out_val

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

            # Copy the bias.
            elif weight_or_bias == "bias":
                  SCREAMING_SNAKE_CASE__   :      int      		=	megatron_to_transformers[op_name]
                  SCREAMING_SNAKE_CASE__   :      Dict      		=	val

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

      # The final layernorm.
      SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	transformer["""final_layernorm.weight"""]
      SCREAMING_SNAKE_CASE__   :      str      		=	transformer["""final_layernorm.bias"""]

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

      # It should be done!
      return output_state_dict




def  _lowercase					(    )       ->				List[Any]:
      # Create the argument parser.
      SCREAMING_SNAKE_CASE__   :      str      		=	argparse.ArgumentParser()
      parser.add_argument("""--print-checkpoint-structure"""  ,					action="""store_true"""							)
      parser.add_argument(
          """path_to_checkpoint"""  ,					type=__lowerCAmelCase  ,					help="""Path to the checkpoint file (.zip archive or direct .pt file)"""  ,					)
      parser.add_argument(
          """--config_file"""  ,					default=""""""  ,					type=__lowerCAmelCase  ,					help="""An optional config json file describing the pre-trained model."""  ,					)
      SCREAMING_SNAKE_CASE__   :      Dict      		=	parser.parse_args()

      # Extract the basename.
      SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	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:
                        SCREAMING_SNAKE_CASE__   :      List[Any]      		=	torch.load(__lowerCAmelCase  ,					map_location="""cpu"""							)
      else:
            SCREAMING_SNAKE_CASE__   :      str      		=	torch.load(args.path_to_checkpoint  ,					map_location="""cpu"""							)

      SCREAMING_SNAKE_CASE__   :      int      		=	input_state_dict.get("""args"""  ,					__lowerCAmelCase							)

      # 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:
                        SCREAMING_SNAKE_CASE__   :      Dict      		=	"""gelu_fast"""
                  elif ds_args.openai_gelu:
                        SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	"""gelu_new"""
                  else:
                        SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	"""gelu"""
            else:
                  # in the very early days this used to be "gelu_new"
                  SCREAMING_SNAKE_CASE__   :      Any      		=	"""gelu_new"""

            # Spell out all parameters in case the defaults change.
            SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	GPTaConfig(
                vocab_size=5_0257  ,					n_positions=1024  ,					n_embd=1024  ,					n_layer=24  ,					n_head=16  ,					n_inner=4096  ,					activation_function=__lowerCAmelCase  ,					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=__lowerCAmelCase  ,					summary_activation=__lowerCAmelCase  ,					summary_proj_to_labels=__lowerCAmelCase  ,					summary_first_dropout=0.1  ,					scale_attn_weights=__lowerCAmelCase  ,					use_cache=__lowerCAmelCase  ,					bos_token_id=5_0256  ,					eos_token_id=5_0256  ,					)
      else:
            SCREAMING_SNAKE_CASE__   :      List[Any]      		=	GPTaConfig.from_json_file(args.config_file							)

      SCREAMING_SNAKE_CASE__   :      Tuple      		=	["""GPT2LMHeadModel"""]

      # Convert.
      print("""Converting"""							)
      SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	convert_megatron_checkpoint(__lowerCAmelCase  ,					__lowerCAmelCase  ,					__lowerCAmelCase							)

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

      # Add tokenizer class info to config
      # see https://github.com/huggingface/transformers/issues/13906)
      if ds_args is not None:
            SCREAMING_SNAKE_CASE__   :      Tuple      		=	ds_args.tokenizer_type
            if tokenizer_type == "GPT2BPETokenizer":
                  SCREAMING_SNAKE_CASE__   :      Any      		=	"""gpt2"""
            elif tokenizer_type == "PretrainedFromHF":
                  SCREAMING_SNAKE_CASE__   :      Any      		=	ds_args.tokenizer_name_or_path
            else:
                  raise ValueError(F'''Unrecognized tokenizer_type {tokenizer_type}'''							)
      else:
            SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	"""gpt2"""

      SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	AutoTokenizer.from_pretrained(__lowerCAmelCase							)
      SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	type(__lowerCAmelCase							).__name__
      SCREAMING_SNAKE_CASE__   :      Dict      		=	tokenizer_class

      # Store the config to file.
      print("""Saving config"""							)
      config.save_pretrained(__lowerCAmelCase							)

      # Save tokenizer based on args
      print(F'''Adding {tokenizer_class} tokenizer files'''							)
      tokenizer.save_pretrained(__lowerCAmelCase							)

      # Store the state_dict to file.
      SCREAMING_SNAKE_CASE__   :      Any      		=	os.path.join(__lowerCAmelCase  ,					"""pytorch_model.bin"""							)
      print(F'''Saving checkpoint to "{output_checkpoint_file}"'''							)
      torch.save(__lowerCAmelCase  ,					__lowerCAmelCase							)


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

if __name__ == "__main__":
  main()

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







"""simple docstring"""


import unittest

import numpy as np

from transformers import RoFormerConfig, is_flax_available
from transformers.testing_utils import require_flax, slow

from ...test_modeling_flax_common import FlaxModelTesterMixin, ids_tensor, random_attention_mask


if is_flax_available():
  import jax.numpy as jnp

  from transformers.models.roformer.modeling_flax_roformer import (
      FlaxRoFormerForMaskedLM,
      FlaxRoFormerForMultipleChoice,
      FlaxRoFormerForQuestionAnswering,
      FlaxRoFormerForSequenceClassification,
      FlaxRoFormerForTokenClassification,
      FlaxRoFormerModel,
  )

class      __a							(unittest.TestCase):






     '''simple docstring'''

     def __init__(						self	,    _a	,    _a=13	,    _a=7	,    _a=True	,    _a=True	,    _a=True	,    _a=True	,    _a=99	,    _a=32	,    _a=5	,    _a=4	,    _a=37	,    _a="gelu"	,    _a=0.1	,    _a=0.1	,    _a=512	,    _a=16	,    _a=2	,    _a=0.02	,    _a=4	,    )  ->      List[str]:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      str      		=	parent
           SCREAMING_SNAKE_CASE__   :      Tuple      		=	batch_size
           SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	seq_length
           SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	is_training
           SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	use_attention_mask
           SCREAMING_SNAKE_CASE__   :      Tuple      		=	use_token_type_ids
           SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	use_labels
           SCREAMING_SNAKE_CASE__   :      int      		=	vocab_size
           SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	hidden_size
           SCREAMING_SNAKE_CASE__   :      List[Any]      		=	num_hidden_layers
           SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	num_attention_heads
           SCREAMING_SNAKE_CASE__   :      Dict      		=	intermediate_size
           SCREAMING_SNAKE_CASE__   :      int      		=	hidden_act
           SCREAMING_SNAKE_CASE__   :      Dict      		=	hidden_dropout_prob
           SCREAMING_SNAKE_CASE__   :      str      		=	attention_probs_dropout_prob
           SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	max_position_embeddings
           SCREAMING_SNAKE_CASE__   :      Dict      		=	type_vocab_size
           SCREAMING_SNAKE_CASE__   :      Any      		=	type_sequence_label_size
           SCREAMING_SNAKE_CASE__   :      int      		=	initializer_range
           SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	num_choices

     def 					_a			(						self  )  ->      Optional[int]:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      Tuple      		=	ids_tensor([self.batch_size, self.seq_length]	,    self.vocab_size  )

           SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	None
           if self.use_attention_mask:
                 SCREAMING_SNAKE_CASE__   :      int      		=	random_attention_mask([self.batch_size, self.seq_length]  )

           SCREAMING_SNAKE_CASE__   :      Tuple      		=	None
           if self.use_token_type_ids:
                 SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	ids_tensor([self.batch_size, self.seq_length]	,    self.type_vocab_size  )

           SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	RoFormerConfig(
               vocab_size=self.vocab_size	,    hidden_size=self.hidden_size	,    num_hidden_layers=self.num_hidden_layers	,    num_attention_heads=self.num_attention_heads	,    intermediate_size=self.intermediate_size	,    hidden_act=self.hidden_act	,    hidden_dropout_prob=self.hidden_dropout_prob	,    attention_probs_dropout_prob=self.attention_probs_dropout_prob	,    max_position_embeddings=self.max_position_embeddings	,    type_vocab_size=self.type_vocab_size	,    is_decoder=_a	,    initializer_range=self.initializer_range	,    )

           return config, input_ids, token_type_ids, attention_mask





     def 					_a			(						self  )  ->      Tuple:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      Optional[int]      		=	self.prepare_config_and_inputs()
           SCREAMING_SNAKE_CASE__		,		SCREAMING_SNAKE_CASE__		,		SCREAMING_SNAKE_CASE__		,		SCREAMING_SNAKE_CASE__   :      List[str]      		=	config_and_inputs
           SCREAMING_SNAKE_CASE__   :      List[Any]      		=	{"""input_ids""": input_ids, """token_type_ids""": token_type_ids, """attention_mask""": attention_mask}
           return config, inputs_dict





@require_flax
class      __a							(UpperCamelCase_   ,	unittest.TestCase):






     '''simple docstring'''
     _SCREAMING_SNAKE_CASE						:Any       = True

     _SCREAMING_SNAKE_CASE						:Optional[Any]       = (
         (
             FlaxRoFormerModel,
             FlaxRoFormerForMaskedLM,
             FlaxRoFormerForSequenceClassification,
             FlaxRoFormerForTokenClassification,
             FlaxRoFormerForMultipleChoice,
             FlaxRoFormerForQuestionAnswering,
         )
         if is_flax_available()
         else ()
     )

     def 					_a			(						self  )  ->      List[Any]:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	FlaxRoFormerModelTester(self  )





     @slow
     def 					_a			(						self  )  ->      int:


           """simple docstring"""


           for model_class_name in self.all_model_classes:
                 SCREAMING_SNAKE_CASE__   :      Tuple      		=	model_class_name.from_pretrained("""junnyu/roformer_chinese_small"""	,    from_pt=_a  )
                 SCREAMING_SNAKE_CASE__   :      Tuple      		=	model(np.ones((1, 1)  )  )
                 self.assertIsNotNone(_a  )





@require_flax
class      __a							(unittest.TestCase):






     '''simple docstring'''

     @slow
     def 					_a			(						self  )  ->      Dict:


           """simple docstring"""


           SCREAMING_SNAKE_CASE__   :      Union[str, Any]      		=	FlaxRoFormerForMaskedLM.from_pretrained("""junnyu/roformer_chinese_base"""  )
           SCREAMING_SNAKE_CASE__   :      Tuple      		=	jnp.array([[0, 1, 2, 3, 4, 5]]  )
           SCREAMING_SNAKE_CASE__   :      str      		=	model(_a  )[0]

           SCREAMING_SNAKE_CASE__   :      List[Any]      		=	50_000

           SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	(1, 6, vocab_size)
           self.assertEqual(output.shape	,    _a  )

           SCREAMING_SNAKE_CASE__   :      Optional[Any]      		=	jnp.array(
               [[[-0.1_205, -1.0_265, 0.2_922], [-1.5_134, 0.1_974, 0.1_519], [-5.0_135, -3.9_003, -0.8_404]]]  )

           self.assertTrue(jnp.allclose(output[:, :3, :3]	,    _a	,    atol=1E-4  )  )




