

# Copyright (c) 2021-, NVIDIA CORPORATION.  All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

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

#
# Note: If when running this conversion script you're getting an exception:
#     ModuleNotFoundError: No module named 'megatron.model.enums'
# you need to tell python where to find the clone of Megatron-LM, e.g.:
#
# cd /tmp
# git clone https://github.com/NVIDIA/Megatron-LM
# PYTHONPATH=/tmp/Megatron-LM python src/transformers/models/megatron_bert/convert_megatron_bert_checkpoint.py ...
#
# if you already have it cloned elsewhere, simply adjust the path to the existing path
#
# If the training was done using a Megatron-LM fork, e.g.,
# https://github.com/microsoft/Megatron-DeepSpeed/ then chances are that you need to have that one
# in your path, i.e., /path/to/Megatron-DeepSpeed/
#

import argparse
import os
import re
import zipfile

import torch

from transformers import MegatronBertConfig

def 			snake_case__    (					SCREAMING_SNAKE_CASE_	:					Dict			,  SCREAMING_SNAKE_CASE_	:					Any			,  SCREAMING_SNAKE_CASE_	:					Any=0    ):



     '''simple docstring'''





     if name is None:
          lowercase__					:     Tuple   = None
     else:
          lowercase__					:     Union[str, Any]   = '.' * max(0			,  spaces - 2    ) + '# {:' + str(50 - spaces    ) + 's}'
          lowercase__					:     str   = 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 			snake_case__    (					SCREAMING_SNAKE_CASE_	:					Tuple			,  SCREAMING_SNAKE_CASE_	:					Any			,  SCREAMING_SNAKE_CASE_	:					Optional[int]			,  SCREAMING_SNAKE_CASE_	:					Optional[int]			,  SCREAMING_SNAKE_CASE_	:					Any    ):



     '''simple docstring'''





     lowercase__					:     Optional[int]   = param.size()
     if checkpoint_version == 1.0:
          # version 1.0 stores [num_heads * hidden_size * num_splits, :]
          lowercase__					:     Tuple   = (num_heads, hidden_size, num_splits) + input_shape[1:]
          lowercase__					:     Any   = param.view(*SCREAMING_SNAKE_CASE_    )
          lowercase__					:     str   = param.transpose(0			,  2    )
          lowercase__					:     str   = param.transpose(1			,  2    ).contiguous()
     elif checkpoint_version >= 2.0:
          # other versions store [num_heads * num_splits * hidden_size, :]
          lowercase__					:     Union[str, Any]   = (num_heads, num_splits, hidden_size) + input_shape[1:]
          lowercase__					:     List[Any]   = param.view(*SCREAMING_SNAKE_CASE_    )
          lowercase__					:     int   = param.transpose(0			,  1    ).contiguous()
     lowercase__					:     str   = param.view(*SCREAMING_SNAKE_CASE_    )
     return param

def 			snake_case__    (					SCREAMING_SNAKE_CASE_	:					Tuple			,  SCREAMING_SNAKE_CASE_	:					Optional[Any]			,  SCREAMING_SNAKE_CASE_	:					List[str]    ):



     '''simple docstring'''





     lowercase__					:     str   = {}

     # old versions did not store training args
     lowercase__					:     Optional[Any]   = input_state_dict.get('args'			,  SCREAMING_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))

          lowercase__					:     Dict   = ds_args.tokenizer_type
          lowercase__					:     Optional[Any]   = ds_args.padded_vocab_size
          lowercase__					:     Any   = ds_args.max_position_embeddings
          lowercase__					:     Dict   = ds_args.hidden_size
          lowercase__					:     Optional[Any]   = ds_args.num_layers
          lowercase__					:     Union[str, Any]   = ds_args.num_attention_heads
          lowercase__					:     Union[str, Any]   = ds_args.ffn_hidden_size if 'ffn_hidden_size' in ds_args else 4 * ds_args.hidden_size
          # pprint(config)

     # The number of heads.
     lowercase__					:     Optional[int]   = config.num_attention_heads
     # The hidden_size per head.
     lowercase__					:     Union[str, Any]   = config.hidden_size // heads
     # Megatron-LM checkpoint version
     if "checkpoint_version" in input_state_dict.keys():
          lowercase__					:     Dict   = input_state_dict['checkpoint_version']
     else:
          lowercase__					:     Tuple   = 0.0

     # The model.
     lowercase__					:     Optional[int]   = input_state_dict['model']
     # The language model.
     lowercase__					:     Any   = model['language_model']
     # The embeddings.
     lowercase__					:     Union[str, Any]   = lm['embedding']

     # The word embeddings.
     lowercase__					:     List[str]   = embeddings['word_embeddings']['weight']
     # Truncate the embedding table to vocab_size rows.
     lowercase__					:     int   = word_embeddings[: config.vocab_size, :]
     # Store the word embeddings.
     lowercase__					:     List[str]   = word_embeddings

     # The position embeddings.
     lowercase__					:     Optional[Any]   = embeddings['position_embeddings']['weight']
     assert pos_embeddings.size(0    ) == config.max_position_embeddings and pos_embeddings.size(1    ) == config.hidden_size
     # Store the position embeddings.
     lowercase__					:     Dict   = pos_embeddings

     # The token-type embeddings.
     lowercase__					:     Union[str, Any]   = embeddings['tokentype_embeddings']['weight']
     # Store the position embeddings.
     lowercase__					:     Optional[Any]   = tokentype_embeddings

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

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

     # The simple map of names for "automated" rules.
     lowercase__					:     str   = {
         'attention.dense': '.attention.output.dense.',
         'self_attention.dense': '.attention.output.dense.',
         'mlp.dense_h_to_4h': '.intermediate.dense.',
         'mlp.dense_4h_to_h': '.output.dense.',
     }

     # Keep track of the attention/query/value tensor.
     lowercase__					:     int   = None

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

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

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

          # The name of the layer.
          lowercase__					:     Dict   = f"""bert.encoder.layer.{layer_idx}"""

          # For layernorm(s), simply store the layer norm.
          if op_name.endswith('layernorm'    ):
               lowercase__					:     List[str]   = 'attention.ln' if op_name.startswith('input'    ) else 'ln'
               lowercase__					:     Dict   = 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":
               # Make sure the QKV pointer is nil.
               assert attention_qkv_weight is None, ""

               lowercase__					:     int   = fix_query_key_value_ordering(SCREAMING_SNAKE_CASE_			,  SCREAMING_SNAKE_CASE_			,  3			,  SCREAMING_SNAKE_CASE_			,  SCREAMING_SNAKE_CASE_    )
               # Store the tensor as we need the bias as well to interleave QKV and biases.
               lowercase__					:     Optional[int]   = 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":
               # Make sure we read the weight tensor.
               assert attention_qkv_weight is not None, ""

               # Split the QKV matrix into Q, K and V. Megatron stores Q,K,V interleaved.
               lowercase__					:     Optional[Any]   = attention_qkv_weight[0 * config.hidden_size : 1 * config.hidden_size, :]
               lowercase__					:     Any   = attention_qkv_weight[1 * config.hidden_size : 2 * config.hidden_size, :]
               lowercase__					:     Optional[Any]   = attention_qkv_weight[2 * config.hidden_size : 3 * config.hidden_size, :]

               lowercase__					:     Optional[Any]   = fix_query_key_value_ordering(SCREAMING_SNAKE_CASE_			,  SCREAMING_SNAKE_CASE_			,  3			,  SCREAMING_SNAKE_CASE_			,  SCREAMING_SNAKE_CASE_    )
               # Split the bias.
               lowercase__					:     List[str]   = out_val[0 * config.hidden_size : 1 * config.hidden_size]
               lowercase__					:     Union[str, Any]   = out_val[1 * config.hidden_size : 2 * config.hidden_size]
               lowercase__					:     Tuple   = out_val[2 * config.hidden_size : 3 * config.hidden_size]

               # Store.
               lowercase__					:     List[Any]   = q
               lowercase__					:     int   = q_bias
               lowercase__					:     Dict   = k
               lowercase__					:     Dict   = k_bias
               lowercase__					:     int   = v
               lowercase__					:     Tuple   = v_bias

               # Clear the stored tensor.
               lowercase__					:     Union[str, Any]   = None

          # Copy weights and biases as is.
          elif weight_or_bias in ["weight", "bias"]:
               lowercase__					:     Optional[int]   = megatron_to_transformers[op_name]
               lowercase__					:     Optional[Any]   = val

    # The final layernorm.
     lowercase__					:     Optional[int]   = transformer['final_layernorm.weight']
     lowercase__					:     int   = transformer['final_layernorm.bias']

     # The pooler.
     lowercase__					:     str   = lm['pooler']

     # Store the matrix and the bias.
     lowercase__					:     Union[str, Any]   = pooler['dense.weight']
     lowercase__					:     Tuple   = pooler['dense.bias']

     # The LM head from Megatron (for RACE).
     lowercase__					:     Dict   = model['lm_head']

     # The transform matrix.
     lowercase__					:     int   = lm_head['dense.weight']
     lowercase__					:     Dict   = lm_head['dense.bias']

     # The transform LN.
     lowercase__					:     List[Any]   = lm_head['layernorm.weight']
     lowercase__					:     Optional[int]   = lm_head['layernorm.bias']

     # For the decoder, we replicate the weights.
     lowercase__					:     Union[str, Any]   = word_embeddings
     lowercase__					:     List[str]   = lm_head['bias']

     # The classifier from Megatron (for MLNI).
     lowercase__					:     Any   = model['binary_head']

     # Store the classifier.
     lowercase__					:     List[Any]   = binary_head['weight']
     lowercase__					:     int   = binary_head['bias']

     # It should be done!
     return output_state_dict

def 			snake_case__    (					):



     '''simple docstring'''





     lowercase__					:     List[Any]   = argparse.ArgumentParser()
     parser.add_argument('--print-checkpoint-structure'			,  action='store_true'    )
     parser.add_argument('path_to_checkpoint'			,  type=SCREAMING_SNAKE_CASE_			,  help='Path to the ZIP file containing the checkpoint'    )
     parser.add_argument(
         '--config_file'			,  default=''			,  type=SCREAMING_SNAKE_CASE_			,  help='An optional config json file describing the pre-trained model.'			,  )
     lowercase__					:     Optional[int]   = parser.parse_args()

     # Extract the basename.
     lowercase__					:     Dict   = 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:
                    lowercase__					:     List[str]   = torch.load(SCREAMING_SNAKE_CASE_			,  map_location='cpu'    )
     else:
          lowercase__					:     Dict   = torch.load(args.path_to_checkpoint			,  map_location='cpu'    )

     if args.config_file == "":
          # Default config of megatron-bert 345m
          lowercase__					:     Tuple   = MegatronBertConfig()

          # different megatron-bert-*-345m models have different vocab sizes, so override the default
          # config (which is for megatron-bert-cased-345m) with the actual vocab dimension
          lowercase__					:     Optional[int]   = input_state_dict['model']['lm_head']['bias'].numel()
     else:
          lowercase__					:     int   = MegatronBertConfig.from_json_file(args.config_file    )

     # Convert.
     print('Converting'    )
     lowercase__					:     Tuple   = convert_megatron_checkpoint(SCREAMING_SNAKE_CASE_			,  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_    )

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

     # Store the state_dict to file.
     lowercase__					:     Optional[int]   = 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__":
       main()

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




from transformers.models.cpm.tokenization_cpm import CpmTokenizer
from transformers.testing_utils import custom_tokenizers

from ..xlnet.test_modeling_xlnet import XLNetModelTest


@custom_tokenizers
class    SCREAMING_SNAKE_CASE__      (__snake_case  ):





    def    snake_case_       (   self		,     a		,     a		,     a		,     a		,     a):
         return True





    def    snake_case_       (   self):
         lowercase__					:     Tuple   = CpmTokenizer.from_pretrained('TsinghuaAI/CPM-Generate')
         lowercase__					:     str   = 'Hugging Face大法好，谁用谁知道。'
         lowercase__					:     Optional[int]   = 'Hugging Face大法好,谁用谁知道。<unk>'
         lowercase__					:     Any   = '▁Hu gg ing ▁ ▂ ▁F ace ▁大法 ▁好 ▁ , ▁谁 ▁用 ▁谁 ▁知 道 ▁ 。'.split()

         lowercase__					:     Any   = tokenizer.tokenize(a)
         self.assertListEqual(a		,     a)

         lowercase__					:     List[Any]   = tokens + [tokenizer.unk_token]

         lowercase__					:     Any   = [1_3789, 1_3283, 1421, 8, 10, 1164, 1_3608, 1_6528, 63, 8, 9, 440, 108, 440, 121, 90, 8, 12, 0]
         self.assertListEqual(tokenizer.convert_tokens_to_ids(a)		,     a)

         lowercase__					:     Optional[Any]   = tokenizer.decode(a)
         self.assertEqual(a		,     a)

