
# 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			(					lowerCamelCase_:  Any				,	lowerCamelCase_:  Tuple				,	lowerCamelCase_:  str=0		):



				'''simple docstring'''







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



				'''simple docstring'''







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





def 							_lowerCamelCase			(					lowerCamelCase_:  Optional[Any]				,	lowerCamelCase_:  Tuple				,	lowerCamelCase_:  List[Any]		):



				'''simple docstring'''







				A     :  Any   =				{}

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

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

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

				# The word embeddings.
				A     :  Optional[Any]   =				embeddings['''word_embeddings''']['''weight''']
				# Truncate the embedding table to vocab_size rows.
				A     :  str   =				word_embeddings[: config.vocab_size, :]
				# Store the word embeddings.
				A     :  Union[str, Any]   =				word_embeddings

				# The position embeddings.
				A     :  List[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.
				A     :  Optional[int]   =				pos_embeddings

				# The token-type embeddings.
				A     :  Optional[int]   =				embeddings['''tokentype_embeddings''']['''weight''']
				# Store the position embeddings.
				A     :  List[Any]   =				tokentype_embeddings

				# The transformer.
				A     :  Optional[Any]   =				lm['''transformer'''] if '''transformer''' in lm.keys() else lm['''encoder''']

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

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

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

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

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

								# The name of the layer.
								A     :  Optional[Any]   =				f"""bert.encoder.layer.{layer_idx}"""

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

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

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

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

												# Clear the stored tensor.
												A     :  Optional[Any]   =				None

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

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

				# The pooler.
				A     :  Optional[int]   =				lm['''pooler''']

				# Store the matrix and the bias.
				A     :  List[Any]   =				pooler['''dense.weight''']
				A     :  List[Any]   =				pooler['''dense.bias''']

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

				# The transform matrix.
				A     :  List[Any]   =				lm_head['''dense.weight''']
				A     :  int   =				lm_head['''dense.bias''']

				# The transform LN.
				A     :  Tuple   =				lm_head['''layernorm.weight''']
				A     :  Optional[int]   =				lm_head['''layernorm.bias''']

				# For the decoder, we replicate the weights.
				A     :  Optional[Any]   =				word_embeddings
				A     :  str   =				lm_head['''bias''']

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

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

				# It should be done!
				return output_state_dict





def 							_lowerCamelCase			(					):



				'''simple docstring'''







				A     :  Any   =				argparse.ArgumentParser()
				parser.add_argument('''--print-checkpoint-structure'''				,	action='''store_true'''		)
				parser.add_argument('''path_to_checkpoint'''				,	type=lowerCamelCase_				,	help='''Path to the ZIP file containing the checkpoint'''		)
				parser.add_argument(
				    '''--config_file'''				,	default=''''''				,	type=lowerCamelCase_				,	help='''An optional config json file describing the pre-trained model.'''				,	)
				A     :  Tuple   =				parser.parse_args()

				# Extract the basename.
				A     :  int   =				os.path.dirname(args.path_to_checkpoint		)

				# Load the model.
				# the .zip is very optional, let's keep it for backward compatibility
				print(f"""Extracting PyTorch state dictionary from \"{args.path_to_checkpoint}\""""		)
				if args.path_to_checkpoint.endswith('''.zip'''		):
								with zipfile.ZipFile(args.path_to_checkpoint				,	'''r'''		) as checkpoint:
												with checkpoint.open('''release/mp_rank_00/model_optim_rng.pt'''		) as pytorch_dict:
																A     :  Union[str, Any]   =				torch.load(lowerCamelCase_				,	map_location='''cpu'''		)
				else:
								A     :  Union[str, Any]   =				torch.load(args.path_to_checkpoint				,	map_location='''cpu'''		)

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

				# Convert.
				print('''Converting'''		)
				A     :  str   =				convert_megatron_checkpoint(lowerCamelCase_				,	lowerCamelCase_				,	lowerCamelCase_		)

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

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

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


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

if __name__ == "__main__":
					main()

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

import math
from dataclasses import dataclass
from typing import Optional, Tuple, Union

import numpy as np
import torch

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, randn_tensor
from .scheduling_utils import SchedulerMixin

@dataclass
class     _SCREAMING_SNAKE_CASE							(		snake_case							):
				lowerCamelCase_       =     42
				lowerCamelCase_       =     42





def 							_lowerCamelCase			(					lowerCamelCase_:  str				,	lowerCamelCase_:  int=0.9_9_9				,	lowerCamelCase_:  Optional[Any]="cosine"				,	):



				'''simple docstring'''







				if alpha_transform_type == "cosine":

								def alpha_bar_fn(lowerCamelCase_:  Optional[Any]		):
												return math.cos((t + 0.0_0_8) / 1.0_0_8 * math.pi / 2		) ** 2

				elif alpha_transform_type == "exp":

								def alpha_bar_fn(lowerCamelCase_:  Optional[Any]		):
												return math.exp(t * -1_2.0		)

				else:
								raise ValueError(f"""Unsupported alpha_tranform_type: {alpha_transform_type}"""		)

				A     :  Dict   =				[]
				for i in range(lowerCamelCase_		):
								A     :  Dict   =				i / num_diffusion_timesteps
								A     :  List[str]   =				(i + 1) / num_diffusion_timesteps
								betas.append(min(1 - alpha_bar_fn(lowerCamelCase_		) / alpha_bar_fn(lowerCamelCase_		)				,	lowerCamelCase_		)		)
				return torch.tensor(lowerCamelCase_				,	dtype=torch.floataa		)






class     _SCREAMING_SNAKE_CASE							(		snake_case,    snake_case							):
				lowerCamelCase_       =     1





				@register_to_config
				def __init__(		self :		Optional[Any]					,      snake_case_ :		int = 1000					,      snake_case_ :		float = 0.00_01					,      snake_case_ :		float = 0.02					,      snake_case_ :		str = "linear"					,      snake_case_ :		float = 0.0					,      snake_case_ :		Optional[np.ndarray] = None					,      snake_case_ :		bool = True					,      ):


								"""simple docstring"""

								if trained_betas is not None:
												A     :  Any   =				torch.from_numpy(snake_case_							)
								elif beta_schedule == "linear":
												A     :  Tuple   =				torch.linspace(snake_case_					,      snake_case_					,      snake_case_					,      dtype=torch.floataa							)
								elif beta_schedule == "scaled_linear":
												# this schedule is very specific to the latent diffusion model.
												A     :  str   =				(
												    torch.linspace(beta_start**0.5					,      beta_end**0.5					,      snake_case_					,      dtype=torch.floataa							) ** 2
												)
								elif beta_schedule == "squaredcos_cap_v2":
												# Glide cosine schedule
												A     :  int   =				betas_for_alpha_bar(snake_case_							)
								elif beta_schedule == "sigmoid":
												# GeoDiff sigmoid schedule
												A     :  Optional[Any]   =				torch.linspace(-6					,      6					,      snake_case_							)
												A     :  str   =				torch.sigmoid(snake_case_							) * (beta_end - beta_start) + beta_start
								else:
												raise NotImplementedError(f"""{beta_schedule} does is not implemented for {self.__class__}"""							)

								A     :  Any   =				1.0 - self.betas
								A     :  int   =				torch.cumprod(self.alphas					,      dim=0							)
								A     :  Any   =				torch.tensor(1.0							)

								A     :  Dict   =				torch.tensor(1.0							)

								# standard deviation of the initial noise distribution
								A     :  Optional[Any]   =				1.0

								# setable values
								A     :  Dict   =				None
								A     :  Dict   =				torch.from_numpy(np.arange(0					,      snake_case_							)[::-1].copy()							)

								A     :  Any   =				eta





				def        _UpperCAmelCase						(		self :		List[Any]					,      snake_case_ :		torch.FloatTensor					,      snake_case_ :		Optional[int] = None							):


								"""simple docstring"""

								return sample





				def        _UpperCAmelCase						(		self :		List[Any]					,      snake_case_ :		int					,      snake_case_ :		int = 10					,      snake_case_ :		int = 10					,      snake_case_ :		Union[str, torch.device] = None					,      ):


								"""simple docstring"""

								A     :  List[Any]   =				min(self.config.num_train_timesteps					,      snake_case_							)
								A     :  int   =				num_inference_steps

								A     :  List[Any]   =				[]

								A     :  Optional[Any]   =				{}
								for j in range(0					,      num_inference_steps - jump_length					,      snake_case_							):
												A     :  List[Any]   =				jump_n_sample - 1

								A     :  Optional[int]   =				num_inference_steps
								while t >= 1:
												A     :  Optional[Any]   =				t - 1
												timesteps.append(snake_case_							)

												if jumps.get(snake_case_					,      0							) > 0:
																A     :  Optional[int]   =				jumps[t] - 1
																for _ in range(snake_case_							):
																				A     :  Dict   =				t + 1
																				timesteps.append(snake_case_							)

								A     :  Optional[Any]   =				np.array(snake_case_							) * (self.config.num_train_timesteps // self.num_inference_steps)
								A     :  Optional[Any]   =				torch.from_numpy(snake_case_							).to(snake_case_							)





				def        _UpperCAmelCase						(		self :		Optional[int]					,      snake_case_ :		Optional[int]							):


								"""simple docstring"""

								A     :  str   =				t - self.config.num_train_timesteps // self.num_inference_steps

								A     :  str   =				self.alphas_cumprod[t]
								A     :  List[Any]   =				self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
								A     :  Dict   =				1 - alpha_prod_t
								A     :  Any   =				1 - alpha_prod_t_prev

								# For t > 0, compute predicted variance βt (see formula (6) and (7) from
								# https://arxiv.org/pdf/2006.11239.pdf) and sample from it to get
								# previous sample x_{t-1} ~ N(pred_prev_sample, variance) == add
								# variance to pred_sample
								# Is equivalent to formula (16) in https://arxiv.org/pdf/2010.02502.pdf
								# without eta.
								# variance = (1 - alpha_prod_t_prev) / (1 - alpha_prod_t) * self.betas[t]
								A     :  int   =				(beta_prod_t_prev / beta_prod_t) * (1 - alpha_prod_t / alpha_prod_t_prev)

								return variance





				def        _UpperCAmelCase						(		self :		List[str]					,      snake_case_ :		torch.FloatTensor					,      snake_case_ :		int					,      snake_case_ :		torch.FloatTensor					,      snake_case_ :		torch.FloatTensor					,      snake_case_ :		torch.FloatTensor					,      snake_case_ :		Optional[torch.Generator] = None					,      snake_case_ :		bool = True					,      ):


								"""simple docstring"""

								A     :  Any   =				timestep
								A     :  List[str]   =				timestep - self.config.num_train_timesteps // self.num_inference_steps

								# 1. compute alphas, betas
								A     :  List[Any]   =				self.alphas_cumprod[t]
								A     :  Optional[int]   =				self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
								A     :  Optional[Any]   =				1 - alpha_prod_t

								# 2. compute predicted original sample from predicted noise also called
								# "predicted x_0" of formula (15) from https://arxiv.org/pdf/2006.11239.pdf
								A     :  Optional[Any]   =				(sample - beta_prod_t**0.5 * model_output) / alpha_prod_t**0.5

								# 3. Clip "predicted x_0"
								if self.config.clip_sample:
												A     :  Optional[Any]   =				torch.clamp(snake_case_					,      -1					,      1							)

								# We choose to follow RePaint Algorithm 1 to get x_{t-1}, however we
								# substitute formula (7) in the algorithm coming from DDPM paper
								# (formula (4) Algorithm 2 - Sampling) with formula (12) from DDIM paper.
								# DDIM schedule gives the same results as DDPM with eta = 1.0
								# Noise is being reused in 7. and 8., but no impact on quality has
								# been observed.

								# 5. Add noise
								A     :  Dict   =				model_output.device
								A     :  str   =				randn_tensor(model_output.shape					,      generator=snake_case_					,      device=snake_case_					,      dtype=model_output.dtype							)
								A     :  Tuple   =				self.eta * self._get_variance(snake_case_							) ** 0.5

								A     :  List[str]   =				0
								if t > 0 and self.eta > 0:
												A     :  Optional[int]   =				std_dev_t * noise

								# 6. compute "direction pointing to x_t" of formula (12)
								# from https://arxiv.org/pdf/2010.02502.pdf
								A     :  List[Any]   =				(1 - alpha_prod_t_prev - std_dev_t**2) ** 0.5 * model_output

								# 7. compute x_{t-1} of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
								A     :  Dict   =				alpha_prod_t_prev**0.5 * pred_original_sample + pred_sample_direction + variance

								# 8. Algorithm 1 Line 5 https://arxiv.org/pdf/2201.09865.pdf
								A     :  Any   =				(alpha_prod_t_prev**0.5) * original_image + ((1 - alpha_prod_t_prev) ** 0.5) * noise

								# 9. Algorithm 1 Line 8 https://arxiv.org/pdf/2201.09865.pdf
								A     :  Optional[int]   =				mask * prev_known_part + (1.0 - mask) * prev_unknown_part

								if not return_dict:
												return (
												    pred_prev_sample,
												    pred_original_sample,
												)

								return RePaintSchedulerOutput(prev_sample=snake_case_					,      pred_original_sample=snake_case_							)





				def        _UpperCAmelCase						(		self :		Tuple					,      snake_case_ :		Any					,      snake_case_ :		Tuple					,      snake_case_ :		List[str]=None							):


								"""simple docstring"""

								A     :  List[str]   =				self.config.num_train_timesteps // self.num_inference_steps

								for i in range(snake_case_							):
												A     :  Dict   =				self.betas[timestep + i]
												if sample.device.type == "mps":
																# randn does not work reproducibly on mps
																A     :  Any   =				randn_tensor(sample.shape					,      dtype=sample.dtype					,      generator=snake_case_							)
																A     :  Any   =				noise.to(sample.device							)
												else:
																A     :  Union[str, Any]   =				randn_tensor(sample.shape					,      generator=snake_case_					,      device=sample.device					,      dtype=sample.dtype							)

												# 10. Algorithm 1 Line 10 https://arxiv.org/pdf/2201.09865.pdf
												A     :  str   =				(1 - beta) ** 0.5 * sample + beta**0.5 * noise

								return sample





				def        _UpperCAmelCase						(		self :		List[str]					,      snake_case_ :		torch.FloatTensor					,      snake_case_ :		torch.FloatTensor					,      snake_case_ :		torch.IntTensor					,      ):


								"""simple docstring"""

								raise NotImplementedError('''Use `DDPMScheduler.add_noise()` to train for sampling with RePaint.'''							)






				def __len__(		self :		Optional[Any]							):


								"""simple docstring"""

								return self.config.num_train_timesteps