'''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 				__UpperCamelCase (					__UpperCAmelCase  :					Tuple ,   __UpperCAmelCase  :					Optional[int] ,   __UpperCAmelCase  :					Tuple=0			)							->	str:
  # Format the message.
  if name is None:
    lowercase				:							Optional[Any]									=   None
  else:
    lowercase				:							Union[str, Any]									=   '''.''' * max(0 ,   spaces - 2			) + '''# {:''' + str(50 - spaces			) + '''s}'''
    lowercase				:							str									=   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 				__UpperCamelCase (					__UpperCAmelCase  :					Tuple ,   __UpperCAmelCase  :					Dict ,   __UpperCAmelCase  :					int ,   __UpperCAmelCase  :					Optional[int] ,   __UpperCAmelCase  :					List[str]			)							->	Dict:
  # Permutes layout of param tensor to [num_splits * num_heads * hidden_size, :]
  # for compatibility with later versions of NVIDIA Megatron-LM.
  # The inverse operation is performed inside Megatron-LM to read checkpoints:
  # https://github.com/NVIDIA/Megatron-LM/blob/v2.4/megatron/checkpointing.py#L209
  # If param is the weight tensor of the self-attention block, the returned tensor
  # will have to be transposed one more time to be read by HuggingFace BERT.
  lowercase				:							Any									=   param.size()
  if checkpoint_version == 1.0:
    # version 1.0 stores [num_heads * hidden_size * num_splits, :]
    lowercase				:							Optional[Any]									=   (num_heads, hidden_size, num_splits) + input_shape[1:]
    lowercase				:							List[Any]									=   param.view(*__UpperCAmelCase			)
    lowercase				:							List[str]									=   param.transpose(0 ,   2			)
    lowercase				:							Tuple									=   param.transpose(1 ,   2			).contiguous()
  elif checkpoint_version >= 2.0:
    # other versions store [num_heads * num_splits * hidden_size, :]
    lowercase				:							List[Any]									=   (num_heads, num_splits, hidden_size) + input_shape[1:]
    lowercase				:							Optional[int]									=   param.view(*__UpperCAmelCase			)
    lowercase				:							str									=   param.transpose(0 ,   1			).contiguous()
  lowercase				:							str									=   param.view(*__UpperCAmelCase			)
  return param







def 				__UpperCamelCase (					__UpperCAmelCase  :					Optional[Any] ,   __UpperCAmelCase  :					Tuple ,   __UpperCAmelCase  :					str			)							->	Optional[int]:
  # The converted output model.
  lowercase				:							Any									=   {}

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

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

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

  # The model.
  lowercase				:							List[str]									=   input_state_dict['''model''']
  # The language model.
  lowercase				:							Dict									=   model['''language_model''']
  # The embeddings.
  lowercase				:							Tuple									=   lm['''embedding''']

  # The word embeddings.
  lowercase				:							Dict									=   embeddings['''word_embeddings''']['''weight''']
  # Truncate the embedding table to vocab_size rows.
  lowercase				:							Dict									=   word_embeddings[: config.vocab_size, :]
  # Store the word embeddings.
  lowercase				:							Optional[int]									=   word_embeddings

  # The position embeddings.
  lowercase				:							List[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.
  lowercase				:							Tuple									=   pos_embeddings

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

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

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

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

  # Keep track of the attention/query/value tensor.
  lowercase				:							Optional[Any]									=   None

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

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

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

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

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

      lowercase				:							int									=   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.
      lowercase				:							List[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.
      lowercase				:							str									=   attention_qkv_weight[0 * config.hidden_size : 1 * config.hidden_size, :]
      lowercase				:							List[Any]									=   attention_qkv_weight[1 * config.hidden_size : 2 * config.hidden_size, :]
      lowercase				:							Optional[int]									=   attention_qkv_weight[2 * config.hidden_size : 3 * config.hidden_size, :]

      lowercase				:							Optional[Any]									=   fix_query_key_value_ordering(__UpperCAmelCase ,   __UpperCAmelCase ,   3 ,   __UpperCAmelCase ,   __UpperCAmelCase			)
      # Split the bias.
      lowercase				:							Dict									=   out_val[0 * config.hidden_size : 1 * config.hidden_size]
      lowercase				:							List[str]									=   out_val[1 * config.hidden_size : 2 * config.hidden_size]
      lowercase				:							Optional[Any]									=   out_val[2 * config.hidden_size : 3 * config.hidden_size]

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

      # Clear the stored tensor.
      lowercase				:							Any									=   None

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

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

  # The pooler.
  lowercase				:							Optional[Any]									=   lm['''pooler''']

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

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

  # The transform matrix.
  lowercase				:							str									=   lm_head['''dense.weight''']
  lowercase				:							int									=   lm_head['''dense.bias''']

  # The transform LN.
  lowercase				:							Dict									=   lm_head['''layernorm.weight''']
  lowercase				:							List[str]									=   lm_head['''layernorm.bias''']

  # For the decoder, we replicate the weights.
  lowercase				:							Dict									=   word_embeddings
  lowercase				:							Any									=   lm_head['''bias''']

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

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

  # It should be done!
  return output_state_dict







def 				__UpperCamelCase (					)							->	int:
  # Create the argument parser.
  lowercase				:							Dict									=   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.''' ,   )
  lowercase				:							Optional[int]									=   parser.parse_args()

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

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

  # Convert.
  print('''Converting'''			)
  lowercase				:							Optional[int]									=   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.
  lowercase				:							Any									=   os.path.join(__UpperCAmelCase ,   '''pytorch_model.bin'''			)
  print(f"""Saving checkpoint to \"{output_checkpoint_file}\""""			)
  torch.save(__UpperCAmelCase ,   __UpperCAmelCase			)


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

if __name__ == "__main__":
 main()

####################################################################################################
'''simple docstring'''
from collections.abc import Callable
from math import log
from os import name, system
from random import gauss, seed
from typing import TypeVar







def 				__UpperCamelCase (					__UpperCAmelCase  :					float ,   __UpperCAmelCase  :					float ,   __UpperCAmelCase  :					int			)							->	list:
  seed(1			)
  return [gauss(__UpperCAmelCase ,   __UpperCAmelCase			) for _ in range(__UpperCAmelCase			)]







def 				__UpperCamelCase (					__UpperCAmelCase  :					int ,   __UpperCAmelCase  :					list			)							->	list:
  return [k for k in range(__UpperCAmelCase			) for _ in range(instance_count[k]			)]







def 				__UpperCamelCase (					__UpperCAmelCase  :					int ,   __UpperCAmelCase  :					list			)							->	float:
  return sum(__UpperCAmelCase			) / instance_count







def 				__UpperCamelCase (					__UpperCAmelCase  :					int ,   __UpperCAmelCase  :					int			)							->	float:
  return instance_count / total_count







def 				__UpperCamelCase (					__UpperCAmelCase  :					list ,   __UpperCAmelCase  :					list ,   __UpperCAmelCase  :					int			)							->	float:
  lowercase				:							List[Any]									=   []  # An empty list to store all squared differences
  # iterate over number of elements in items
  for i in range(len(__UpperCAmelCase			)			):
    # for loop iterates over number of elements in inner layer of items
    for j in range(len(items[i]			)			):
      # appending squared differences to 'squared_diff' list
      squared_diff.append((items[i][j] - means[i]) ** 2			)

    # one divided by (the number of all instances - number of classes) multiplied by
    # sum of all squared differences
  lowercase				:							List[str]									=   len(__UpperCAmelCase			)  # Number of classes in dataset
  return 1 / (total_count - n_classes) * sum(__UpperCAmelCase			)







def 				__UpperCamelCase (					__UpperCAmelCase  :					list ,   __UpperCAmelCase  :					list ,   __UpperCAmelCase  :					float ,   __UpperCAmelCase  :					list			)							->	list:
  lowercase				:							Union[str, Any]									=   []
  # for loop iterates over number of elements in list
  for i in range(len(__UpperCAmelCase			)			):
    # for loop iterates over number of inner items of each element
    for j in range(len(x_items[i]			)			):
      lowercase				:							Any									=   []  # to store all discriminant values of each item as a list
      # for loop iterates over number of classes we have in our dataset
      for k in range(len(__UpperCAmelCase			)			):
        # appending values of discriminants for each class to 'temp' list
        temp.append(
            x_items[i][j] * (means[k] / variance)
            - (means[k] ** 2 / (2 * variance))
            + log(probabilities[k]			)			)
      # appending discriminant values of each item to 'results' list
      results.append(__UpperCAmelCase			)

  return [result.index(max(__UpperCAmelCase			)			) for result in results]







def 				__UpperCamelCase (					__UpperCAmelCase  :					list ,   __UpperCAmelCase  :					list			)							->	float:
  lowercase				:							List[str]									=   sum(1 for i, j in zip(__UpperCAmelCase ,   __UpperCAmelCase			) if i == j			)
  # percentage of accuracy equals to number of correct predictions divided by number
  # of all data and multiplied by 100
  return (correct / len(__UpperCAmelCase			)) * 100


_A		:      Dict						   =TypeVar('''num''')







def 				__UpperCamelCase (					__UpperCAmelCase  :					Callable[[object], num] ,   __UpperCAmelCase  :					str ,   __UpperCAmelCase  :					str ,   __UpperCAmelCase  :					Callable[[num], bool] = lambda __UpperCAmelCase			: True ,   __UpperCAmelCase  :					str | None = None ,   )							->	num:
  while True:
    try:
      lowercase				:							int									=   input_type(input(__UpperCAmelCase			).strip() or default			)
      if condition(__UpperCAmelCase			):
        return user_input
      else:
        print(f"""{user_input}: {err_msg}"""			)
        continue
    except ValueError:
      print(
          f"""{user_input}: Incorrect input type, expected {input_type.__name__!r}"""			)







def 				__UpperCamelCase (					)							->	Optional[int]:
  while True:
    print(''' Linear Discriminant Analysis '''.center(50 ,   '''*'''			)			)
    print('''*''' * 50 ,   '''\n'''			)
    print('''First of all we should specify the number of classes that'''			)
    print('''we want to generate as training dataset'''			)
    # Trying to get number of classes
    lowercase				:							List[str]									=   valid_input(
        input_type=__UpperCAmelCase ,   condition=lambda __UpperCAmelCase			: x > 0 ,   input_msg='''Enter the number of classes (Data Groupings): ''' ,   err_msg='''Number of classes should be positive!''' ,   )

    print('''-''' * 100			)

    # Trying to get the value of standard deviation
    lowercase				:							Dict									=   valid_input(
        input_type=__UpperCAmelCase ,   condition=lambda __UpperCAmelCase			: x >= 0 ,   input_msg=(
            '''Enter the value of standard deviation'''
            '''(Default value is 1.0 for all classes): '''
        ) ,   err_msg='''Standard deviation should not be negative!''' ,   default='''1.0''' ,   )

    print('''-''' * 100			)

    # Trying to get number of instances in classes and theirs means to generate
    # dataset
    lowercase				:							str									=   []  # An empty list to store instance counts of classes in dataset
    for i in range(__UpperCAmelCase			):
      lowercase				:							List[Any]									=   valid_input(
          input_type=__UpperCAmelCase ,   condition=lambda __UpperCAmelCase			: x > 0 ,   input_msg=(f"""Enter The number of instances for class_{i+1}: """) ,   err_msg='''Number of instances should be positive!''' ,   )
      counts.append(__UpperCAmelCase			)
    print('''-''' * 100			)

    # An empty list to store values of user-entered means of classes
    lowercase				:							int									=   []
    for a in range(__UpperCAmelCase			):
      lowercase				:							int									=   valid_input(
          input_type=__UpperCAmelCase ,   input_msg=(f"""Enter the value of mean for class_{a+1}: """) ,   err_msg='''This is an invalid value.''' ,   )
      user_means.append(__UpperCAmelCase			)
    print('''-''' * 100			)

    print('''Standard deviation: ''' ,   __UpperCAmelCase			)
    # print out the number of instances in classes in separated line
    for i, count in enumerate(__UpperCAmelCase ,   1			):
      print(f"""Number of instances in class_{i} is: {count}"""			)
    print('''-''' * 100			)

    # print out mean values of classes separated line
    for i, user_mean in enumerate(__UpperCAmelCase ,   1			):
      print(f"""Mean of class_{i} is: {user_mean}"""			)
    print('''-''' * 100			)

    # Generating training dataset drawn from gaussian distribution
    lowercase				:							Union[str, Any]									=   [
        gaussian_distribution(user_means[j] ,   __UpperCAmelCase ,   counts[j]			)
        for j in range(__UpperCAmelCase			)
    ]
    print('''Generated Normal Distribution: \n''' ,   __UpperCAmelCase			)
    print('''-''' * 100			)

    # Generating Ys to detecting corresponding classes
    lowercase				:							List[str]									=   y_generator(__UpperCAmelCase ,   __UpperCAmelCase			)
    print('''Generated Corresponding Ys: \n''' ,   __UpperCAmelCase			)
    print('''-''' * 100			)

    # Calculating the value of actual mean for each class
    lowercase				:							int									=   [calculate_mean(counts[k] ,   x[k]			) for k in range(__UpperCAmelCase			)]
    # for loop iterates over number of elements in 'actual_means' list and print
    # out them in separated line
    for i, actual_mean in enumerate(__UpperCAmelCase ,   1			):
      print(f"""Actual(Real) mean of class_{i} is: {actual_mean}"""			)
    print('''-''' * 100			)

    # Calculating the value of probabilities for each class
    lowercase				:							Optional[int]									=   [
        calculate_probabilities(counts[i] ,   sum(__UpperCAmelCase			)			) for i in range(__UpperCAmelCase			)
    ]

    # for loop iterates over number of elements in 'probabilities' list and print
    # out them in separated line
    for i, probability in enumerate(__UpperCAmelCase ,   1			):
      print(f"""Probability of class_{i} is: {probability}"""			)
    print('''-''' * 100			)

    # Calculating the values of variance for each class
    lowercase				:							Tuple									=   calculate_variance(__UpperCAmelCase ,   __UpperCAmelCase ,   sum(__UpperCAmelCase			)			)
    print('''Variance: ''' ,   __UpperCAmelCase			)
    print('''-''' * 100			)

    # Predicting Y values
    # storing predicted Y values in 'pre_indexes' variable
    lowercase				:							Any									=   predict_y_values(__UpperCAmelCase ,   __UpperCAmelCase ,   __UpperCAmelCase ,   __UpperCAmelCase			)
    print('''-''' * 100			)

    # Calculating Accuracy of the model
    print(f"""Accuracy: {accuracy(__UpperCAmelCase ,   __UpperCAmelCase			)}"""			)
    print('''-''' * 100			)
    print(''' DONE '''.center(100 ,   '''+'''			)			)

    if input('''Press any key to restart or \'q\' for quit: '''			).strip().lower() == "q":
      print('''\n''' + '''GoodBye!'''.center(100 ,   '''-'''			) + '''\n'''			)
      break
    system('''cls''' if name == '''nt''' else '''clear'''			)  # noqa: S605


if __name__ == "__main__":
 main()