
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_video_inputs


if is_torch_available():
				import torch

if is_vision_available():
				from PIL import Image

				from transformers import VideoMAEImageProcessor







class 							UpperCAmelCase	(   unittest.TestCase					):

					def __init__(			self      :					List[str] ,      lowerCAmelCase      :					int ,      lowerCAmelCase      :					Tuple=7 ,      lowerCAmelCase      :					Any=3 ,      lowerCAmelCase      :					Any=10 ,      lowerCAmelCase      :					int=18 ,      lowerCAmelCase      :					Optional[int]=30 ,      lowerCAmelCase      :					Dict=400 ,      lowerCAmelCase      :					List[str]=True ,      lowerCAmelCase      :					str=None ,      lowerCAmelCase      :					List[str]=True ,      lowerCAmelCase      :					int=[0.5, 0.5, 0.5] ,      lowerCAmelCase      :					List[str]=[0.5, 0.5, 0.5] ,      lowerCAmelCase      :					str=None ,      ):
											lowercase       :    List[Any]											=  size if size is not None else {'''shortest_edge''': 18}
											lowercase       :    Tuple											=  crop_size if crop_size is not None else {'''height''': 18, '''width''': 18}

											lowercase       :    Optional[Any]											=  parent
											lowercase       :    Any											=  batch_size
											lowercase       :    int											=  num_channels
											lowercase       :    Union[str, Any]											=  num_frames
											lowercase       :    Optional[int]											=  image_size
											lowercase       :    Any											=  min_resolution
											lowercase       :    Union[str, Any]											=  max_resolution
											lowercase       :    str											=  do_resize
											lowercase       :    Tuple											=  size
											lowercase       :    Union[str, Any]											=  do_normalize
											lowercase       :    int											=  image_mean
											lowercase       :    List[str]											=  image_std
											lowercase       :    Optional[Any]											=  crop_size




					def        _lowerCAmelCase	(			self      :					str					):
											return {
											    "image_mean": self.image_mean,
											    "image_std": self.image_std,
											    "do_normalize": self.do_normalize,
											    "do_resize": self.do_resize,
											    "size": self.size,
											    "crop_size": self.crop_size,
											}







@require_torch
@require_vision
class 							UpperCAmelCase	(   __lowerCamelCase						, unittest.TestCase					):
					a__: int			  =				VideoMAEImageProcessor if is_vision_available() else None

					def        _lowerCAmelCase	(			self      :					Tuple					):
											lowercase       :    List[Any]											=  VideoMAEImageProcessingTester(self					)

					@property
					def        _lowerCAmelCase	(			self      :					str					):
											return self.image_processor_tester.prepare_image_processor_dict()

					def        _lowerCAmelCase	(			self      :					Tuple					):
											lowercase       :    int											=  self.image_processing_class(**self.image_processor_dict					)
											self.assertTrue(hasattr(lowerCAmelCase ,      '''image_mean'''					)					)
											self.assertTrue(hasattr(lowerCAmelCase ,      '''image_std'''					)					)
											self.assertTrue(hasattr(lowerCAmelCase ,      '''do_normalize'''					)					)
											self.assertTrue(hasattr(lowerCAmelCase ,      '''do_resize'''					)					)
											self.assertTrue(hasattr(lowerCAmelCase ,      '''do_center_crop'''					)					)
											self.assertTrue(hasattr(lowerCAmelCase ,      '''size'''					)					)

					def        _lowerCAmelCase	(			self      :					int					):
											lowercase       :    str											=  self.image_processing_class.from_dict(self.image_processor_dict					)
											self.assertEqual(image_processor.size ,      {'''shortest_edge''': 18}					)
											self.assertEqual(image_processor.crop_size ,      {'''height''': 18, '''width''': 18}					)

											lowercase       :    Tuple											=  self.image_processing_class.from_dict(self.image_processor_dict ,      size=42 ,      crop_size=84					)
											self.assertEqual(image_processor.size ,      {'''shortest_edge''': 42}					)
											self.assertEqual(image_processor.crop_size ,      {'''height''': 84, '''width''': 84}					)

					def        _lowerCAmelCase	(			self      :					List[str]					):
											pass

					def        _lowerCAmelCase	(			self      :					Optional[Any]					):
											# Initialize image_processing
											lowercase       :    Optional[Any]											=  self.image_processing_class(**self.image_processor_dict					)
											# create random PIL videos
											lowercase       :    Dict											=  prepare_video_inputs(self.image_processor_tester ,      equal_resolution=lowerCAmelCase					)
											for video in video_inputs:
																	self.assertIsInstance(lowerCAmelCase ,      lowerCAmelCase					)
																	self.assertIsInstance(video[0] ,      Image.Image					)

											# Test not batched input
											lowercase       :    Any											=  image_processing(video_inputs[0] ,      return_tensors='''pt'''					).pixel_values
											self.assertEqual(
											    encoded_videos.shape ,      (
											        1,
											        self.image_processor_tester.num_frames,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['''height'''],
											        self.image_processor_tester.crop_size['''width'''],
											    ) ,      )

											# Test batched
											lowercase       :    str											=  image_processing(lowerCAmelCase ,      return_tensors='''pt'''					).pixel_values
											self.assertEqual(
											    encoded_videos.shape ,      (
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_frames,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['''height'''],
											        self.image_processor_tester.crop_size['''width'''],
											    ) ,      )

					def        _lowerCAmelCase	(			self      :					int					):
											# Initialize image_processing
											lowercase       :    int											=  self.image_processing_class(**self.image_processor_dict					)
											# create random numpy tensors
											lowercase       :    List[str]											=  prepare_video_inputs(self.image_processor_tester ,      equal_resolution=lowerCAmelCase ,      numpify=lowerCAmelCase					)
											for video in video_inputs:
																	self.assertIsInstance(lowerCAmelCase ,      lowerCAmelCase					)
																	self.assertIsInstance(video[0] ,      np.ndarray					)

											# Test not batched input
											lowercase       :    Union[str, Any]											=  image_processing(video_inputs[0] ,      return_tensors='''pt'''					).pixel_values
											self.assertEqual(
											    encoded_videos.shape ,      (
											        1,
											        self.image_processor_tester.num_frames,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['''height'''],
											        self.image_processor_tester.crop_size['''width'''],
											    ) ,      )

											# Test batched
											lowercase       :    List[str]											=  image_processing(lowerCAmelCase ,      return_tensors='''pt'''					).pixel_values
											self.assertEqual(
											    encoded_videos.shape ,      (
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_frames,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['''height'''],
											        self.image_processor_tester.crop_size['''width'''],
											    ) ,      )




					def        _lowerCAmelCase	(			self      :					Any					):
											# Initialize image_processing
											lowercase       :    str											=  self.image_processing_class(**self.image_processor_dict					)
											# create random PyTorch tensors
											lowercase       :    Union[str, Any]											=  prepare_video_inputs(self.image_processor_tester ,      equal_resolution=lowerCAmelCase ,      torchify=lowerCAmelCase					)
											for video in video_inputs:
																	self.assertIsInstance(lowerCAmelCase ,      lowerCAmelCase					)
																	self.assertIsInstance(video[0] ,      torch.Tensor					)

											# Test not batched input
											lowercase       :    int											=  image_processing(video_inputs[0] ,      return_tensors='''pt'''					).pixel_values
											self.assertEqual(
											    encoded_videos.shape ,      (
											        1,
											        self.image_processor_tester.num_frames,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['''height'''],
											        self.image_processor_tester.crop_size['''width'''],
											    ) ,      )

											# Test batched
											lowercase       :    Union[str, Any]											=  image_processing(lowerCAmelCase ,      return_tensors='''pt'''					).pixel_values
											self.assertEqual(
											    encoded_videos.shape ,      (
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_frames,
											        self.image_processor_tester.num_channels,
											        self.image_processor_tester.crop_size['''height'''],
											        self.image_processor_tester.crop_size['''width'''],
											    ) ,      )




import argparse
import os
from os.path import isfile

import torch

from transformers import GPTaConfig

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

def        lowerCamelCase_      (			UpperCAmelCase_							:				List[str]							,			UpperCAmelCase_							:				Union[str, Any]       ):
						lowercase       :    str											=  config.n_positions
						lowercase       :    Union[str, Any]											=  config.n_layer
						lowercase       :    Optional[int]											=  config.vocab_size
						lowercase       :    Union[str, Any]											=  config.n_head
						lowercase       :    int											=  config.n_embd // config.n_head

						lowercase       :    Optional[Any]											=  sd_megatron['''model.language_model.embedding.word_embeddings.weight'''][:vocab_size, :]
						lowercase       :    Optional[int]											=  {
						    '''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'''],
						}

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

												lowercase       :    List[str]											=  sd_megatron[f'''{pf}{i}.input_layernorm.weight''']
												lowercase       :    Tuple											=  sd_megatron[f'''{pf}{i}.input_layernorm.bias''']

												lowercase       :    Any											=  sd_megatron[f'''{pf}{i}.self_attention.query_key_value.weight''']
												lowercase       :    Optional[int]											=  fix_query_key_value_ordering(UpperCAmelCase_							,			3							,			UpperCAmelCase_							,			UpperCAmelCase_       )
												lowercase       :    Tuple											=  vala.transpose(0							,			1       ).contiguous()

												lowercase       :    Tuple											=  sd_megatron[f'''{pf}{i}.self_attention.query_key_value.bias''']
												lowercase       :    Any											=  fix_query_key_value_ordering(UpperCAmelCase_							,			3							,			UpperCAmelCase_							,			UpperCAmelCase_       )
												lowercase       :    int											=  vala

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

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

						return sd_hf

def        lowerCamelCase_      (			UpperCAmelCase_							:				str							,			UpperCAmelCase_							:				str       ):
						lowercase       :    str											=  6_40_00
						lowercase       :    Union[str, Any]											=  config_megatron['''encoder_seq_length''']
						lowercase       :    Union[str, Any]											=  config_megatron['''hidden_size''']
						lowercase       :    Optional[Any]											=  config_megatron['''num_layers''']
						lowercase       :    int											=  config_megatron['''num_attention_heads''']
						lowercase       :    str											=  config_megatron['''ffn_hidden_size''']
						lowercase       :    Union[str, Any]											=  '''gelu'''
						lowercase       :    Tuple											=  0.1
						lowercase       :    str											=  0.1
						lowercase       :    str											=  0.1
						lowercase       :    Dict											=  config_megatron['''layernorm_epsilon''']  # 1e-5
						lowercase       :    str											=  config_megatron['''init_method_std''']  # 0.02
						lowercase       :    Optional[int]											=  config_megatron['''apply_query_key_layer_scaling''']  # True
						lowercase       :    Union[str, Any]											=  True
						lowercase       :    int											=  True

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

						return config_hf

def        lowerCamelCase_      (			UpperCAmelCase_							:				Tuple       ):
						print(UpperCAmelCase_       )

						lowercase       :    List[Any]											=  args.checkpoint_path
						lowercase       :    Dict											=  args.save_path
						if isfile(UpperCAmelCase_       ):
												raise FileNotFoundError(f'''ERROR! could not find file {checkpoint_path}'''       )

						# Load the model.
						lowercase       :    Optional[int]											=  torch.load(UpperCAmelCase_							,			map_location='''cpu'''       )

						# Load the config.
						lowercase       :    Any											=  checkpoint['''hyper_parameters''']['''cfg''']
						lowercase       :    Dict											=  GPTaConfig()
						lowercase       :    Dict											=  copy_config(config_hf=UpperCAmelCase_							,			config_megatron=UpperCAmelCase_       )
						lowercase       :    Any											=  ['''GPT2LMHeadModel''']

						lowercase       :    List[Any]											=  checkpoint['''state_dict''']

						# Convert.
						print('''Converting'''       )
						lowercase       :    Dict											=  convert_megatron_checkpoint(UpperCAmelCase_							,			UpperCAmelCase_       )

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

						lowercase       :    List[Any]											=  '''GPTSw3Tokenizer'''

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

						# Store the state_dict to file.
						lowercase       :    Union[str, Any]											=  os.path.join(UpperCAmelCase_							,			'''pytorch_model.bin'''       )
						print(f'''Saving checkpoint to "{output_checkpoint_file}"'''       )
						torch.save(UpperCAmelCase_							,			UpperCAmelCase_       )


if __name__ == "__main__":
				snake_case__  							=							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""")
				snake_case__  							=							parser.parse_args()
				main(_args)


