
import argparse
import logging
import os
from pathlib import Path
from typing import Any, Dict

import pytorch_lightning as pl
from pytorch_lightning.utilities import rank_zero_info

from transformers import (
    AdamW,
    AutoConfig,
    AutoModel,
    AutoModelForPreTraining,
    AutoModelForQuestionAnswering,
    AutoModelForSeqaSeqLM,
    AutoModelForSequenceClassification,
    AutoModelForTokenClassification,
    AutoModelWithLMHead,
    AutoTokenizer,
    PretrainedConfig,
    PreTrainedTokenizer,
)
from transformers.optimization import (
    Adafactor,
    get_cosine_schedule_with_warmup,
    get_cosine_with_hard_restarts_schedule_with_warmup,
    get_linear_schedule_with_warmup,
    get_polynomial_decay_schedule_with_warmup,
)
from transformers.utils.versions import require_version


lowercase_		=							logging.getLogger(__name__)

require_version('''pytorch_lightning>=1.0.4''')

lowercase_		=							{
    '''base''': AutoModel,
    '''sequence-classification''': AutoModelForSequenceClassification,
    '''question-answering''': AutoModelForQuestionAnswering,
    '''pretraining''': AutoModelForPreTraining,
    '''token-classification''': AutoModelForTokenClassification,
    '''language-modeling''': AutoModelWithLMHead,
    '''summarization''': AutoModelForSeqaSeqLM,
    '''translation''': AutoModelForSeqaSeqLM,
}


# update this and the import above to support new schedulers from transformers.optimization
lowercase_		=							{
    '''linear''': get_linear_schedule_with_warmup,
    '''cosine''': get_cosine_schedule_with_warmup,
    '''cosine_w_restarts''': get_cosine_with_hard_restarts_schedule_with_warmup,
    '''polynomial''': get_polynomial_decay_schedule_with_warmup,
    # '': get_constant_schedule,             # not supported for now
    # '': get_constant_schedule_with_warmup, # not supported for now
}
lowercase_		=							sorted(arg_to_scheduler.keys())
lowercase_		=							'''{''' + ''', '''.join(arg_to_scheduler_choices) + '''}'''





class 		A__    (       pl.LightningModule			):






	def __init__(     self    ,					lowerCamelCase    ,					lowerCamelCase=None    ,					lowerCamelCase="base"    ,					lowerCamelCase=None    ,					lowerCamelCase=None    ,					lowerCamelCase=None    ,					**lowerCamelCase    ,					)				->       Any:




						"""simple docstring"""






						super().__init__()
						# TODO: move to self.save_hyperparameters()
						# self.save_hyperparameters()
						# can also expand arguments into trainer signature for easier reading

						self.save_hyperparameters(lowerCamelCase						)
						__magic_name__ :							Union[str, Any]		       =							0
						__magic_name__ :							List[str]		       =							Path(self.hparams.output_dir						)
						__magic_name__ :							Any		       =							self.hparams.cache_dir if self.hparams.cache_dir else None
						if config is None:
											__magic_name__ :							Union[str, Any]		       =							AutoConfig.from_pretrained(
											    self.hparams.config_name if self.hparams.config_name else self.hparams.model_name_or_path    ,					**({'''num_labels''': num_labels} if num_labels is not None else {})    ,					cache_dir=lowerCamelCase    ,					**lowerCamelCase    ,					)
						else:
											__magic_name__ :							PretrainedConfig		       =							config

						__magic_name__ :							List[Any]		       =							('''encoder_layerdrop''', '''decoder_layerdrop''', '''dropout''', '''attention_dropout''')
						for p in extra_model_params:
											if getattr(self.hparams    ,					lowerCamelCase    ,					lowerCamelCase						):
																assert hasattr(self.config    ,					lowerCamelCase						), F'''model config doesn\'t have a `{p}` attribute'''
																setattr(self.config    ,					lowerCamelCase    ,					getattr(self.hparams    ,					lowerCamelCase						)						)

						if tokenizer is None:
											__magic_name__ :							int		       =							AutoTokenizer.from_pretrained(
											    self.hparams.tokenizer_name if self.hparams.tokenizer_name else self.hparams.model_name_or_path    ,					cache_dir=lowerCamelCase    ,					)
						else:
											__magic_name__ :							PreTrainedTokenizer		       =							tokenizer
						__magic_name__ :							Union[str, Any]		       =							MODEL_MODES[mode]
						if model is None:
											__magic_name__ :							Dict		       =							self.model_type.from_pretrained(
											    self.hparams.model_name_or_path    ,					from_tf=bool('''.ckpt''' in self.hparams.model_name_or_path						)    ,					config=self.config    ,					cache_dir=lowerCamelCase    ,					)
						else:
											__magic_name__ :							List[str]		       =							model






	def 			lowercase				(     self    ,					*lowerCamelCase    ,					**lowerCamelCase						)				->       List[str]:




						"""simple docstring"""






						__magic_name__ :							Union[str, Any]		       =							self.model_type.from_pretrained(*lowerCamelCase    ,					**lowerCamelCase						)






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




						"""simple docstring"""






						__magic_name__ :							Dict		       =							arg_to_scheduler[self.hparams.lr_scheduler]
						__magic_name__ :							Dict		       =							get_schedule_func(
						    self.opt    ,					num_warmup_steps=self.hparams.warmup_steps    ,					num_training_steps=self.total_steps()						)
						__magic_name__ :							List[str]		       =							{'''scheduler''': scheduler, '''interval''': '''step''', '''frequency''': 1}
						return scheduler






	def 			lowercase				(     self						)				->       Any:




						"""simple docstring"""






						__magic_name__ :							List[str]		       =							self.model
						__magic_name__ :							List[Any]		       =							['''bias''', '''LayerNorm.weight''']
						__magic_name__ :							Any		       =							[
						    {
						        '''params''': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay						)],
						        '''weight_decay''': self.hparams.weight_decay,
						    },
						    {
						        '''params''': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay						)],
						        '''weight_decay''': 0.0,
						    },
						]
						if self.hparams.adafactor:
											__magic_name__ :							Tuple		       =							Adafactor(
											    lowerCamelCase    ,					lr=self.hparams.learning_rate    ,					scale_parameter=lowerCamelCase    ,					relative_step=lowerCamelCase						)

						else:
											__magic_name__ :							Dict		       =							AdamW(
											    lowerCamelCase    ,					lr=self.hparams.learning_rate    ,					eps=self.hparams.adam_epsilon						)
						__magic_name__ :							List[Any]		       =							optimizer

						__magic_name__ :							Tuple		       =							self.get_lr_scheduler()

						return [optimizer], [scheduler]






	def 			lowercase				(     self    ,					lowerCamelCase    ,					lowerCamelCase						)				->       Dict:




						"""simple docstring"""






						return self.validation_step(lowerCamelCase    ,					lowerCamelCase						)






	def 			lowercase				(     self    ,					lowerCamelCase						)				->       Optional[int]:




						"""simple docstring"""






						return self.validation_end(lowerCamelCase						)






	def 			lowercase				(     self						)				->       int:




						"""simple docstring"""






						__magic_name__ :							List[Any]		       =							max(1    ,					self.hparams.gpus						)  # TODO: consider num_tpu_cores
						__magic_name__ :							Union[str, Any]		       =							self.hparams.train_batch_size * self.hparams.accumulate_grad_batches * num_devices
						return (self.dataset_size / effective_batch_size) * self.hparams.max_epochs






	def 			lowercase				(     self    ,					lowerCamelCase						)				->       List[Any]:




						"""simple docstring"""






						if mode == "test":
											__magic_name__ :							Any		       =							len(self.test_dataloader().dataset						)
						else:
											__magic_name__ :							Optional[int]		       =							self.get_dataloader('''train'''    ,					self.hparams.train_batch_size    ,					shuffle=lowerCamelCase						)
											__magic_name__ :							Union[str, Any]		       =							len(self.train_dataloader().dataset						)






	def 			lowercase				(     self    ,					lowerCamelCase    ,					lowerCamelCase    ,					lowerCamelCase = False						)				->       Any:




						"""simple docstring"""






						raise NotImplementedError('''You must implement this for your task'''						)






	def 			lowercase				(     self						)				->       Union[str, Any]:




						"""simple docstring"""






						return self.train_loader






	def 			lowercase				(     self						)				->       str:




						"""simple docstring"""






						return self.get_dataloader('''dev'''    ,					self.hparams.eval_batch_size    ,					shuffle=lowerCamelCase						)






	def 			lowercase				(     self						)				->       Dict:




						"""simple docstring"""






						return self.get_dataloader('''test'''    ,					self.hparams.eval_batch_size    ,					shuffle=lowerCamelCase						)






	def 			lowercase				(     self    ,					lowerCamelCase						)				->       Tuple:




						"""simple docstring"""






						return os.path.join(
						    self.hparams.data_dir    ,					'''cached_{}_{}_{}'''.format(
						        lowerCamelCase    ,					list(filter(lowerCamelCase    ,					self.hparams.model_name_or_path.split('''/'''						)						)						).pop()    ,					str(self.hparams.max_seq_length						)    ,					)    ,					)






	@pl.utilities.rank_zero_only
	def 			lowercase				(     self    ,					lowerCamelCase						)				->       None:




						"""simple docstring"""






						__magic_name__ :							Optional[Any]		       =							self.output_dir.joinpath('''best_tfmr'''						)
						__magic_name__ :							List[Any]		       =							self.step_count
						self.model.save_pretrained(lowerCamelCase						)
						self.tokenizer.save_pretrained(lowerCamelCase						)






	@staticmethod
	def 			lowercase				(     lowerCamelCase    ,					lowerCamelCase						)				->       Optional[Any]:




						"""simple docstring"""






						parser.add_argument(
						    '''--model_name_or_path'''    ,					default=lowerCamelCase    ,					type=lowerCamelCase    ,					required=lowerCamelCase    ,					help='''Path to pretrained model or model identifier from huggingface.co/models'''    ,					)
						parser.add_argument(
						    '''--config_name'''    ,					default=''''''    ,					type=lowerCamelCase    ,					help='''Pretrained config name or path if not the same as model_name'''						)
						parser.add_argument(
						    '''--tokenizer_name'''    ,					default=lowerCamelCase    ,					type=lowerCamelCase    ,					help='''Pretrained tokenizer name or path if not the same as model_name'''    ,					)
						parser.add_argument(
						    '''--cache_dir'''    ,					default=''''''    ,					type=lowerCamelCase    ,					help='''Where do you want to store the pre-trained models downloaded from huggingface.co'''    ,					)
						parser.add_argument(
						    '''--encoder_layerdrop'''    ,					type=lowerCamelCase    ,					help='''Encoder layer dropout probability (Optional). Goes into model.config'''    ,					)
						parser.add_argument(
						    '''--decoder_layerdrop'''    ,					type=lowerCamelCase    ,					help='''Decoder layer dropout probability (Optional). Goes into model.config'''    ,					)
						parser.add_argument(
						    '''--dropout'''    ,					type=lowerCamelCase    ,					help='''Dropout probability (Optional). Goes into model.config'''    ,					)
						parser.add_argument(
						    '''--attention_dropout'''    ,					type=lowerCamelCase    ,					help='''Attention dropout probability (Optional). Goes into model.config'''    ,					)
						parser.add_argument('''--learning_rate'''    ,					default=5e-5    ,					type=lowerCamelCase    ,					help='''The initial learning rate for Adam.'''						)
						parser.add_argument(
						    '''--lr_scheduler'''    ,					default='''linear'''    ,					choices=lowerCamelCase    ,					metavar=lowerCamelCase    ,					type=lowerCamelCase    ,					help='''Learning rate scheduler'''    ,					)
						parser.add_argument('''--weight_decay'''    ,					default=0.0    ,					type=lowerCamelCase    ,					help='''Weight decay if we apply some.'''						)
						parser.add_argument('''--adam_epsilon'''    ,					default=1e-8    ,					type=lowerCamelCase    ,					help='''Epsilon for Adam optimizer.'''						)
						parser.add_argument('''--warmup_steps'''    ,					default=0    ,					type=lowerCamelCase    ,					help='''Linear warmup over warmup_steps.'''						)
						parser.add_argument('''--num_workers'''    ,					default=4    ,					type=lowerCamelCase    ,					help='''kwarg passed to DataLoader'''						)
						parser.add_argument('''--num_train_epochs'''    ,					dest='''max_epochs'''    ,					default=3    ,					type=lowerCamelCase						)
						parser.add_argument('''--train_batch_size'''    ,					default=32    ,					type=lowerCamelCase						)
						parser.add_argument('''--eval_batch_size'''    ,					default=32    ,					type=lowerCamelCase						)
						parser.add_argument('''--adafactor'''    ,					action='''store_true'''						)





class 		A__    (       pl.Callback			):






	def 			lowercase				(     self    ,					lowerCamelCase    ,					lowerCamelCase						)				->       str:




						"""simple docstring"""






						__magic_name__ :							int		       =							trainer.lr_schedulers[0]['''scheduler''']
						__magic_name__ :							int		       =							{F'''lr_group_{i}''': lr for i, lr in enumerate(lr_scheduler.get_lr()						)}
						pl_module.logger.log_metrics(lowerCamelCase						)






	def 			lowercase				(     self    ,					lowerCamelCase    ,					lowerCamelCase						)				->       Optional[Any]:




						"""simple docstring"""






						rank_zero_info('''***** Validation results *****'''						)
						__magic_name__ :							Optional[int]		       =							trainer.callback_metrics
						# Log results
						for key in sorted(lowerCamelCase						):
											if key not in ["log", "progress_bar"]:
																rank_zero_info('''{} = {}\n'''.format(lowerCamelCase    ,					str(metrics[key]						)						)						)






	def 			lowercase				(     self    ,					lowerCamelCase    ,					lowerCamelCase						)				->       Any:




						"""simple docstring"""






						rank_zero_info('''***** Test results *****'''						)
						__magic_name__ :							Tuple		       =							trainer.callback_metrics
						# Log and save results to file
						__magic_name__ :							int		       =							os.path.join(pl_module.hparams.output_dir    ,					'''test_results.txt'''						)
						with open(lowerCamelCase    ,					'''w'''						) as writer:
											for key in sorted(lowerCamelCase						):
																if key not in ["log", "progress_bar"]:
																					rank_zero_info('''{} = {}\n'''.format(lowerCamelCase    ,					str(metrics[key]						)						)						)
																					writer.write('''{} = {}\n'''.format(lowerCamelCase    ,					str(metrics[key]						)						)						)







def 			lowerCAmelCase  (     UpperCAmelCase,     UpperCAmelCase	)  ->None:






					"""simple docstring"""






					parser.add_argument(
					    '''--output_dir''',     default=UpperCAmelCase,     type=UpperCAmelCase,     required=UpperCAmelCase,     help='''The output directory where the model predictions and checkpoints will be written.''',     )
					parser.add_argument(
					    '''--fp16''',     action='''store_true''',     help='''Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit''',     )

					parser.add_argument(
					    '''--fp16_opt_level''',     type=UpperCAmelCase,     default='''O2''',     help=(
					        '''For fp16: Apex AMP optimization level selected in [\'O0\', \'O1\', \'O2\', and \'O3\'].'''
					        '''See details at https://nvidia.github.io/apex/amp.html'''
					    ),     )
					parser.add_argument('''--n_tpu_cores''',     dest='''tpu_cores''',     type=UpperCAmelCase	)
					parser.add_argument('''--max_grad_norm''',     dest='''gradient_clip_val''',     default=1.0,     type=UpperCAmelCase,     help='''Max gradient norm'''	)
					parser.add_argument('''--do_train''',     action='''store_true''',     help='''Whether to run training.'''	)
					parser.add_argument('''--do_predict''',     action='''store_true''',     help='''Whether to run predictions on the test set.'''	)
					parser.add_argument(
					    '''--gradient_accumulation_steps''',     dest='''accumulate_grad_batches''',     type=UpperCAmelCase,     default=1,     help='''Number of updates steps to accumulate before performing a backward/update pass.''',     )
					parser.add_argument('''--seed''',     type=UpperCAmelCase,     default=42,     help='''random seed for initialization'''	)
					parser.add_argument(
					    '''--data_dir''',     default=UpperCAmelCase,     type=UpperCAmelCase,     required=UpperCAmelCase,     help='''The input data dir. Should contain the training files for the CoNLL-2003 NER task.''',     )







def 			lowerCAmelCase  (     UpperCAmelCase,     UpperCAmelCase,     UpperCAmelCase=None,     UpperCAmelCase=True,     UpperCAmelCase=[],     UpperCAmelCase=None,     UpperCAmelCase=None,     **UpperCAmelCase,     )  ->Dict:






					"""simple docstring"""






					pl.seed_everything(args.seed	)

					# init model
					__magic_name__ :							Dict		       =							Path(model.hparams.output_dir	)
					odir.mkdir(exist_ok=UpperCAmelCase	)

					# add custom checkpoints
					if checkpoint_callback is None:
										__magic_name__ :							int		       =							pl.callbacks.ModelCheckpoint(
										    filepath=args.output_dir,     prefix='''checkpoint''',     monitor='''val_loss''',     mode='''min''',     save_top_k=1	)
					if early_stopping_callback:
										extra_callbacks.append(UpperCAmelCase	)
					if logging_callback is None:
										__magic_name__ :							Optional[int]		       =							LoggingCallback()

					__magic_name__ :							str		       =							{}

					# TODO: remove with PyTorch 1.6 since pl uses native amp
					if args.fpaa:
										__magic_name__ :							str		       =							16
										__magic_name__ :							List[Any]		       =							args.fpaa_opt_level

					if args.gpus > 1:
										__magic_name__ :							List[Any]		       =							'''ddp'''

					__magic_name__ :							List[str]		       =							args.accumulate_grad_batches
					__magic_name__ :							List[str]		       =							extra_train_kwargs.get('''accelerator''',     UpperCAmelCase	)
					__magic_name__ :							Any		       =							extra_train_kwargs.get('''profiler''',     UpperCAmelCase	)

					__magic_name__ :							Optional[Any]		       =							pl.Trainer.from_argparse_args(
					    UpperCAmelCase,     weights_summary=UpperCAmelCase,     callbacks=[logging_callback] + extra_callbacks,     logger=UpperCAmelCase,     checkpoint_callback=UpperCAmelCase,     **UpperCAmelCase,     )

					if args.do_train:
										trainer.fit(UpperCAmelCase	)

					return trainer









# 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 			lowerCAmelCase  (     UpperCAmelCase,     UpperCAmelCase,     UpperCAmelCase=0	)  ->Union[str, Any]:






					"""simple docstring"""






					if name is None:
										__magic_name__ :							Tuple		       =							None
					else:
										__magic_name__ :							Any		       =							'''.''' * max(0,     spaces - 2	) + '''# {:''' + str(50 - spaces	) + '''s}'''
										__magic_name__ :							int		       =							fmt.format(UpperCAmelCase	)

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







def 			lowerCAmelCase  (     UpperCAmelCase,     UpperCAmelCase,     UpperCAmelCase,     UpperCAmelCase,     UpperCAmelCase	)  ->Any:






					"""simple docstring"""






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







def 			lowerCAmelCase  (     UpperCAmelCase,     UpperCAmelCase,     UpperCAmelCase	)  ->Dict:






					"""simple docstring"""






					__magic_name__ :							Any		       =							{}

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

										__magic_name__ :							Dict		       =							ds_args.tokenizer_type
										__magic_name__ :							Tuple		       =							ds_args.padded_vocab_size
										__magic_name__ :							Optional[int]		       =							ds_args.max_position_embeddings
										__magic_name__ :							List[Any]		       =							ds_args.hidden_size
										__magic_name__ :							Dict		       =							ds_args.num_layers
										__magic_name__ :							Optional[int]		       =							ds_args.num_attention_heads
										__magic_name__ :							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.
					__magic_name__ :							Union[str, Any]		       =							config.num_attention_heads
					# The hidden_size per head.
					__magic_name__ :							Union[str, Any]		       =							config.hidden_size // heads
					# Megatron-LM checkpoint version
					if "checkpoint_version" in input_state_dict.keys():
										__magic_name__ :							Optional[Any]		       =							input_state_dict['''checkpoint_version''']
					else:
										__magic_name__ :							Tuple		       =							0.0

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

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

					# The position embeddings.
					__magic_name__ :							str		       =							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.
					__magic_name__ :							Optional[Any]		       =							pos_embeddings

					# The token-type embeddings.
					__magic_name__ :							int		       =							embeddings['''tokentype_embeddings''']['''weight''']
					# Store the position embeddings.
					__magic_name__ :							Tuple		       =							tokentype_embeddings

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

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

					# The simple map of names for "automated" rules.
					__magic_name__ :							Union[str, Any]		       =							{
					    '''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.
					__magic_name__ :							Optional[Any]		       =							None

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

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

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

										# The name of the layer.
										__magic_name__ :							List[Any]		       =							F'''bert.encoder.layer.{layer_idx}'''

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

															__magic_name__ :							Any		       =							fix_query_key_value_ordering(UpperCAmelCase,     UpperCAmelCase,     3,     UpperCAmelCase,     UpperCAmelCase	)
															# Store the tensor as we need the bias as well to interleave QKV and biases.
															__magic_name__ :							str		       =							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.
															__magic_name__ :							List[str]		       =							attention_qkv_weight[0 * config.hidden_size : 1 * config.hidden_size, :]
															__magic_name__ :							str		       =							attention_qkv_weight[1 * config.hidden_size : 2 * config.hidden_size, :]
															__magic_name__ :							Optional[Any]		       =							attention_qkv_weight[2 * config.hidden_size : 3 * config.hidden_size, :]

															__magic_name__ :							str		       =							fix_query_key_value_ordering(UpperCAmelCase,     UpperCAmelCase,     3,     UpperCAmelCase,     UpperCAmelCase	)
															# Split the bias.
															__magic_name__ :							Optional[int]		       =							out_val[0 * config.hidden_size : 1 * config.hidden_size]
															__magic_name__ :							str		       =							out_val[1 * config.hidden_size : 2 * config.hidden_size]
															__magic_name__ :							List[str]		       =							out_val[2 * config.hidden_size : 3 * config.hidden_size]

															# Store.
															__magic_name__ :							str		       =							q
															__magic_name__ :							List[Any]		       =							q_bias
															__magic_name__ :							List[str]		       =							k
															__magic_name__ :							Optional[Any]		       =							k_bias
															__magic_name__ :							Union[str, Any]		       =							v
															__magic_name__ :							str		       =							v_bias

															# Clear the stored tensor.
															__magic_name__ :							List[str]		       =							None

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

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

					# The pooler.
					__magic_name__ :							List[Any]		       =							lm['''pooler''']

					# Store the matrix and the bias.
					__magic_name__ :							Tuple		       =							pooler['''dense.weight''']
					__magic_name__ :							str		       =							pooler['''dense.bias''']

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

					# The transform matrix.
					__magic_name__ :							Optional[int]		       =							lm_head['''dense.weight''']
					__magic_name__ :							int		       =							lm_head['''dense.bias''']

					# The transform LN.
					__magic_name__ :							str		       =							lm_head['''layernorm.weight''']
					__magic_name__ :							Any		       =							lm_head['''layernorm.bias''']

					# For the decoder, we replicate the weights.
					__magic_name__ :							int		       =							word_embeddings
					__magic_name__ :							Tuple		       =							lm_head['''bias''']

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

					# Store the classifier.
					__magic_name__ :							Union[str, Any]		       =							binary_head['''weight''']
					__magic_name__ :							List[str]		       =							binary_head['''bias''']

					# It should be done!
					return output_state_dict







def 			lowerCAmelCase  (     )  ->Optional[int]:






					"""simple docstring"""






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

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

					if args.config_file == "":
										# Default config of megatron-bert 345m
										__magic_name__ :							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
										__magic_name__ :							Optional[int]		       =							input_state_dict['''model''']['''lm_head''']['''bias'''].numel()
					else:
										__magic_name__ :							Union[str, Any]		       =							MegatronBertConfig.from_json_file(args.config_file	)

					# Convert.
					print('''Converting'''	)
					__magic_name__ :							List[Any]		       =							convert_megatron_checkpoint(UpperCAmelCase,     UpperCAmelCase,     UpperCAmelCase	)

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

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

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


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

if __name__ == "__main__":
				main()

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



