





"""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_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    a__       (       _SCREAMING_SNAKE_CASE	,						_SCREAMING_SNAKE_CASE	,						_SCREAMING_SNAKE_CASE=0     ):




		"""simple docstring"""


		if name is None:
				UpperCamelCase =						None
		else:
				UpperCamelCase =						"." * max(0	,						spaces - 2     ) + "# {:" + str(50 - spaces     ) + "s}"
				UpperCamelCase =						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    a__       (       _SCREAMING_SNAKE_CASE	,						_SCREAMING_SNAKE_CASE	,						_SCREAMING_SNAKE_CASE	,						_SCREAMING_SNAKE_CASE	,						_SCREAMING_SNAKE_CASE     ):




		"""simple docstring"""


		UpperCamelCase =						param.size()
		if checkpoint_version == 1.0:
				# version 1.0 stores [num_heads * hidden_size * num_splits, :]
				UpperCamelCase =						(num_heads, hidden_size, num_splits) + input_shape[1:]
				UpperCamelCase =						param.view(*_SCREAMING_SNAKE_CASE     )
				UpperCamelCase =						param.transpose(0	,						2     )
				UpperCamelCase =						param.transpose(1	,						2     ).contiguous()
		elif checkpoint_version >= 2.0:
				# other versions store [num_heads * num_splits * hidden_size, :]
				UpperCamelCase =						(num_heads, num_splits, hidden_size) + input_shape[1:]
				UpperCamelCase =						param.view(*_SCREAMING_SNAKE_CASE     )
				UpperCamelCase =						param.transpose(0	,						1     ).contiguous()
		UpperCamelCase =						param.view(*_SCREAMING_SNAKE_CASE     )
		return param


def    a__       (       _SCREAMING_SNAKE_CASE	,						_SCREAMING_SNAKE_CASE	,						_SCREAMING_SNAKE_CASE     ):




		"""simple docstring"""


		UpperCamelCase =						{}

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

				UpperCamelCase =						ds_args.tokenizer_type
				UpperCamelCase =						ds_args.padded_vocab_size
				UpperCamelCase =						ds_args.max_position_embeddings
				UpperCamelCase =						ds_args.hidden_size
				UpperCamelCase =						ds_args.num_layers
				UpperCamelCase =						ds_args.num_attention_heads
				UpperCamelCase =						ds_args.ffn_hidden_size if "ffn_hidden_size" in ds_args else 4 * ds_args.hidden_size
				# pprint(config)

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

		# The model.
		UpperCamelCase =						input_state_dict["model"]
		# The language model.
		UpperCamelCase =						model["language_model"]
		# The embeddings.
		UpperCamelCase =						lm["embedding"]

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

		# The position embeddings.
		UpperCamelCase =						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.
		UpperCamelCase =						pos_embeddings

		# The token-type embeddings.
		UpperCamelCase =						embeddings["tokentype_embeddings"]["weight"]
		# Store the position embeddings.
		UpperCamelCase =						tokentype_embeddings

		# The transformer.
		UpperCamelCase =						lm["transformer"] if "transformer" in lm.keys() else lm["encoder"]

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

		# The simple map of names for "automated" rules.
		UpperCamelCase =						{
		    "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.
		UpperCamelCase =						None

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

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

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

				# The name of the layer.
				UpperCamelCase =						F"bert.encoder.layer.{layer_idx}"

				# For layernorm(s), simply store the layer norm.
				if op_name.endswith("layernorm"     ):
						UpperCamelCase =						"attention.ln" if op_name.startswith("input"     ) else "ln"
						UpperCamelCase =						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, ""

						UpperCamelCase =						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.
						UpperCamelCase =						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.
						UpperCamelCase =						attention_qkv_weight[0 * config.hidden_size : 1 * config.hidden_size, :]
						UpperCamelCase =						attention_qkv_weight[1 * config.hidden_size : 2 * config.hidden_size, :]
						UpperCamelCase =						attention_qkv_weight[2 * config.hidden_size : 3 * config.hidden_size, :]

						UpperCamelCase =						fix_query_key_value_ordering(_SCREAMING_SNAKE_CASE	,						_SCREAMING_SNAKE_CASE	,						3	,						_SCREAMING_SNAKE_CASE	,						_SCREAMING_SNAKE_CASE     )
						# Split the bias.
						UpperCamelCase =						out_val[0 * config.hidden_size : 1 * config.hidden_size]
						UpperCamelCase =						out_val[1 * config.hidden_size : 2 * config.hidden_size]
						UpperCamelCase =						out_val[2 * config.hidden_size : 3 * config.hidden_size]

						# Store.
						UpperCamelCase =						q
						UpperCamelCase =						q_bias
						UpperCamelCase =						k
						UpperCamelCase =						k_bias
						UpperCamelCase =						v
						UpperCamelCase =						v_bias

						# Clear the stored tensor.
						UpperCamelCase =						None

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

    # The final layernorm.
		UpperCamelCase =						transformer["final_layernorm.weight"]
		UpperCamelCase =						transformer["final_layernorm.bias"]

		# The pooler.
		UpperCamelCase =						lm["pooler"]

		# Store the matrix and the bias.
		UpperCamelCase =						pooler["dense.weight"]
		UpperCamelCase =						pooler["dense.bias"]

		# The LM head from Megatron (for RACE).
		UpperCamelCase =						model["lm_head"]

		# The transform matrix.
		UpperCamelCase =						lm_head["dense.weight"]
		UpperCamelCase =						lm_head["dense.bias"]

		# The transform LN.
		UpperCamelCase =						lm_head["layernorm.weight"]
		UpperCamelCase =						lm_head["layernorm.bias"]

		# For the decoder, we replicate the weights.
		UpperCamelCase =						word_embeddings
		UpperCamelCase =						lm_head["bias"]

		# The classifier from Megatron (for MLNI).
		UpperCamelCase =						model["binary_head"]

		# Store the classifier.
		UpperCamelCase =						binary_head["weight"]
		UpperCamelCase =						binary_head["bias"]

		# It should be done!
		return output_state_dict


def    a__       (       ):




		"""simple docstring"""


		UpperCamelCase =						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."	,						)
		UpperCamelCase =						parser.parse_args()

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

		if args.config_file == "":
				# Default config of megatron-bert 345m
				UpperCamelCase =						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
				UpperCamelCase =						input_state_dict["model"]["lm_head"]["bias"].numel()
		else:
				UpperCamelCase =						MegatronBertConfig.from_json_file(args.config_file     )

		# Convert.
		print("Converting"     )
		UpperCamelCase =						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.
		UpperCamelCase =						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()

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













"""simple docstring"""





import csv
from collections import defaultdict
from dataclasses import dataclass, field
from typing import List, Optional

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import ScalarFormatter

from transformers import HfArgumentParser


def    a__       (       _SCREAMING_SNAKE_CASE=None	,						_SCREAMING_SNAKE_CASE=None     ):




		"""simple docstring"""


		return field(default_factory=lambda: default	,						metadata=_SCREAMING_SNAKE_CASE     )





@dataclass
class 							_lowerCamelCase   :
						UpperCAmelCase_			=      field(
						    metadata={"help": "The csv file to plot."}	,      )
						UpperCAmelCase_			=      field(
						    default=_lowercase	,      metadata={"help": "Whether to plot along batch size or sequence length. Defaults to sequence length."}	,      )
						UpperCAmelCase_			=      field(
						    default=_lowercase	,      metadata={"help": "Whether the csv file has time results or memory results. Defaults to memory results."}	,      )
						UpperCAmelCase_			=      field(
						    default=_lowercase	,      metadata={"help": "Disable logarithmic scale when plotting"}	,      )
						UpperCAmelCase_			=      field(
						    default=_lowercase	,      metadata={
						        "help": "Whether the csv file has training results or inference results. Defaults to inference results."
						    }	,      )
						UpperCAmelCase_			=      field(
						    default=_lowercase	,      metadata={"help": "Filename under which the plot will be saved. If unused no plot is saved."}	,      )
						UpperCAmelCase_			=      list_field(
						    default=_lowercase	,      metadata={"help": "List of model names that are used instead of the ones in the csv file."}			)



def    a__       (       _SCREAMING_SNAKE_CASE     ):




		"""simple docstring"""


		try:
				int(_SCREAMING_SNAKE_CASE     )
				return True
		except ValueError:
				return False


def    a__       (       _SCREAMING_SNAKE_CASE     ):




		"""simple docstring"""


		try:
				float(_SCREAMING_SNAKE_CASE     )
				return True
		except ValueError:
				return False





class 							_lowerCamelCase   :


						def __init__(self ,				__a		)			-> Tuple:
								UpperCamelCase =						args
								UpperCamelCase =						defaultdict(lambda: {"bsz": [], "seq_len": [], "result": {}}		)

								with open(self.args.csv_file ,				newline=""		) as csv_file:
										UpperCamelCase =						csv.DictReader(__a		)
										for row in reader:
												UpperCamelCase =						row["model"]
												self.result_dict[model_name]["bsz"].append(int(row["batch_size"]		)		)
												self.result_dict[model_name]["seq_len"].append(int(row["sequence_length"]		)		)
												if can_convert_to_int(row["result"]		):
														# value is not None
														UpperCamelCase =						int(row["result"]		)
												elif can_convert_to_float(row["result"]		):
														# value is not None
														UpperCamelCase =						float(row["result"]		)




						def      snake_case_ (self		)			-> Optional[int]:
								UpperCamelCase ,					UpperCamelCase =						plt.subplots()
								UpperCamelCase =						"Time usage" if self.args.is_time else "Memory usage"
								UpperCamelCase =						title_str + " for training" if self.args.is_train else title_str + " for inference"

								if not self.args.no_log_scale:
										# set logarithm scales
										ax.set_xscale("log"		)
										ax.set_yscale("log"		)

								for axis in [ax.xaxis, ax.yaxis]:
										axis.set_major_formatter(ScalarFormatter()		)

								for model_name_idx, model_name in enumerate(self.result_dict.keys()		):
										UpperCamelCase =						sorted(set(self.result_dict[model_name]["bsz"]		)		)
										UpperCamelCase =						sorted(set(self.result_dict[model_name]["seq_len"]		)		)
										UpperCamelCase =						self.result_dict[model_name]["result"]

										((UpperCamelCase) ,					(UpperCamelCase)) =						(
										    (batch_sizes, sequence_lengths) if self.args.plot_along_batch else (sequence_lengths, batch_sizes)
										)

										UpperCamelCase =						(
										    model_name if self.args.short_model_names is None else self.args.short_model_names[model_name_idx]
										)

										for inner_loop_value in inner_loop_array:
												if self.args.plot_along_batch:
														UpperCamelCase =						np.asarray(
														    [results[(x, inner_loop_value)] for x in x_axis_array if (x, inner_loop_value) in results] ,				dtype=__a ,				)
												else:
														UpperCamelCase =						np.asarray(
														    [results[(inner_loop_value, x)] for x in x_axis_array if (inner_loop_value, x) in results] ,				dtype=np.floataa ,				)

												((UpperCamelCase) ,					(UpperCamelCase)) =						(
												    ("batch_size", "len") if self.args.plot_along_batch else ("in #tokens", "bsz")
												)

												UpperCamelCase =						np.asarray(__a ,				__a		)[: len(__a		)]
												plt.scatter(
												    __a ,				__a ,				label=F"{label_model_name} - {inner_loop_label}: {inner_loop_value}"		)
												plt.plot(__a ,				__a ,				"--"		)

										title_str += F" {label_model_name} vs."

								UpperCamelCase =						title_str[:-4]
								UpperCamelCase =						"Time in s" if self.args.is_time else "Memory in MB"

								# plot
								plt.title(__a		)
								plt.xlabel(__a		)
								plt.ylabel(__a		)
								plt.legend()

								if self.args.figure_png_file is not None:
										plt.savefig(self.args.figure_png_file		)
								else:
										plt.show()



def    a__       (       ):




		"""simple docstring"""


		UpperCamelCase =						HfArgumentParser(_SCREAMING_SNAKE_CASE     )
		UpperCamelCase =						parser.parse_args_into_dataclasses()[0]
		UpperCamelCase =						Plot(args=_SCREAMING_SNAKE_CASE     )
		plot.plot()


if __name__ == "__main__":
						main()






