code: 
  """simple docstring"""
  from __future__ import annotations
  
  import unittest
  
  from transformers import AutoTokenizer, GPTJConfig, is_tf_available
  from transformers.testing_utils import require_tf, slow, tooslow
  
  from ...test_configuration_common import ConfigTester
  from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor, random_attention_mask
  from ...test_pipeline_mixin import PipelineTesterMixin
  from ...utils.test_modeling_tf_core import TFCoreModelTesterMixin
  
  
  if is_tf_available():
  			import tensorflow as tf
  
  			from transformers.models.gptj.modeling_tf_gptj import (
  			    TFGPTJForCausalLM,
  			    TFGPTJForQuestionAnswering,
  			    TFGPTJForSequenceClassification,
  			    TFGPTJModel,
  			    shape_list,
  			)
  
  
  class    _lowerCAmelCase						:
  
  
  
  							def __init__(      self ,						a_   )							->							str:
  								_UpperCAmelCase =						parent
  								_UpperCAmelCase =						13
  								_UpperCAmelCase =						7
  								_UpperCAmelCase =						True
  								_UpperCAmelCase =						True
  								_UpperCAmelCase =						True
  								_UpperCAmelCase =						True
  								_UpperCAmelCase =						True
  								_UpperCAmelCase =						99
  								_UpperCAmelCase =						32
  								_UpperCAmelCase =						4
  								_UpperCAmelCase =						2
  								_UpperCAmelCase =						4
  								_UpperCAmelCase =						37
  								_UpperCAmelCase =						"gelu"
  								_UpperCAmelCase =						0.1
  								_UpperCAmelCase =						0.1
  								_UpperCAmelCase =						512
  								_UpperCAmelCase =						16
  								_UpperCAmelCase =						2
  								_UpperCAmelCase =						0.02
  								_UpperCAmelCase =						3
  								_UpperCAmelCase =						4
  								_UpperCAmelCase =						None
  								_UpperCAmelCase =						self.vocab_size - 1
  								_UpperCAmelCase =						self.vocab_size - 1
  								_UpperCAmelCase =						self.vocab_size - 1
  
  
  
  							def       _a   (      self   )							->							Optional[Any]:
  								_UpperCAmelCase =						ids_tensor([self.batch_size, self.seq_length] ,						self.vocab_size   )
  
  								_UpperCAmelCase =						None
  								if self.use_input_mask:
  									_UpperCAmelCase =						random_attention_mask([self.batch_size, self.seq_length]   )
  
  								_UpperCAmelCase =						None
  								if self.use_token_type_ids:
  									_UpperCAmelCase =						ids_tensor([self.batch_size, self.seq_length] ,						self.type_vocab_size   )
  
  								_UpperCAmelCase =						None
  								if self.use_mc_token_ids:
  									_UpperCAmelCase =						ids_tensor([self.batch_size, self.num_choices] ,						self.seq_length   )
  
  								_UpperCAmelCase =						None
  								_UpperCAmelCase =						None
  								_UpperCAmelCase =						None
  								if self.use_labels:
  									_UpperCAmelCase =						ids_tensor([self.batch_size] ,						self.type_sequence_label_size   )
  									_UpperCAmelCase =						ids_tensor([self.batch_size, self.seq_length] ,						self.num_labels   )
  									_UpperCAmelCase =						ids_tensor([self.batch_size] ,						self.num_choices   )
  
  								_UpperCAmelCase =						GPTJConfig(
  								    vocab_size=self.vocab_size ,						n_embd=self.hidden_size ,						n_layer=self.num_hidden_layers ,						n_head=self.num_attention_heads ,						intermediate_size=self.intermediate_size ,						hidden_act=self.hidden_act ,						hidden_dropout_prob=self.hidden_dropout_prob ,						attention_probs_dropout_prob=self.attention_probs_dropout_prob ,						n_positions=self.max_position_embeddings ,						type_vocab_size=self.type_vocab_size ,						initializer_range=self.initializer_range ,						bos_token_id=self.bos_token_id ,						eos_token_id=self.eos_token_id ,						pad_token_id=self.pad_token_id ,						rotary_dim=self.rotary_dim ,						return_dict=a_ ,						)
  
  								_UpperCAmelCase =						ids_tensor([self.num_hidden_layers, self.num_attention_heads] ,						2   )
  
  								return (
  								    config,
  								    input_ids,
  								    input_mask,
  								    head_mask,
  								    token_type_ids,
  								    mc_token_ids,
  								    sequence_labels,
  								    token_labels,
  								    choice_labels,
  								)
  
  
  
  							def       _a   (      self ,						a_ ,						a_ ,						a_ ,						a_ ,						a_ ,						*a_   )							->							List[Any]:
  								_UpperCAmelCase =						TFGPTJModel(config=a_   )
  								_UpperCAmelCase =						{
  								    "input_ids": input_ids,
  								    "attention_mask": input_mask,
  								    "token_type_ids": token_type_ids,
  								}
  								_UpperCAmelCase =						model(a_   )
  
  								_UpperCAmelCase =						[input_ids, None, input_mask]  # None is the input for 'past'
  								_UpperCAmelCase =						model(a_   )
  
  								_UpperCAmelCase =						model(a_   )
  
  								self.parent.assertEqual(result.last_hidden_state.shape ,						(self.batch_size, self.seq_length, self.hidden_size)   )
  
  
  
  							def       _a   (      self ,						a_ ,						a_ ,						a_ ,						a_ ,						a_ ,						*a_   )							->							List[str]:
  								_UpperCAmelCase =						TFGPTJModel(config=a_   )
  
  								# first forward pass
  								_UpperCAmelCase =						model(a_ ,						token_type_ids=a_ ,						use_cache=a_   )
  								_UpperCAmelCase =						model(a_ ,						token_type_ids=a_   )
  								_UpperCAmelCase =						model(a_ ,						token_type_ids=a_ ,						use_cache=a_   )
  
  								self.parent.assertTrue(len(a_   ) == len(a_   )   )
  								self.parent.assertTrue(len(a_   ) == len(a_   ) + 1   )
  
  								_UpperCAmelCase ,      _UpperCAmelCase =						outputs.to_tuple()
  
  								# create hypothetical next token and extent to next_input_ids
  								_UpperCAmelCase =						ids_tensor((self.batch_size, 1) ,						config.vocab_size   )
  								_UpperCAmelCase =						ids_tensor([self.batch_size, 1] ,						self.type_vocab_size   )
  
  								# append to next input_ids and token_type_ids
  								_UpperCAmelCase =						tf.concat([input_ids, next_tokens] ,						axis=-1   )
  								_UpperCAmelCase =						tf.concat([token_type_ids, next_token_types] ,						axis=-1   )
  
  								_UpperCAmelCase =						model(a_ ,						token_type_ids=a_   )["last_hidden_state"]
  								_UpperCAmelCase =						model(a_ ,						token_type_ids=a_ ,						past_key_values=a_   )[
  								    "last_hidden_state"
  								]
  
  								# select random slice
  								_UpperCAmelCase =						int(ids_tensor((1,) ,						shape_list(a_   )[-1]   )   )
  								_UpperCAmelCase =						output_from_no_past[:, -1, random_slice_idx]
  								_UpperCAmelCase =						output_from_past[:, 0, random_slice_idx]
  
  								# test that outputs are equal for slice
  								tf.debugging.assert_near(a_ ,						a_ ,						rtol=1e-6   )
  
  
  
  							def       _a   (      self ,						a_ ,						a_ ,						a_ ,						a_ ,						a_ ,						*a_   )							->							Union[str, Any]:
  								_UpperCAmelCase =						TFGPTJModel(config=a_   )
  
  								# create attention mask
  								_UpperCAmelCase =						self.seq_length // 2
  								_UpperCAmelCase =						tf.ones((self.batch_size, half_seq_length) ,						dtype=tf.intaa   )
  								_UpperCAmelCase =						tf.zeros((self.batch_size, self.seq_length - half_seq_length) ,						dtype=tf.intaa   )
  								_UpperCAmelCase =						tf.concat([attn_mask_begin, attn_mask_end] ,						axis=1   )
  
  								# first forward pass
  								_UpperCAmelCase ,      _UpperCAmelCase =						model(a_ ,						attention_mask=a_   ).to_tuple()
  
  								# create hypothetical next token and extent to next_input_ids
  								_UpperCAmelCase =						ids_tensor((self.batch_size, 1) ,						config.vocab_size   )
  
  								# change a random masked slice from input_ids
  								_UpperCAmelCase =						ids_tensor((1,) ,						a_   ).numpy() + 1
  								_UpperCAmelCase =						ids_tensor((self.batch_size, self.seq_length) ,						config.vocab_size   )
  								_UpperCAmelCase =						tf.range(self.seq_length   ) == (self.seq_length - random_seq_idx_to_change)
  								_UpperCAmelCase =						tf.transpose(
  								    tf.broadcast_to(tf.expand_dims(a_ ,						-1   ) ,						(self.seq_length, self.batch_size)   )   )
  								_UpperCAmelCase =						tf.where(a_ ,						a_ ,						a_   )
  
  								# append to next input_ids and attn_mask
  								_UpperCAmelCase =						tf.concat([input_ids, next_tokens] ,						axis=-1   )
  								_UpperCAmelCase =						tf.concat([attn_mask, tf.ones((shape_list(a_   )[0], 1) ,						dtype=tf.intaa   )] ,						axis=1   )
  
  								# get two different outputs
  								_UpperCAmelCase =						model(a_ ,						attention_mask=a_   )["last_hidden_state"]
  								_UpperCAmelCase =						model(a_ ,						past_key_values=a_ ,						attention_mask=a_   )[
  								    "last_hidden_state"
  								]
  
  								# select random slice
  								_UpperCAmelCase =						int(ids_tensor((1,) ,						shape_list(a_   )[-1]   )   )
  								_UpperCAmelCase =						output_from_no_past[:, -1, random_slice_idx]
  								_UpperCAmelCase =						output_from_past[:, 0, random_slice_idx]
  
  								# test that outputs are equal for slice
  								tf.debugging.assert_near(a_ ,						a_ ,						rtol=1e-12   )
  
  
  
  							def       _a   (      self ,						a_ ,						a_ ,						a_ ,						a_ ,						a_ ,						*a_   )							->							Optional[Any]:
  								_UpperCAmelCase =						TFGPTJModel(config=a_   )
  
  								_UpperCAmelCase =						input_ids[:1, :]
  								_UpperCAmelCase =						input_mask[:1, :]
  								_UpperCAmelCase =						token_type_ids[:1, :]
  								_UpperCAmelCase =						1
  
  								# first forward pass
  								_UpperCAmelCase =						model(a_ ,						attention_mask=a_ ,						token_type_ids=a_ ,						use_cache=a_   )
  
  								_UpperCAmelCase ,      _UpperCAmelCase =						outputs.to_tuple()
  
  								# create hypothetical next token and extent to next_input_ids
  								_UpperCAmelCase =						ids_tensor((self.batch_size, 3) ,						config.vocab_size   )
  								_UpperCAmelCase =						ids_tensor((self.batch_size, 3) ,						2   )
  								_UpperCAmelCase =						ids_tensor((self.batch_size, 3) ,						self.type_vocab_size   )
  
  								# append to next input_ids and token_type_ids
  								_UpperCAmelCase =						tf.concat([input_ids, next_tokens] ,						axis=-1   )
  								_UpperCAmelCase =						tf.concat([input_mask, next_attn_mask] ,						axis=-1   )
  								_UpperCAmelCase =						tf.concat([token_type_ids, next_token_types] ,						axis=-1   )
  
  								_UpperCAmelCase =						model(
  								    a_ ,						token_type_ids=a_ ,						attention_mask=a_   )["last_hidden_state"]
  								_UpperCAmelCase =						model(
  								    a_ ,						token_type_ids=a_ ,						attention_mask=a_ ,						past_key_values=a_ ,						)["last_hidden_state"]
  								self.parent.assertTrue(output_from_past.shape[1] == next_tokens.shape[1]   )
  
  								# select random slice
  								_UpperCAmelCase =						int(ids_tensor((1,) ,						shape_list(a_   )[-1]   )   )
  								_UpperCAmelCase =						output_from_no_past[:, -3:, random_slice_idx]
  								_UpperCAmelCase =						output_from_past[:, :, random_slice_idx]
  
  								# test that outputs are equal for slice
  								tf.debugging.assert_near(a_ ,						a_ ,						rtol=1e-3   )
  
  
  
  							def       _a   (      self ,						a_ ,						a_ ,						a_ ,						a_ ,						a_ ,						*a_   )							->							Optional[Any]:
  								_UpperCAmelCase =						TFGPTJForCausalLM(config=a_   )
  								_UpperCAmelCase =						{
  								    "input_ids": input_ids,
  								    "attention_mask": input_mask,
  								    "token_type_ids": token_type_ids,
  								}
  								_UpperCAmelCase =						model(a_   )
  								self.parent.assertEqual(result.logits.shape ,						(self.batch_size, self.seq_length, self.vocab_size)   )
  
  
  
  							def       _a   (      self   )							->							int:
  								_UpperCAmelCase =						self.prepare_config_and_inputs()
  
  								(
  								    (
  								    _UpperCAmelCase
  								) ,      (
  								    _UpperCAmelCase
  								) ,      (
  								    _UpperCAmelCase
  								) ,      (
  								    _UpperCAmelCase
  								) ,      (
  								    _UpperCAmelCase
  								) ,      (
  								    _UpperCAmelCase
  								) ,      (
  								    _UpperCAmelCase
  								) ,      (
  								    _UpperCAmelCase
  								) ,      (
  								    _UpperCAmelCase
  								) ,      
  								) =						config_and_inputs
  
  								_UpperCAmelCase =						{
  								    "input_ids": input_ids,
  								    "token_type_ids": token_type_ids,
  								    "attention_mask": input_mask,
  								}
  								return config, inputs_dict
  
  
  
  
  
  @require_tf
  class    _lowerCAmelCase						(						lowerCamelCase    ,       lowerCamelCase    ,       lowerCamelCase    ,       unittest.TestCase						):
  							lowercase_     :     List[Any]       =							(
  							    (TFGPTJForCausalLM, TFGPTJForSequenceClassification, TFGPTJForQuestionAnswering, TFGPTJModel)
  							    if is_tf_available()
  							    else ()
  							)
  
  							lowercase_     :     int       =							(TFGPTJForCausalLM,) if is_tf_available() else ()
  							lowercase_     :     Optional[Any]       =							(
  							    {
  							        '''feature-extraction''': TFGPTJModel,
  							        '''question-answering''': TFGPTJForQuestionAnswering,
  							        '''text-classification''': TFGPTJForSequenceClassification,
  							        '''text-generation''': TFGPTJForCausalLM,
  							        '''zero-shot''': TFGPTJForSequenceClassification,
  							    }
  							    if is_tf_available()
  							    else {}
  							)
  							lowercase_     :     Dict       =							False
  							lowercase_     :     Optional[int]       =							False
  							lowercase_     :     List[Any]       =							False
  							lowercase_     :     List[str]       =							False
  
  
  
  							def       _a   (      self ,						a_ ,						a_ ,						a_ ,						a_ ,						a_   )							->							List[str]:
  								if (
  								    pipeline_test_casse_name == "QAPipelineTests"
  								    and tokenizer_name is not None
  								    and not tokenizer_name.endswith("Fast"   )
  								):
  									# `QAPipelineTests` fails for a few models when the slower tokenizer are used.
  									# (The slower tokenizers were never used for pipeline tests before the pipeline testing rework)
  									# TODO: check (and possibly fix) the `QAPipelineTests` with slower tokenizer
  									return True
  
  								return False
  
  
  
  							def       _a   (      self   )							->							str:
  								_UpperCAmelCase =						TFGPTJModelTester(self   )
  								_UpperCAmelCase =						ConfigTester(self ,						config_class=a_ ,						n_embd=37   )
  
  
  
  							def       _a   (      self   )							->							Any:
  								self.config_tester.run_common_tests()
  
  
  
  							def       _a   (      self   )							->							Union[str, Any]:
  								_UpperCAmelCase =						self.model_tester.prepare_config_and_inputs()
  								self.model_tester.create_and_check_gptj_model(*a_   )
  
  
  
  							def       _a   (      self   )							->							List[Any]:
  								_UpperCAmelCase =						self.model_tester.prepare_config_and_inputs()
  								self.model_tester.create_and_check_gptj_model_past(*a_   )
  
  
  
  							def       _a   (      self   )							->							Optional[Any]:
  								_UpperCAmelCase =						self.model_tester.prepare_config_and_inputs()
  								self.model_tester.create_and_check_gptj_model_attention_mask_past(*a_   )
  
  
  
  							def       _a   (      self   )							->							List[str]:
  								_UpperCAmelCase =						self.model_tester.prepare_config_and_inputs()
  								self.model_tester.create_and_check_gptj_model_past_large_inputs(*a_   )
  
  
  
  							def       _a   (      self   )							->							int:
  								_UpperCAmelCase =						self.model_tester.prepare_config_and_inputs()
  								self.model_tester.create_and_check_gptj_lm_head_model(*a_   )
  
  
  
  							@slow
  							@unittest.skipIf(
  							    not is_tf_available() or len(tf.config.list_physical_devices("GPU"   )   ) > 0 ,						"skip testing on GPU for now to avoid GPU OOM." ,						)
  							def       _a   (      self   )							->							Optional[Any]:
  								_UpperCAmelCase =						TFGPTJModel.from_pretrained("EleutherAI/gpt-j-6B" ,						from_pt=a_   )
  								self.assertIsNotNone(a_   )
  
  
  
  							@unittest.skip(reason="Currently, model embeddings are going to undergo a major refactor."   )
  							def       _a   (      self   )							->							str:
  								super().test_resize_token_embeddings()
  
  
  
  
  
  @require_tf
  @tooslow
  # Marked as @tooslow due to GPU OOM -- but still useful to run locally. Requires ~39GB of RAM.
  class    _lowerCAmelCase						(						unittest.TestCase						):
  
  
  
  							def       _a   (      self   )							->							Tuple:
  								_UpperCAmelCase =						TFGPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B" ,						from_pt=a_   )
  								_UpperCAmelCase =						tf.convert_to_tensor([[464, 3290]] ,						dtype=tf.intaa   )  # The dog
  								# fmt: off
  								# The dog is a man's best friend. It is a loyal companion, and it is a friend
  								_UpperCAmelCase =						[464, 3290, 318, 257, 582, 338, 1266, 1545, 13, 632, 318, 257, 9112, 15185, 11, 290, 340, 318, 257, 1545]
  								# fmt: on
  								_UpperCAmelCase =						model.generate(a_ ,						do_sample=a_   )
  								self.assertListEqual(output_ids[0].numpy().tolist() ,						a_   )
  
  
  
  							def       _a   (      self   )							->							Dict:
  								_UpperCAmelCase =						AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B" ,						revision="float16"   )
  								_UpperCAmelCase =						TFGPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B" ,						revision="float16" ,						from_pt=a_   )
  
  								_UpperCAmelCase =						tokenizer("Today is a nice day and" ,						return_tensors="tf"   )
  								# forces the generation to happen on CPU, to avoid GPU-related quirks
  								with tf.device(":/CPU:0"   ):
  									_UpperCAmelCase =						model.generate(**a_ ,						do_sample=a_ ,						seed=[42, 0]   )
  								_UpperCAmelCase =						tokenizer.decode(output_ids[0] ,						skip_special_tokens=a_   )
  
  								_UpperCAmelCase =						"Today is a nice day and I’m going to go for a walk. I’"
  								self.assertEqual(a_ ,						a_   )
  
  
  
  							def       _a   (      self   )							->							int:
  								_UpperCAmelCase =						TFGPTJForCausalLM.from_pretrained("EleutherAI/gpt-j-6B" ,						revision="float16" ,						from_pt=a_   )
  								_UpperCAmelCase =						AutoTokenizer.from_pretrained("EleutherAI/gpt-j-6B" ,						revision="float16"   )
  
  								_UpperCAmelCase =						"left"
  
  								# Define PAD Token = EOS Token = 50256
  								_UpperCAmelCase =						tokenizer.eos_token
  								_UpperCAmelCase =						model.config.eos_token_id
  
  								# use different length sentences to test batching
  								_UpperCAmelCase =						[
  								    "Hello, my dog is a little",
  								    "Today, I",
  								]
  								_UpperCAmelCase =						[
  								    "Hello, my dog is a little over a year old and has been diagnosed with hip dysplasia",
  								    "Today, I’m going to be talking about a topic that’",
  								]
  								return model, tokenizer, sentences, expected_output_sentences
  
  
  
  							def       _a   (      self   )							->							Optional[Any]:
  								# Confirms that we get the expected results with left-padded beam search
  								_UpperCAmelCase ,      _UpperCAmelCase ,      _UpperCAmelCase ,      _UpperCAmelCase =						self._get_beam_search_test_objects()
  
  								_UpperCAmelCase =						tokenizer(a_ ,						return_tensors="tf" ,						padding=a_   )
  								_UpperCAmelCase =						model.generate(**a_ ,						do_sample=a_ ,						num_beams=2   )
  								_UpperCAmelCase =						tokenizer.batch_decode(a_ ,						skip_special_tokens=a_   )
  								self.assertListEqual(a_ ,						a_   )
  
  
  
  							def       _a   (      self   )							->							List[str]:
  								# Confirms that left-padding is working properly
  								_UpperCAmelCase ,      _UpperCAmelCase ,      _UpperCAmelCase ,      _UpperCAmelCase =						self._get_beam_search_test_objects()
  
  								_UpperCAmelCase =						tokenizer(a_ ,						return_tensors="tf" ,						padding=a_   )
  								_UpperCAmelCase =						tokenizer(sentences[0] ,						return_tensors="tf"   )
  								_UpperCAmelCase =						model.generate(**a_ ,						do_sample=a_ ,						num_beams=2   )
  								_UpperCAmelCase =						(
  								    shape_list(inputs_non_padded["input_ids"]   )[-1]
  								    - tf.reduce_sum(tf.cast(inputs["attention_mask"][-1] ,						tf.intaa   )   ).numpy()
  								)
  								_UpperCAmelCase =						tokenizer(sentences[1] ,						return_tensors="tf"   )
  								_UpperCAmelCase =						model.generate(
  								    **a_ ,						do_sample=a_ ,						num_beams=2 ,						max_length=model.config.max_length - num_paddings   )
  								_UpperCAmelCase =						tokenizer.decode(output_non_padded[0] ,						skip_special_tokens=a_   )
  								_UpperCAmelCase =						tokenizer.decode(output_padded[0] ,						skip_special_tokens=a_   )
  								self.assertListEqual(a_ ,						[non_padded_sentence, padded_sentence]   )
  
  
  
  							def       _a   (      self   )							->							str:
  								# Confirms that XLA is working properly
  								_UpperCAmelCase ,      _UpperCAmelCase ,      _UpperCAmelCase ,      _UpperCAmelCase =						self._get_beam_search_test_objects()
  
  								_UpperCAmelCase =						tokenizer(a_ ,						return_tensors="tf" ,						padding=a_   )
  								_UpperCAmelCase =						tf.function(model.generate ,						jit_compile=a_   )
  								_UpperCAmelCase =						xla_generate(**a_ ,						do_sample=a_ ,						num_beams=2   )
  								_UpperCAmelCase =						tokenizer.batch_decode(a_ ,						skip_special_tokens=a_   )
  								self.assertListEqual(a_ ,						a_   )
  
  
  
  
  
style_context: 
  """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     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__=0      ):
  
  
  	"""simple docstring"""
  
  
  
  
  
  
  	if name is None:
  		_UpperCAmelCase =						None
  	else:
  		_UpperCAmelCase =						"." * max(0				,     spaces - 2      ) + "# {:" + str(50 - spaces      ) + "s}"
  		_UpperCAmelCase =						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__      ):
  
  
  	"""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(*UpperCamelCase__      )
  		_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(*UpperCamelCase__      )
  		_UpperCAmelCase =						param.transpose(0				,     1      ).contiguous()
  	_UpperCAmelCase =						param.view(*UpperCamelCase__      )
  	return param
  
  
  
  
  def     __lowerCamelCase  (		UpperCamelCase__				,     UpperCamelCase__				,     UpperCamelCase__      ):
  
  
  	"""simple docstring"""
  
  
  
  
  
  
  	_UpperCAmelCase =						{}
  
  	# old versions did not store training args
  	_UpperCAmelCase =						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))
  
  		_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(UpperCamelCase__      )
  
  		# 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(UpperCamelCase__				,     UpperCamelCase__				,     3				,     UpperCamelCase__				,     UpperCamelCase__      )
  			# 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(UpperCamelCase__				,     UpperCamelCase__				,     3				,     UpperCamelCase__				,     UpperCamelCase__      )
  			# 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     __lowerCamelCase  (		):
  
  
  	"""simple docstring"""
  
  
  
  
  
  
  	_UpperCAmelCase =						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."				,     )
  	_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(UpperCamelCase__				,     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(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.
  	_UpperCAmelCase =						os.path.join(UpperCamelCase__				,     "pytorch_model.bin"      )
  	print(f"Saving checkpoint to \"{output_checkpoint_file}\""      )
  	torch.save(UpperCamelCase__				,     UpperCamelCase__      )
  
  
  ####################################################################################################
  
  if __name__ == "__main__":
  			main()
  
  ####################################################################################################
  
  
  
  
  