
"""simple docstring"""





import argparse
import os
from os.path import isfile

import torch

from transformers import GPTaConfig







def       __a	(						__lowerCamelCase,						__lowerCamelCase,						__lowerCamelCase=0    ):
   # Format the message.
   if name is None:
      UpperCAmelCase_   :   str     	=       None
   else:
      UpperCAmelCase_   :   Tuple     	=       "." * max(0,						spaces - 2    ) + "# {:" + str(50 - spaces    ) + "s}"
      UpperCAmelCase_   :   Optional[int]     	=       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       __a	(						__lowerCamelCase,						__lowerCamelCase,						__lowerCamelCase,						__lowerCamelCase    ):
   # 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 GPT2.
   UpperCAmelCase_   :   Any     	=       param.size()
   # other versions store [num_heads * num_splits * hidden_size, :]
   UpperCAmelCase_   :   List[Any]     	=       (num_heads, num_splits, hidden_size) + input_shape[1:]
   UpperCAmelCase_   :   List[Any]     	=       param.view(*__lowerCamelCase    )
   UpperCAmelCase_   :   List[str]     	=       param.transpose(0,						1    ).contiguous()
   UpperCAmelCase_   :   Union[str, Any]     	=       param.view(*__lowerCamelCase    )
   return param







def       __a	(						__lowerCamelCase,						__lowerCamelCase    ):
   UpperCAmelCase_   :   Dict     	=       config.n_positions
   UpperCAmelCase_   :   Optional[int]     	=       config.n_layer
   UpperCAmelCase_   :   Any     	=       config.vocab_size
   UpperCAmelCase_   :   Optional[Any]     	=       config.n_head
   UpperCAmelCase_   :   Optional[int]     	=       config.n_embd // config.n_head

   UpperCAmelCase_   :   Union[str, Any]     	=       sd_megatron["model.language_model.embedding.word_embeddings.weight"][:vocab_size, :]
   UpperCAmelCase_   :   Union[str, Any]     	=       {
       "transformer.wte.weight": word_embeddings,
       "transformer.wpe.weight": sd_megatron["model.language_model.embedding.position_embeddings.weight"],
       "transformer.ln_f.weight": sd_megatron["model.language_model.encoder.final_layernorm.weight"],
       "transformer.ln_f.bias": sd_megatron["model.language_model.encoder.final_layernorm.bias"],
   }

   UpperCAmelCase_   :   Union[str, Any]     	=       "model.language_model.encoder.layers."
   for i in range(__lowerCamelCase    ):
      UpperCAmelCase_   :   Tuple     	=       torch.tril(torch.ones((n_positions, n_positions),						dtype=torch.bool    )    )
      UpperCAmelCase_   :   Optional[int]     	=       causal_mask.view(1,						1,						__lowerCamelCase,						__lowerCamelCase    )
      UpperCAmelCase_   :   Any     	=       causal_mask
      UpperCAmelCase_   :   List[Any]     	=       torch.tensor(-1E4,						dtype=torch.bfloataa    )

      UpperCAmelCase_   :   List[str]     	=       sd_megatron[f"""{pf}{i}.input_layernorm.weight"""]
      UpperCAmelCase_   :   Union[str, Any]     	=       sd_megatron[f"""{pf}{i}.input_layernorm.bias"""]

      UpperCAmelCase_   :   List[Any]     	=       sd_megatron[f"""{pf}{i}.self_attention.query_key_value.weight"""]
      UpperCAmelCase_   :   List[Any]     	=       fix_query_key_value_ordering(__lowerCamelCase,						3,						__lowerCamelCase,						__lowerCamelCase    )
      UpperCAmelCase_   :   Optional[Any]     	=       vala.transpose(0,						1    ).contiguous()

      UpperCAmelCase_   :   Any     	=       sd_megatron[f"""{pf}{i}.self_attention.query_key_value.bias"""]
      UpperCAmelCase_   :   Dict     	=       fix_query_key_value_ordering(__lowerCamelCase,						3,						__lowerCamelCase,						__lowerCamelCase    )
      UpperCAmelCase_   :   List[str]     	=       vala

      UpperCAmelCase_   :   List[Any]     	=       sd_megatron[f"""{pf}{i}.self_attention.dense.weight"""].transpose(
          0,						1    )
      UpperCAmelCase_   :   Union[str, Any]     	=       sd_megatron[f"""{pf}{i}.self_attention.dense.bias"""]
      UpperCAmelCase_   :   str     	=       sd_megatron[f"""{pf}{i}.post_attention_layernorm.weight"""]
      UpperCAmelCase_   :   Union[str, Any]     	=       sd_megatron[f"""{pf}{i}.post_attention_layernorm.bias"""]
      UpperCAmelCase_   :   List[Any]     	=       sd_megatron[f"""{pf}{i}.mlp.dense_h_to_4h.weight"""].transpose(0,						1    )
      UpperCAmelCase_   :   Any     	=       sd_megatron[f"""{pf}{i}.mlp.dense_h_to_4h.bias"""]
      UpperCAmelCase_   :   int     	=       sd_megatron[f"""{pf}{i}.mlp.dense_4h_to_h.weight"""].transpose(
          0,						1    )
      UpperCAmelCase_   :   Optional[Any]     	=       sd_megatron[f"""{pf}{i}.mlp.dense_4h_to_h.bias"""]

   # For LM head, transformers' wants the matrix to weight embeddings.
   UpperCAmelCase_   :   Tuple     	=       word_embeddings

   return sd_hf







def       __a	(						__lowerCamelCase,						__lowerCamelCase    ):
   UpperCAmelCase_   :   int     	=       6_4000
   UpperCAmelCase_   :   List[Any]     	=       config_megatron["encoder_seq_length"]
   UpperCAmelCase_   :   Dict     	=       config_megatron["hidden_size"]
   UpperCAmelCase_   :   List[Any]     	=       config_megatron["num_layers"]
   UpperCAmelCase_   :   Optional[Any]     	=       config_megatron["num_attention_heads"]
   UpperCAmelCase_   :   Optional[Any]     	=       config_megatron["ffn_hidden_size"]
   UpperCAmelCase_   :   List[str]     	=       "gelu"
   UpperCAmelCase_   :   Tuple     	=       0.1
   UpperCAmelCase_   :   Any     	=       0.1
   UpperCAmelCase_   :   Dict     	=       0.1
   UpperCAmelCase_   :   Optional[Any]     	=       config_megatron["layernorm_epsilon"]  # 1e-5
   UpperCAmelCase_   :   Dict     	=       config_megatron["init_method_std"]  # 0.02
   UpperCAmelCase_   :   Optional[int]     	=       config_megatron["apply_query_key_layer_scaling"]  # True
   UpperCAmelCase_   :   List[Any]     	=       True
   UpperCAmelCase_   :   str     	=       True

   # This identifies the 6.7B (7B) model which uses a different tokenizer
   if config_megatron["hidden_size"] == 4096:
      UpperCAmelCase_   :   Optional[int]     	=       1  # <|endoftext|>
      UpperCAmelCase_   :   Optional[Any]     	=       1  # <|endoftext|>
      UpperCAmelCase_   :   List[Any]     	=       0  # <unk>
   else:
      UpperCAmelCase_   :   str     	=       2  # <s>
      UpperCAmelCase_   :   List[str]     	=       3  # <|endoftext|>
      UpperCAmelCase_   :   List[Any]     	=       0  # <pad>

   return config_hf







def       __a	(						__lowerCamelCase    ):
   print(__lowerCamelCase    )

   UpperCAmelCase_   :   Optional[int]     	=       args.checkpoint_path
   UpperCAmelCase_   :   Dict     	=       args.save_path
   if isfile(__lowerCamelCase    ):
      raise FileNotFoundError(f"""ERROR! could not find file {checkpoint_path}"""    )

   # Load the model.
   UpperCAmelCase_   :   List[Any]     	=       torch.load(__lowerCamelCase,						map_location="cpu"    )

   # Load the config.
   UpperCAmelCase_   :   List[str]     	=       checkpoint["hyper_parameters"]["cfg"]
   UpperCAmelCase_   :   str     	=       GPTaConfig()
   UpperCAmelCase_   :   Tuple     	=       copy_config(config_hf=__lowerCamelCase,						config_megatron=__lowerCamelCase    )
   UpperCAmelCase_   :   List[str]     	=       ["GPT2LMHeadModel"]

   UpperCAmelCase_   :   int     	=       checkpoint["state_dict"]

   # Convert.
   print("Converting"    )
   UpperCAmelCase_   :   Optional[Any]     	=       convert_megatron_checkpoint(__lowerCamelCase,						__lowerCamelCase    )

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

   UpperCAmelCase_   :   Tuple     	=       "GPTSw3Tokenizer"

   # Store the config to file.
   print("Saving config"    )
   config_hf.save_pretrained(__lowerCamelCase    )

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


if __name__ == "__main__":
    _a									=				argparse.ArgumentParser()
    parser.add_argument(
        '--checkpoint_path',
        type=str,
        required=True,
        help='e.g. megatron_gpt--val_loss=2.42-step=38000-consumed_samples=54720000',
    )
    parser.add_argument('--save_path', type=str, required=True, help='e.g. /home/user/gpt-sw3/hf')
    parser.add_argument('--print-checkpoint-structure', action='store_true')
    _a									=				parser.parse_args()
    main(_args)








import argparse
import json
import logging
import os
import sys
from unittest import skip
from unittest.mock import patch

import tensorflow as tf

from transformers.testing_utils import TestCasePlus, get_gpu_count, slow


UpperCAmelCase__    :							Any       		=     [
    os.path.join(os.path.dirname(__file__), dirname)
    for dirname in [
        'text-generation',
        'text-classification',
        'token-classification',
        'language-modeling',
        'multiple-choice',
        'question-answering',
        'summarization',
        'translation',
        'image-classification',
    ]
]
sys.path.extend(SRC_DIRS)


if SRC_DIRS is not None:
   import run_clm
   import run_image_classification
   import run_mlm
   import run_ner
   import run_qa as run_squad
   import run_summarization
   import run_swag
   import run_text_classification
   import run_translation


logging.basicConfig(level=logging.DEBUG)

UpperCAmelCase__    :							Union[str, Any]       		=     logging.getLogger()


def 		_lowerCamelCase					(       )      ->		str:





  """simple docstring"""





  _lowercase:			int      =     argparse.ArgumentParser()
  parser.add_argument('-f'				)
  _lowercase:			Optional[Any]      =     parser.parse_args()
  return args.f


def 		_lowerCamelCase					(       UpperCamelCase				)      ->		Dict:





  """simple docstring"""





  _lowercase:			str      =     {}
  _lowercase:			Union[str, Any]      =     os.path.join(UpperCamelCase       ,  'all_results.json'				)
  if os.path.exists(UpperCamelCase				):
    with open(UpperCamelCase       ,  'r'				) as f:
      _lowercase:			Dict      =     json.load(UpperCamelCase				)
  else:
    raise ValueError(F'can\'t find {path}'				)
  return results


def 		_lowerCamelCase					(       )      ->		Any:





  """simple docstring"""





  return bool(tf.config.list_physical_devices('GPU'				)				)


UpperCAmelCase__    :							List[Any]       		=     logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)





class   UpperCAmelCase    (      A ):






   @skip('Skipping until shape inference for to_tf_dataset PR is merged.'  )
   def 			_a    (						self :							Union[str, Any]  )->      Optional[Any]:
     _lowercase:			List[str]      =     self.get_auto_remove_tmp_dir()
     _lowercase:			List[str]      =     f'\n            run_text_classification.py\n            --model_name_or_path distilbert-base-uncased\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --train_file ./tests/fixtures/tests_samples/MRPC/train.csv\n            --validation_file ./tests/fixtures/tests_samples/MRPC/dev.csv\n            --do_train\n            --do_eval\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --learning_rate=1e-4\n            --max_steps=10\n            --warmup_steps=2\n            --seed=42\n            --max_seq_length=128\n            '.split()

     if is_cuda_available():
       testargs.append('--fp16'  )

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_text_classification.main()
       # Reset the mixed precision policy so we don't break other tests
       tf.keras.mixed_precision.set_global_policy('float32'  )
       _lowercase:			List[str]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['eval_accuracy']    ,       0.75  )






   def 			_a    (						self :							Optional[Any]  )->      int:
     _lowercase:			Dict      =     self.get_auto_remove_tmp_dir()
     _lowercase:			str      =     f'\n            run_clm.py\n            --model_name_or_path distilgpt2\n            --train_file ./tests/fixtures/sample_text.txt\n            --validation_file ./tests/fixtures/sample_text.txt\n            --do_train\n            --do_eval\n            --block_size 128\n            --per_device_train_batch_size 2\n            --per_device_eval_batch_size 1\n            --num_train_epochs 2\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            '.split()

     if len(tf.config.list_physical_devices('GPU'  )  ) > 1:
       # Skipping because there are not enough batches to train the model + would need a drop_last to work.
       return

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_clm.main()
       _lowercase:			str      =     get_results(UpperCamelCase_  )
       self.assertLess(result['eval_perplexity']    ,       1_00  )






   def 			_a    (						self :							Union[str, Any]  )->      Optional[int]:
     _lowercase:			int      =     self.get_auto_remove_tmp_dir()
     _lowercase:			int      =     f'\n            run_mlm.py\n            --model_name_or_path distilroberta-base\n            --train_file ./tests/fixtures/sample_text.txt\n            --validation_file ./tests/fixtures/sample_text.txt\n            --max_seq_length 64\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --do_train\n            --do_eval\n            --prediction_loss_only\n            --num_train_epochs=1\n            --learning_rate=1e-4\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_mlm.main()
       _lowercase:			str      =     get_results(UpperCamelCase_  )
       self.assertLess(result['eval_perplexity']    ,       42  )






   def 			_a    (						self :							int  )->      Any:
     # with so little data distributed training needs more epochs to get the score on par with 0/1 gpu
     _lowercase:			List[Any]      =     7 if get_gpu_count() > 1 else 2

     _lowercase:			Dict      =     self.get_auto_remove_tmp_dir()
     _lowercase:			Optional[int]      =     f'\n            run_ner.py\n            --model_name_or_path bert-base-uncased\n            --train_file tests/fixtures/tests_samples/conll/sample.json\n            --validation_file tests/fixtures/tests_samples/conll/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --do_train\n            --do_eval\n            --warmup_steps=2\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=2\n            --num_train_epochs={epochs}\n            --seed 7\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_ner.main()
       _lowercase:			Optional[Any]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['accuracy']    ,       0.75  )






   def 			_a    (						self :							Tuple  )->      Optional[int]:
     _lowercase:			List[Any]      =     self.get_auto_remove_tmp_dir()
     _lowercase:			int      =     f'\n            run_qa.py\n            --model_name_or_path bert-base-uncased\n            --version_2_with_negative\n            --train_file tests/fixtures/tests_samples/SQUAD/sample.json\n            --validation_file tests/fixtures/tests_samples/SQUAD/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --max_steps=10\n            --warmup_steps=2\n            --do_train\n            --do_eval\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_squad.main()
       _lowercase:			Union[str, Any]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['f1']    ,       30  )
       self.assertGreaterEqual(result['exact']    ,       30  )






   def 			_a    (						self :							List[str]  )->      Tuple:
     _lowercase:			str      =     self.get_auto_remove_tmp_dir()
     _lowercase:			Any      =     f'\n            run_swag.py\n            --model_name_or_path bert-base-uncased\n            --train_file tests/fixtures/tests_samples/swag/sample.json\n            --validation_file tests/fixtures/tests_samples/swag/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --max_steps=20\n            --warmup_steps=2\n            --do_train\n            --do_eval\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_swag.main()
       _lowercase:			List[str]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['val_accuracy']    ,       0.8  )






   @slow
   def 			_a    (						self :							Dict  )->      Tuple:
     _lowercase:			Dict      =     self.get_auto_remove_tmp_dir()
     _lowercase:			str      =     f'\n            run_summarization.py\n            --model_name_or_path t5-small\n            --train_file tests/fixtures/tests_samples/xsum/sample.json\n            --validation_file tests/fixtures/tests_samples/xsum/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --max_steps=50\n            --warmup_steps=8\n            --do_train\n            --do_eval\n            --learning_rate=2e-4\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_summarization.main()
       _lowercase:			List[str]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['rouge1']    ,       10  )
       self.assertGreaterEqual(result['rouge2']    ,       2  )
       self.assertGreaterEqual(result['rougeL']    ,       7  )
       self.assertGreaterEqual(result['rougeLsum']    ,       7  )






   @slow
   def 			_a    (						self :							Tuple  )->      str:
     _lowercase:			List[Any]      =     self.get_auto_remove_tmp_dir()
     _lowercase:			List[str]      =     f'\n            run_translation.py\n            --model_name_or_path Rocketknight1/student_marian_en_ro_6_1\n            --source_lang en\n            --target_lang ro\n            --train_file tests/fixtures/tests_samples/wmt16/sample.json\n            --validation_file tests/fixtures/tests_samples/wmt16/sample.json\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --warmup_steps=8\n            --do_train\n            --do_eval\n            --learning_rate=3e-3\n            --num_train_epochs 12\n            --per_device_train_batch_size=2\n            --per_device_eval_batch_size=1\n            --source_lang en_XX\n            --target_lang ro_RO\n        '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_translation.main()
       _lowercase:			Optional[int]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['bleu']    ,       30  )






   def 			_a    (						self :							int  )->      List[Any]:
     _lowercase:			str      =     self.get_auto_remove_tmp_dir()
     _lowercase:			Dict      =     f'\n            run_image_classification.py\n            --dataset_name hf-internal-testing/cats_vs_dogs_sample\n            --model_name_or_path microsoft/resnet-18\n            --do_train\n            --do_eval\n            --learning_rate 1e-4\n            --per_device_train_batch_size 2\n            --per_device_eval_batch_size 1\n            --output_dir {tmp_dir}\n            --overwrite_output_dir\n            --dataloader_num_workers 16\n            --num_train_epochs 2\n            --train_val_split 0.1\n            --seed 42\n            --ignore_mismatched_sizes True\n            '.split()

     with patch.object(UpperCamelCase_    ,       'argv'    ,       UpperCamelCase_  ):
       run_image_classification.main()
       _lowercase:			Union[str, Any]      =     get_results(UpperCamelCase_  )
       self.assertGreaterEqual(result['accuracy']    ,       0.7  )
