'''simple docstring'''


# 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_gpt2/convert_megatron_gpt2_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 AutoTokenizer, GPTaConfig


def  _lowerCamelCase   (				lowerCamelCase_ :							Union[str, Any]     ,					lowerCamelCase_ :							Optional[int]     ,					lowerCamelCase_ :							Optional[int]=0       ):



     """simple docstring"""





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



     """simple docstring"""





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


def  _lowerCamelCase   (				lowerCamelCase_ :							Any     ,					lowerCamelCase_ :							str     ,					lowerCamelCase_ :							Any       ):



     """simple docstring"""





     UpperCAmelCase_							:       Optional[int]       =				{}

     # old versions did not store training args
     UpperCAmelCase_							:       Any       =				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))

          UpperCAmelCase_							:       Optional[Any]       =				ds_args.padded_vocab_size
          UpperCAmelCase_							:       Optional[Any]       =				ds_args.max_position_embeddings
          UpperCAmelCase_							:       Tuple       =				ds_args.hidden_size
          UpperCAmelCase_							:       Optional[Any]       =				ds_args.num_layers
          UpperCAmelCase_							:       int       =				ds_args.num_attention_heads
          UpperCAmelCase_							:       int       =				ds_args.ffn_hidden_size
          # pprint(config)

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

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

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

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

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

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

     # The simple map of names for "automated" rules.
     UpperCAmelCase_							:       str       =				{
         '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.
          UpperCAmelCase_							:       Tuple       =				layer_re.match(lowerCamelCase_       )

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

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

          # The name of the layer.
          UpperCAmelCase_							:       int       =				F'''transformer.h.{layer_idx}'''

          # For layernorm(s), simply store the layer norm.
          if op_name.endswith('layernorm'       ):
               UpperCAmelCase_							:       str       =				'ln_1' if op_name.startswith('input'       ) else 'ln_2'
               UpperCAmelCase_							:       Optional[int]       =				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.
               UpperCAmelCase_							:       str       =				torch.tril(torch.ones((n_positions, n_positions)     ,					dtype=torch.floataa       )       ).view(
                   1     ,					1     ,					lowerCamelCase_     ,					lowerCamelCase_       )
               UpperCAmelCase_							:       int       =				causal_mask

               # Insert a "dummy" tensor for masked_bias.
               UpperCAmelCase_							:       List[Any]       =				torch.tensor(-1e4     ,					dtype=torch.floataa       )
               UpperCAmelCase_							:       int       =				masked_bias

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

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

          # Copy the bias.
          elif weight_or_bias == "bias":
               UpperCAmelCase_							:       Optional[int]       =				megatron_to_transformers[op_name]
               UpperCAmelCase_							:       str       =				val

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

     # The final layernorm.
     UpperCAmelCase_							:       Tuple       =				transformer['final_layernorm.weight']
     UpperCAmelCase_							:       Tuple       =				transformer['final_layernorm.bias']

     # For LM head, transformers' wants the matrix to weight embeddings.
     UpperCAmelCase_							:       List[str]       =				word_embeddings

     # It should be done!
     return output_state_dict


def  _lowerCamelCase   (				):



     """simple docstring"""





     UpperCAmelCase_							:       List[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.'     ,					)
     UpperCAmelCase_							:       Tuple       =				parser.parse_args()

     # Extract the basename.
     UpperCAmelCase_							:       Optional[Any]       =				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:
                    UpperCAmelCase_							:       Tuple       =				torch.load(lowerCamelCase_     ,					map_location='cpu'       )
     else:
          UpperCAmelCase_							:       int       =				torch.load(args.path_to_checkpoint     ,					map_location='cpu'       )

     UpperCAmelCase_							:       Union[str, Any]       =				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:
                    UpperCAmelCase_							:       str       =				'gelu_fast'
               elif ds_args.openai_gelu:
                    UpperCAmelCase_							:       Tuple       =				'gelu_new'
               else:
                    UpperCAmelCase_							:       List[str]       =				'gelu'
          else:
               # in the very early days this used to be "gelu_new"
               UpperCAmelCase_							:       Optional[int]       =				'gelu_new'

          # Spell out all parameters in case the defaults change.
          UpperCAmelCase_							:       List[str]       =				GPTaConfig(
              vocab_size=50257     ,					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=50256     ,					eos_token_id=50256     ,					)
     else:
          UpperCAmelCase_							:       Any       =				GPTaConfig.from_json_file(args.config_file       )

     UpperCAmelCase_							:       Any       =				['GPT2LMHeadModel']

     # Convert.
     print('Converting'       )
     UpperCAmelCase_							:       Tuple       =				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:
          UpperCAmelCase_							:       str       =				ds_args.tokenizer_type
          if tokenizer_type == "GPT2BPETokenizer":
               UpperCAmelCase_							:       Dict       =				'gpt2'
          elif tokenizer_type == "PretrainedFromHF":
               UpperCAmelCase_							:       Optional[int]       =				ds_args.tokenizer_name_or_path
          else:
               raise ValueError(F'''Unrecognized tokenizer_type {tokenizer_type}'''       )
     else:
          UpperCAmelCase_							:       Any       =				'gpt2'

     UpperCAmelCase_							:       Optional[Any]       =				AutoTokenizer.from_pretrained(lowerCamelCase_       )
     UpperCAmelCase_							:       Tuple       =				type(lowerCamelCase_       ).__name__
     UpperCAmelCase_							:       int       =				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.
     UpperCAmelCase_							:       Optional[int]       =				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 numpy as np
import torch
from torch.nn import CrossEntropyLoss
from transformers import AutoModelForCausalLM, AutoTokenizer

import datasets
from datasets import logging


snake_case__					:      str				      =  '''\

'''

snake_case__					:      Union[str, Any]				      =  '''
Perplexity (PPL) is one of the most common metrics for evaluating language models.
It is defined as the exponentiated average negative log-likelihood of a sequence.

For more information, see https://huggingface.co/docs/transformers/perplexity
'''

snake_case__					:      str				      =  '''
Args:
    model_id (str): model used for calculating Perplexity
            NOTE: Perplexity can only be calculated for causal language models.
                    This includes models such as gpt2, causal variations of bert,
                    causal versions of t5, and more (the full list can be found
                    in the AutoModelForCausalLM documentation here:
                    https://huggingface.co/docs/transformers/master/en/model_doc/auto#transformers.AutoModelForCausalLM )

    input_texts (list of str): input text, each separate text snippet
        is one list entry.
    batch_size (int): the batch size to run texts through the model. Defaults to 16.
    add_start_token (bool): whether to add the start token to the texts,
        so the perplexity can include the probability of the first word. Defaults to True.
    device (str): device to run on, defaults to \'cuda\' when available
Returns:
    perplexity: dictionary containing the perplexity scores for the texts
        in the input list, as well as the mean perplexity. If one of the input texts is
        longer than the max input length of the model, then it is truncated to the
        max length for the perplexity computation.
Examples:
    Example 1:
        >>> perplexity = datasets.load_metric("perplexity")
        >>> input_texts = ["lorem ipsum", "Happy Birthday!", "Bienvenue"]
        >>> results = perplexity.compute(model_id=\'gpt2\',
        ...                              add_start_token=False,
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        [\'perplexities\', \'mean_perplexity\']
        >>> print(round(results["mean_perplexity"], 2))
        78.22
        >>> print(round(results["perplexities"][0], 2))
        11.11

    Example 2:
        >>> perplexity = datasets.load_metric("perplexity")
        >>> input_texts = datasets.load_dataset("wikitext",
        ...                                     "wikitext-2-raw-v1",
        ...                                     split="test")["text"][:50] # doctest:+ELLIPSIS
        [...]
        >>> input_texts = [s for s in input_texts if s!=\'\']
        >>> results = perplexity.compute(model_id=\'gpt2\',
        ...                              input_texts=input_texts) # doctest:+ELLIPSIS
        >>> print(list(results.keys()))
        [\'perplexities\', \'mean_perplexity\']
        >>> print(round(results["mean_perplexity"], 2))
        60.35
        >>> print(round(results["perplexities"][0], 2))
        81.12
'''






@datasets.utils.file_utils.add_start_docstrings(_DESCRIPTION						,     _KWARGS_DESCRIPTION	)
class 					__SCREAMING_SNAKE_CASE						(	datasets.Metric	):







  '''simple docstring'''






  def _UpperCamelCase					(			self						):




       '''simple docstring'''

       return datasets.MetricInfo(
           description=_DESCRIPTION				,		citation=_CITATION				,		inputs_description=_KWARGS_DESCRIPTION				,		features=datasets.Features(
               {
                   'input_texts': datasets.Value('string'						),
               }						)				,		reference_urls=['https://huggingface.co/docs/transformers/perplexity']				,		)






  def _UpperCamelCase					(			self				,		snake_case_				,		snake_case_				,		snake_case_ = 1_6				,		snake_case_ = True				,		snake_case_=None						):




       '''simple docstring'''

       if device is not None:
            assert device in ["gpu", "cpu", "cuda"], "device should be either gpu or cpu."
            if device == "gpu":
                 UpperCAmelCase_							:       int       =				'cuda'
       else:
            UpperCAmelCase_							:       Union[str, Any]       =				'cuda' if torch.cuda.is_available() else 'cpu'

       UpperCAmelCase_							:       Tuple       =				AutoModelForCausalLM.from_pretrained(snake_case_						)
       UpperCAmelCase_							:       Dict       =				model.to(snake_case_						)

       UpperCAmelCase_							:       Dict       =				AutoTokenizer.from_pretrained(snake_case_						)

       # if batch_size > 1 (which generally leads to padding being required), and
       # if there is not an already assigned pad_token, assign an existing
       # special token to also be the padding token
       if tokenizer.pad_token is None and batch_size > 1:
            UpperCAmelCase_							:       Any       =				list(tokenizer.special_tokens_map_extended.values()						)
            # check that the model already has at least one special token defined
            assert (
                len(snake_case_						) > 0
            ), "If batch_size > 1, model must have at least one special token to use for padding. Please use a different model or set batch_size=1."
            # assign one of the special tokens to also be the pad token
            tokenizer.add_special_tokens({'pad_token': existing_special_tokens[0]}						)

       if add_start_token:
            # leave room for <BOS> token to be added:
            assert (
                tokenizer.bos_token is not None
            ), "Input model must already have a BOS token if using add_start_token=True. Please use a different model, or set add_start_token=False"
            UpperCAmelCase_							:       Union[str, Any]       =				model.config.max_length - 1
       else:
            UpperCAmelCase_							:       int       =				model.config.max_length

       UpperCAmelCase_							:       List[str]       =				tokenizer(
           snake_case_				,		add_special_tokens=snake_case_				,		padding=snake_case_				,		truncation=snake_case_				,		max_length=snake_case_				,		return_tensors='pt'				,		return_attention_mask=snake_case_				,		).to(snake_case_						)

       UpperCAmelCase_							:       Tuple       =				encodings['input_ids']
       UpperCAmelCase_							:       Optional[int]       =				encodings['attention_mask']

       # check that each input is long enough:
       if add_start_token:
            assert torch.all(torch.ge(attn_masks.sum(1						)				,		1						)						), "Each input text must be at least one token long."
       else:
            assert torch.all(
                torch.ge(attn_masks.sum(1						)				,		2						)						), "When add_start_token=False, each input text must be at least two tokens long. Run with add_start_token=True if inputting strings of only one token, and remove all empty input strings."

       UpperCAmelCase_							:       Union[str, Any]       =				[]
       UpperCAmelCase_							:       Optional[int]       =				CrossEntropyLoss(reduction='none'						)

       for start_index in logging.tqdm(range(0				,		len(snake_case_						)				,		snake_case_						)						):
            UpperCAmelCase_							:       Union[str, Any]       =				min(start_index + batch_size				,		len(snake_case_						)						)
            UpperCAmelCase_							:       List[Any]       =				encoded_texts[start_index:end_index]
            UpperCAmelCase_							:       Tuple       =				attn_masks[start_index:end_index]

            if add_start_token:
                 UpperCAmelCase_							:       List[str]       =				torch.tensor([[tokenizer.bos_token_id]] * encoded_batch.size(dim=0						)						).to(snake_case_						)
                 UpperCAmelCase_							:       Any       =				torch.cat([bos_tokens_tensor, encoded_batch]				,		dim=1						)
                 UpperCAmelCase_							:       List[Any]       =				torch.cat(
                     [torch.ones(bos_tokens_tensor.size()				,		dtype=torch.intaa						).to(snake_case_						), attn_mask]				,		dim=1						)

            UpperCAmelCase_							:       List[Any]       =				encoded_batch

            with torch.no_grad():
                 UpperCAmelCase_							:       int       =				model(snake_case_				,		attention_mask=snake_case_						).logits

            UpperCAmelCase_							:       Any       =				out_logits[..., :-1, :].contiguous()
            UpperCAmelCase_							:       Dict       =				labels[..., 1:].contiguous()
            UpperCAmelCase_							:       Union[str, Any]       =				attn_mask[..., 1:].contiguous()

            UpperCAmelCase_							:       List[Any]       =				torch.expa(
                (loss_fct(shift_logits.transpose(1				,		2						)				,		snake_case_						) * shift_attention_mask_batch).sum(1						)
                / shift_attention_mask_batch.sum(1						)						)

            ppls += perplexity_batch.tolist()

       return {"perplexities": ppls, "mean_perplexity": np.mean(snake_case_						)}






