






"""simple docstring"""



import argparse
import os
from os.path import isfile

import torch

from transformers import GPTaConfig
def 		_SCREAMING_SNAKE_CASE					(       __snake_case     :    List[str]						,   __snake_case     :    Dict						,   __snake_case     :    str=0       ):





  '''simple docstring'''





  if name is None:
    lowercase				       =			None
  else:
    lowercase				       =			'.' * max(0						,   spaces - 2       ) + '# {:' + str(50 - spaces       ) + 's}'
    lowercase				       =			fmt.format(__snake_case       )

  # Print and recurse (if needed).
  if isinstance(__snake_case						,   __snake_case       ):
    if msg is not None:
      print(__snake_case       )
    for k in val.keys():
      recursive_print(__snake_case						,   val[k]						,   spaces + 2       )
  elif isinstance(__snake_case						,   torch.Tensor       ):
    print(__snake_case						,   ':'						,   val.size()       )
  else:
    print(__snake_case						,   ':'						,   __snake_case       )
def 		_SCREAMING_SNAKE_CASE					(       __snake_case     :    List[str]						,   __snake_case     :    List[str]						,   __snake_case     :    str						,   __snake_case     :    str       ):





  '''simple docstring'''





  lowercase				       =			param.size()
  # other versions store [num_heads * num_splits * hidden_size, :]
  lowercase				       =			(num_heads, num_splits, hidden_size) + input_shape[1:]
  lowercase				       =			param.view(*__snake_case       )
  lowercase				       =			param.transpose(0						,   1       ).contiguous()
  lowercase				       =			param.view(*__snake_case       )
  return param
def 		_SCREAMING_SNAKE_CASE					(       __snake_case     :    str						,   __snake_case     :    int       ):





  '''simple docstring'''





  lowercase				       =			config.n_positions
  lowercase				       =			config.n_layer
  lowercase				       =			config.vocab_size
  lowercase				       =			config.n_head
  lowercase				       =			config.n_embd // config.n_head

  lowercase				       =			sd_megatron['model.language_model.embedding.word_embeddings.weight'][:vocab_size, :]
  lowercase				       =			{
      '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				       =			'model.language_model.encoder.layers.'
  for i in range(__snake_case       ):
    lowercase				       =			torch.tril(torch.ones((n_positions, n_positions)						,   dtype=torch.bool       )       )
    lowercase				       =			causal_mask.view(1						,   1						,   __snake_case						,   __snake_case       )
    lowercase				       =			causal_mask
    lowercase				       =			torch.tensor(-1e4						,   dtype=torch.bfloataa       )

    lowercase				       =			sd_megatron[f'{pf}{i}.input_layernorm.weight']
    lowercase				       =			sd_megatron[f'{pf}{i}.input_layernorm.bias']

    lowercase				       =			sd_megatron[f'{pf}{i}.self_attention.query_key_value.weight']
    lowercase				       =			fix_query_key_value_ordering(__snake_case						,   3						,   __snake_case						,   __snake_case       )
    lowercase				       =			vala.transpose(0						,   1       ).contiguous()

    lowercase				       =			sd_megatron[f'{pf}{i}.self_attention.query_key_value.bias']
    lowercase				       =			fix_query_key_value_ordering(__snake_case						,   3						,   __snake_case						,   __snake_case       )
    lowercase				       =			vala

    lowercase				       =			sd_megatron[f'{pf}{i}.self_attention.dense.weight'].transpose(
        0						,   1       )
    lowercase				       =			sd_megatron[f'{pf}{i}.self_attention.dense.bias']
    lowercase				       =			sd_megatron[f'{pf}{i}.post_attention_layernorm.weight']
    lowercase				       =			sd_megatron[f'{pf}{i}.post_attention_layernorm.bias']
    lowercase				       =			sd_megatron[f'{pf}{i}.mlp.dense_h_to_4h.weight'].transpose(0						,   1       )
    lowercase				       =			sd_megatron[f'{pf}{i}.mlp.dense_h_to_4h.bias']
    lowercase				       =			sd_megatron[f'{pf}{i}.mlp.dense_4h_to_h.weight'].transpose(
        0						,   1       )
    lowercase				       =			sd_megatron[f'{pf}{i}.mlp.dense_4h_to_h.bias']

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

  return sd_hf
def 		_SCREAMING_SNAKE_CASE					(       __snake_case     :    Dict						,   __snake_case     :    int       ):





  '''simple docstring'''





  lowercase				       =			6_40_00
  lowercase				       =			config_megatron['encoder_seq_length']
  lowercase				       =			config_megatron['hidden_size']
  lowercase				       =			config_megatron['num_layers']
  lowercase				       =			config_megatron['num_attention_heads']
  lowercase				       =			config_megatron['ffn_hidden_size']
  lowercase				       =			'gelu'
  lowercase				       =			0.1
  lowercase				       =			0.1
  lowercase				       =			0.1
  lowercase				       =			config_megatron['layernorm_epsilon']  # 1e-5
  lowercase				       =			config_megatron['init_method_std']  # 0.02
  lowercase				       =			config_megatron['apply_query_key_layer_scaling']  # True
  lowercase				       =			True
  lowercase				       =			True

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

  return config_hf
def 		_SCREAMING_SNAKE_CASE					(       __snake_case     :    Any       ):





  '''simple docstring'''





  print(__snake_case       )

  lowercase				       =			args.checkpoint_path
  lowercase				       =			args.save_path
  if isfile(__snake_case       ):
    raise FileNotFoundError(f'ERROR! could not find file {checkpoint_path}'       )

  # Load the model.
  lowercase				       =			torch.load(__snake_case						,   map_location='cpu'       )

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

  lowercase				       =			checkpoint['state_dict']

  # Convert.
  print('Converting'       )
  lowercase				       =			convert_megatron_checkpoint(__snake_case						,   __snake_case       )

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

  lowercase				       =			'GPTSw3Tokenizer'

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

  # Store the state_dict to file.
  lowercase				       =			os.path.join(__snake_case						,   'pytorch_model.bin'       )
  print(f'Saving checkpoint to "{output_checkpoint_file}"'       )
  torch.save(__snake_case						,   __snake_case       )


if __name__ == "__main__":
    _UpperCamelCase						:    List[Any]		=						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')
    _UpperCamelCase						:    Optional[Any]		=						parser.parse_args()
    main(_args)








from __future__ import annotations

import inspect
import unittest
from typing import List, Tuple

from transformers import ConvNextConfig
from transformers.testing_utils import require_tf, require_vision, slow
from transformers.utils import cached_property, is_tf_available, is_vision_available

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, floats_tensor, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
		import tensorflow as tf

		from transformers import TFConvNextForImageClassification, TFConvNextModel


if is_vision_available():
		from PIL import Image

		from transformers import ConvNextImageProcessor


class 				__UpperCamelCase      :





				'''simple docstring'''



				def __init__(			self							,			UpperCAmelCase_							,			UpperCAmelCase_=13							,			UpperCAmelCase_=32							,			UpperCAmelCase_=3							,			UpperCAmelCase_=4							,			UpperCAmelCase_=[10, 20, 30, 40]							,			UpperCAmelCase_=[2, 2, 3, 2]							,			UpperCAmelCase_=True							,			UpperCAmelCase_=True							,			UpperCAmelCase_=37							,			UpperCAmelCase_="gelu"							,			UpperCAmelCase_=10							,			UpperCAmelCase_=0.02							,			UpperCAmelCase_=3							,			UpperCAmelCase_=None							,			):
											lowerCAmelCase =		parent
											lowerCAmelCase =		batch_size
											lowerCAmelCase =		image_size
											lowerCAmelCase =		num_channels
											lowerCAmelCase =		num_stages
											lowerCAmelCase =		hidden_sizes
											lowerCAmelCase =		depths
											lowerCAmelCase =		is_training
											lowerCAmelCase =		use_labels
											lowerCAmelCase =		intermediate_size
											lowerCAmelCase =		hidden_act
											lowerCAmelCase =		type_sequence_label_size
											lowerCAmelCase =		initializer_range
											lowerCAmelCase =		scope



				def    __snake_case		(			self    ):
											lowerCAmelCase =		floats_tensor([self.batch_size, self.num_channels, self.image_size, self.image_size]    )

											lowerCAmelCase =		None
											if self.use_labels:
																		lowerCAmelCase =		ids_tensor([self.batch_size]							,			self.type_sequence_label_size    )

											lowerCAmelCase =		self.get_config()

											return config, pixel_values, labels



				def    __snake_case		(			self    ):
											return ConvNextConfig(
											    num_channels=self.num_channels							,			hidden_sizes=self.hidden_sizes							,			depths=self.depths							,			num_stages=self.num_stages							,			hidden_act=self.hidden_act							,			is_decoder=UpperCAmelCase_							,			initializer_range=self.initializer_range							,			)



				def    __snake_case		(			self							,			UpperCAmelCase_							,			UpperCAmelCase_							,			UpperCAmelCase_    ):
											lowerCAmelCase =		TFConvNextModel(config=UpperCAmelCase_    )
											lowerCAmelCase =		model(UpperCAmelCase_							,			training=UpperCAmelCase_    )
											# expected last hidden states: B, C, H // 32, W // 32
											self.parent.assertEqual(
											    result.last_hidden_state.shape							,			(self.batch_size, self.hidden_sizes[-1], self.image_size // 32, self.image_size // 32)							,			)



				def    __snake_case		(			self							,			UpperCAmelCase_							,			UpperCAmelCase_							,			UpperCAmelCase_    ):
											lowerCAmelCase =		self.type_sequence_label_size
											lowerCAmelCase =		TFConvNextForImageClassification(UpperCAmelCase_    )
											lowerCAmelCase =		model(UpperCAmelCase_							,			labels=UpperCAmelCase_							,			training=UpperCAmelCase_    )
											self.parent.assertEqual(result.logits.shape							,			(self.batch_size, self.type_sequence_label_size)    )






				def    __snake_case		(			self    ):
											lowerCAmelCase =		self.prepare_config_and_inputs()
											lowerCAmelCase ,  lowerCAmelCase ,  lowerCAmelCase =		config_and_inputs
											lowerCAmelCase =		{'''pixel_values''': pixel_values}
											return config, inputs_dict




@require_tf
class 				__UpperCamelCase      (			__UpperCAmelCase  ,       __UpperCAmelCase  ,       unittest.TestCase	):





				'''simple docstring'''



				__a				:			Union[str, Any]					    =(TFConvNextModel, TFConvNextForImageClassification) if is_tf_available() else ()
				__a				:			Optional[int]					    =(
				    {"""feature-extraction""": TFConvNextModel, """image-classification""": TFConvNextForImageClassification}
				    if is_tf_available()
				    else {}
				)

				__a				:			Any					    =False
				__a				:			int					    =False
				__a				:			Union[str, Any]					    =False
				__a				:			Optional[Any]					    =False
				__a				:			List[Any]					    =False



				def    __snake_case		(			self    ):
											lowerCAmelCase =		TFConvNextModelTester(self    )
											lowerCAmelCase =		ConfigTester(
											    self							,			config_class=UpperCAmelCase_							,			has_text_modality=UpperCAmelCase_							,			hidden_size=37							,			)



				@unittest.skip(reason='''ConvNext does not use inputs_embeds'''    )
				def    __snake_case		(			self    ):
											pass



				@unittest.skipIf(
				    not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''    )    ) == 0							,			reason='''TF does not support backprop for grouped convolutions on CPU.'''							,			)
				@slow
				def    __snake_case		(			self    ):
											super().test_keras_fit()



				@unittest.skip(reason='''ConvNext does not support input and output embeddings'''    )
				def    __snake_case		(			self    ):
											pass



				def    __snake_case		(			self    ):
											lowerCAmelCase ,  lowerCAmelCase =		self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																		lowerCAmelCase =		model_class(UpperCAmelCase_    )
																		lowerCAmelCase =		inspect.signature(model.call    )
																		# signature.parameters is an OrderedDict => so arg_names order is deterministic
																		lowerCAmelCase =		[*signature.parameters.keys()]

																		lowerCAmelCase =		['''pixel_values''']
																		self.assertListEqual(arg_names[:1]							,			UpperCAmelCase_    )



				def    __snake_case		(			self    ):
											lowerCAmelCase =		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_model(*UpperCAmelCase_    )



				@unittest.skipIf(
				    not is_tf_available() or len(tf.config.list_physical_devices('''GPU'''    )    ) == 0							,			reason='''TF does not support backprop for grouped convolutions on CPU.'''							,			)
				def    __snake_case		(			self    ):
											super().test_dataset_conversion()



				def    __snake_case		(			self    ):
											def check_hidden_states_output(UpperCAmelCase_							,			UpperCAmelCase_							,			UpperCAmelCase_    ):
																		lowerCAmelCase =		model_class(UpperCAmelCase_    )

																		lowerCAmelCase =		model(**self._prepare_for_class(UpperCAmelCase_							,			UpperCAmelCase_    )    )
																		lowerCAmelCase =		outputs.encoder_hidden_states if config.is_encoder_decoder else outputs.hidden_states

																		lowerCAmelCase =		self.model_tester.num_stages
																		self.assertEqual(len(UpperCAmelCase_    )							,			expected_num_stages + 1    )

																		# ConvNext's feature maps are of shape (batch_size, num_channels, height, width)
																		self.assertListEqual(
																		    list(hidden_states[0].shape[-2:]    )							,			[self.model_tester.image_size // 4, self.model_tester.image_size // 4]							,			)

											lowerCAmelCase ,  lowerCAmelCase =		self.model_tester.prepare_config_and_inputs_for_common()

											for model_class in self.all_model_classes:
																		lowerCAmelCase =		True
																		check_hidden_states_output(UpperCAmelCase_							,			UpperCAmelCase_							,			UpperCAmelCase_    )

																		# check that output_hidden_states also work using config
																		del inputs_dict["output_hidden_states"]
																		lowerCAmelCase =		True

																		check_hidden_states_output(UpperCAmelCase_							,			UpperCAmelCase_							,			UpperCAmelCase_    )



				def    __snake_case		(			self    ):
											lowerCAmelCase ,  lowerCAmelCase =		self.model_tester.prepare_config_and_inputs_for_common()

											def check_equivalence(UpperCAmelCase_							,			UpperCAmelCase_							,			UpperCAmelCase_							,			UpperCAmelCase_={}    ):
																		lowerCAmelCase =		model(UpperCAmelCase_							,			return_dict=UpperCAmelCase_							,			**UpperCAmelCase_    )
																		lowerCAmelCase =		model(UpperCAmelCase_							,			return_dict=UpperCAmelCase_							,			**UpperCAmelCase_    ).to_tuple()

																		def recursive_check(UpperCAmelCase_							,			UpperCAmelCase_    ):
																									if isinstance(UpperCAmelCase_							,			(List, Tuple)    ):
																																for tuple_iterable_value, dict_iterable_value in zip(UpperCAmelCase_							,			UpperCAmelCase_    ):
																																							recursive_check(UpperCAmelCase_							,			UpperCAmelCase_    )
																									elif tuple_object is None:
																																return
																									else:
																																self.assertTrue(
																																    all(tf.equal(UpperCAmelCase_							,			UpperCAmelCase_    )    )							,			msg=(
																																        '''Tuple and dict output are not equal. Difference:'''
																																        F""" {tf.math.reduce_max(tf.abs(tuple_object - dict_object    )    )}"""
																																    )							,			)

																									recursive_check(UpperCAmelCase_							,			UpperCAmelCase_    )

											for model_class in self.all_model_classes:
																		lowerCAmelCase =		model_class(UpperCAmelCase_    )

																		lowerCAmelCase =		self._prepare_for_class(UpperCAmelCase_							,			UpperCAmelCase_    )
																		lowerCAmelCase =		self._prepare_for_class(UpperCAmelCase_							,			UpperCAmelCase_    )
																		check_equivalence(UpperCAmelCase_							,			UpperCAmelCase_							,			UpperCAmelCase_    )

																		lowerCAmelCase =		self._prepare_for_class(UpperCAmelCase_							,			UpperCAmelCase_							,			return_labels=UpperCAmelCase_    )
																		lowerCAmelCase =		self._prepare_for_class(UpperCAmelCase_							,			UpperCAmelCase_							,			return_labels=UpperCAmelCase_    )
																		check_equivalence(UpperCAmelCase_							,			UpperCAmelCase_							,			UpperCAmelCase_    )

																		lowerCAmelCase =		self._prepare_for_class(UpperCAmelCase_							,			UpperCAmelCase_    )
																		lowerCAmelCase =		self._prepare_for_class(UpperCAmelCase_							,			UpperCAmelCase_    )
																		check_equivalence(UpperCAmelCase_							,			UpperCAmelCase_							,			UpperCAmelCase_							,			{'''output_hidden_states''': True}    )

																		lowerCAmelCase =		self._prepare_for_class(UpperCAmelCase_							,			UpperCAmelCase_							,			return_labels=UpperCAmelCase_    )
																		lowerCAmelCase =		self._prepare_for_class(UpperCAmelCase_							,			UpperCAmelCase_							,			return_labels=UpperCAmelCase_    )
																		check_equivalence(UpperCAmelCase_							,			UpperCAmelCase_							,			UpperCAmelCase_							,			{'''output_hidden_states''': True}    )



				def    __snake_case		(			self    ):
											lowerCAmelCase =		self.model_tester.prepare_config_and_inputs()
											self.model_tester.create_and_check_for_image_classification(*UpperCAmelCase_    )






				@slow
				def    __snake_case		(			self    ):
											lowerCAmelCase =		TFConvNextModel.from_pretrained('''facebook/convnext-tiny-224'''    )
											self.assertIsNotNone(UpperCAmelCase_    )




def    UpperCAmelCase							(  ):
							lowerCAmelCase =		Image.open('''./tests/fixtures/tests_samples/COCO/000000039769.png'''				)
							return image


@require_tf
@require_vision
class 				__UpperCamelCase      (			unittest.TestCase	):





				'''simple docstring'''



				@cached_property
				def    __snake_case		(			self    ):
											return ConvNextImageProcessor.from_pretrained('''facebook/convnext-tiny-224'''    ) if is_vision_available() else None






				@slow
				def    __snake_case		(			self    ):
											lowerCAmelCase =		TFConvNextForImageClassification.from_pretrained('''facebook/convnext-tiny-224'''    )

											lowerCAmelCase =		self.default_image_processor
											lowerCAmelCase =		prepare_img()
											lowerCAmelCase =		image_processor(images=UpperCAmelCase_							,			return_tensors='''tf'''    )

											# forward pass
											lowerCAmelCase =		model(**UpperCAmelCase_    )

											# verify the logits
											lowerCAmelCase =		tf.TensorShape((1, 10_00)    )
											self.assertEqual(outputs.logits.shape							,			UpperCAmelCase_    )

											lowerCAmelCase =		tf.constant([-0.0260, -0.4739, 0.1911]    )

											tf.debugging.assert_near(outputs.logits[0, :3]							,			UpperCAmelCase_							,			atol=1E-4    )



